diff --git a/README.md b/README.md index bd058fb9d2ccf7540b85e3ac16f92115a43f3c0e..a368dfe296d0693f33b032977d1cbc2b4848205d 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,14 @@ TypeScript, Java, Rust, Go, Python, .NET and Swift. The language strip on the page links to each runtime source and marks TypeScript as the runtime currently executing in the browser. +The new development-process section links directly to the canonical +[`order-model.xml`](https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml) +and the model-aware Assist files. It shows the actual path from domain model to +generated typed APIs, one bounded Q request, runtime execution, TraceChain and +the SQL SQLite/WASM executed. It also explains how progressive entity, action +and field Assist reduces repeated context use without claiming an unmeasured +percentage. + The final section preserves an unmodified OpenObserve dashboard capture of the Order-query business TraceChain. It shows the page purpose and nested request comments connected to the eight SQL executions captured by the observability @@ -56,7 +64,7 @@ cross-origin isolation. The exact runtime, tests, model, generated Order library and browser application source are retained under [`source/teaql-ts`](./source/teaql-ts). They correspond to -TeaQL TypeScript commit `1e1f50e7a54f2f47753a24cdd988e53fbde78180` on `main`. +TeaQL TypeScript commit `b7c0f71f717d368c222da7cc8484db32bf281f11` on `main`. ```bash cd source/teaql-ts @@ -71,8 +79,10 @@ npm run smoke npm run smoke:orders ``` -The validated runtime result was 57 passing suites and 608 passing tests, with six -tests skipped by the repository configuration. Both real-browser smoke suites pass. +For this release, the TypeScript runtime build and the browser application build +passed. Both real-browser smoke suites also pass, including the generated-library +hash gate. Earlier aggregate test counts were removed because they described an +older source snapshot. Learn more at [teaql.io](https://teaql.io/) and inspect the upstream source at [github.com/teaql/teaql-ts](https://github.com/teaql/teaql-ts). diff --git a/assets/dynamic-search-BwvXmN4R.js b/assets/dynamic-search-BwvXmN4R.js new file mode 100644 index 0000000000000000000000000000000000000000..13a6d3c917f969f76b204b94860f0d531a45230a --- /dev/null +++ b/assets/dynamic-search-BwvXmN4R.js @@ -0,0 +1,13 @@ +var Ct=n=>{throw TypeError(n)};var $t=(n,e,t)=>e.has(n)||Ct("Cannot "+t);var x=(n,e,t)=>($t(n,e,"read from private field"),t?t.call(n):e.get(n)),Pe=(n,e,t)=>e.has(n)?Ct("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),_e=(n,e,t,i)=>($t(n,e,"write to private field"),i?i.call(n,t):e.set(n,t),t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();const Zi=/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/,en=1024;function ue(n){if(typeof n!="string"||!Zi.test(n)||n.length-Number(n.startsWith("-"))-Number(n.includes("."))>en)throw new TypeError('Decimal requires a finite base-10 string (for example "3.50")');return n}const tn=/^-?(?:0|[1-9][0-9]*)$/,nn=-(1n<<63n),rn=(1n<<63n)-1n;function be(n){if(typeof n!="string"&&typeof n!="bigint")throw new TypeError("Long requires a signed 64-bit integer string or bigint");const e=String(n);if(!tn.test(e))throw new TypeError("Long requires a canonical integer string");const t=BigInt(e);if(trn)throw new RangeError("Long is outside signed 64-bit range");return t.toString()}const sn=/^(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]{1,6})?$/;function Ce(n){if(typeof n!="string"||!sn.test(n))throw new TypeError("LocalTime requires HH:mm:ss with optional 1-6 fractional digits");const e=n.indexOf(".");if(e<0)return n;const t=n.slice(e+1).padEnd(6,"0");return t==="000000"?n.slice(0,e):`${n.slice(0,e)}.${t}`}const on="modulepreload",an=function(n){return"/"+n},Nt={},cn=function(e,t,i){let r=Promise.resolve();if(t&&t.length>0){let c=function(u){return Promise.all(u.map(l=>Promise.resolve(l).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");r=c(t.map(u=>{if(u=an(u),u in Nt)return;Nt[u]=!0;const l=u.endsWith(".css"),d=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=l?"stylesheet":on,l||(h.as="script"),h.crossOrigin="",h.href=u,a&&h.setAttribute("nonce",a),document.head.appendChild(h),l)return new Promise((f,p)=>{h.addEventListener("load",f),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return r.then(s=>{for(const a of s||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function ln(n){const e=n instanceof Error&&n.constructor?.name?n.constructor.name.toLowerCase():typeof n;return/timeout|deadline/.test(e)?"timeout":/authentication|authorization|unauthorized|forbidden|permission/.test(e)?"authorization":/validation|invalidargument|valueerror|parse|format/.test(e)?"validation":/conflict|optimistic|version|duplicate|alreadyexists/.test(e)?"conflict":/transport|network|connection|socket|http|ioerror/.test(e)?"transport":/provider|sql|database|jdbc/.test(e)?"provider":"internal"}const xt=Object.freeze({success:()=>{},failure:()=>{}}),un=new Set(["teaql.entity.id","teaql.user.id","teaql.tenant.id","teaql.query.parameters","teaql.field.values","teaql.audit.reason","db.query.parameter_values","http.request.body","url.full"]);function dn(n){const e={"teaql.operation.family":n.family,"teaql.operation.name":n.name};for(const[t,i]of Object.entries(n.attributes||{}))un.has(t)||(e[t]=i);return Object.freeze({...n,attributes:Object.freeze(e)})}function H(n,e){if(!n)return xt;try{const t=n.start(dn(e));let i=!1;return{correlation:()=>{try{return t.correlation?.()}catch{return}},run:t.run?r=>t.run(r):r=>r(),success(r){if(!i){i=!0;try{t?.success(r)}catch{}}},failure(r){if(!i){i=!0;try{t?.failure(r)}catch{}}}}}catch{return xt}}async function me(n,e,t,i){const r=H(n,e);try{const o=await(r.run?r.run(t):t());return r.success(i?.(o)),o}catch(o){throw r.failure(o),o}}const xe=class xe extends Error{constructor(e){super(`Check failed: ${e.map(i=>i.message??`${i.ruleId}:${i.location}`).join("; ")}`),this.violations=e,this.name="CheckException";const t=[...e];Object.defineProperty(this,"violations",{value:t,enumerable:!0}),xe.owned.set(this,t)}refreshPresentation(e){const t=xe.owned.get(this);t&&(e.length===t.length&&e.every((i,r)=>i.message===t[r].message)||(t.splice(0,t.length,...e),this.message=`Check failed: ${e.map(i=>i.message??`${i.ruleId}:${i.location}`).join("; ")}`))}};xe.owned=new WeakMap;let G=xe;function hi(n){const e=n.split("_");return e[0]+e.slice(1).map(t=>t?t[0].toUpperCase()+t.slice(1):"").join("")}function hn(n,e){if(e==="snake_case")return n;const t=hi(n);return e==="camelCase"||!t?t:t[0].toUpperCase()+t.slice(1)}function fn(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class F{constructor(e){this.segments=e}static root(){return new F([])}static property(e){return F.root().property(e)}property(e){return new F([...this.segments,{kind:"property",name:e}])}index(e){return new F([...this.segments,{kind:"index",index:e}])}prefixedBy(e){return new F([...e.segments,...this.segments])}modelPath(){return this.render(e=>e)}nativePath(){return this.render(hi)}instancePath(e="camelCase"){return this.segments.map(t=>t.kind==="index"?String(t.index):fn(hn(t.name,e))).map(t=>`/${t}`).join("")}toString(){return this.nativePath()}render(e){let t="";for(const i of this.segments)i.kind==="index"?t+=`[${i.index}]`:t+=`${t?".":""}${e(i.name)}`;return t}}const fi=-(1n<<63n),pi=(1n<<63n)-1n,qt=BigInt(Number.MAX_SAFE_INTEGER);class X extends G{constructor(e,t="mutation"){super([{ruleId:e,location:F.property("version"),message:e==="version_exhausted"?`${t} version is exhausted in the signed 64-bit domain`:`${t} requires an exact version in its permitted lifecycle state`}]),this.code=e,this.name="MutationVersionError"}}function M(n){let e;if(typeof n=="bigint")e=n;else if(typeof n=="number"&&Number.isSafeInteger(n))e=BigInt(n);else if(typeof n=="string"&&/^(?:0|-?[1-9][0-9]*)$/.test(n))e=BigInt(n);else throw new X("invalid_type");if(epi)throw new X("invalid_type");return e>=-qt&&e<=qt?Number(e):be(e)}function ct(n,e){if(n==="Create")return 1;const t=BigInt(M(e));let i;switch(n){case"Update":if(t<=0n)throw new X("invalid_type",n);i=t+1n;break;case"Delete":if(t<=0n)throw new X("invalid_type",n);i=-t-1n;break;case"Recover":if(t>=0n)throw new X("invalid_type",n);i=-t+1n;break;default:throw new X("invalid_type")}if(ipi)throw new X("version_exhausted",n);return M(i)}const qe=new WeakMap,He=new WeakMap;function Mt(n){return He.get(n)}function pn(n,e){He.set(n,e)}function mn(n){return qe.get(n)}function je(n,e){qe.set(e,qe.get(n)??N(n))}function N(n,e=new Map){if(!n||typeof n!="object")return n;if(e.has(n))return e.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof Uint8Array)return new Uint8Array(n);const t=Array.isArray(n)?[]:Object.create(Object.getPrototypeOf(n));e.set(n,t);for(const o of Reflect.ownKeys(n)){const s=Object.getOwnPropertyDescriptor(n,o);"value"in s&&s.enumerable&&(s.value=N(s.value,e)),Object.defineProperty(t,o,s)}const i=qe.get(n);i&&qe.set(t,i);const r=He.get(n);return r&&He.set(t,r),t}function B(n){return Object.freeze(n.map(e=>Object.freeze({...e})))}class gn{#e;#t;constructor(e,t){this.#e=e,this.#t=Object.freeze({...t}),Object.freeze(this)}recover(){const e=[];let t=this;for(;t;)e.push(t.#t),t=t.#e;return B(e.reverse())}}function yn(n,e,t,i,r){const o=n?r:i;if(n&&(typeof o!="string"||new RegExp("^\\p{White_Space}*$","u").test(o)))return n;const s=String(t),a=/^(0|[1-9][0-9]*)$/.test(s)&&BigInt(s)<=18446744073709551615n?t:void 0;return new gn(n,{kind:"auditReason",name:e,entityId:a,detail:o})}const bn=new Set(["comment","purpose","auditReason"]),lt=n=>!new RegExp("^\\p{White_Space}*$","u").test(n);function gt(n,e,t){const i=s=>{for(let a=n.length-1;a>=0;a--)if(n[a].kind===s)return n[a].detail??""},r=["operation","provider","sql"].every(s=>n.some(a=>a.kind===s));let o;if(r)o=n.filter(s=>!bn.has(s.kind));else{const s=n.find(c=>lt(c.name))?.name??"unknown";let a=s;if(t!=="select")for(const c of n)c.kind==="entity"&<(c.name)&&(a=c.name);o=[{kind:"operation",name:s,detail:t==="select"?"query":"mutation"},{kind:t==="select"?"request":"entity",name:t==="select"?s:a,detail:""},...n.filter(c=>c.kind==="relation"),{kind:"provider",name:lt(e)?e:"unknown",detail:""},{kind:"sql",name:t,detail:""}]}return Object.freeze({tracePath:B(o),comment:i("comment"),purpose:i("purpose"),auditReason:i("auditReason")})}function mi(n,e,t){return B([{kind:"comment",name:n,detail:e},{kind:"purpose",name:n,detail:t}])}const C=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class wn{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(e,t){this.traces.set(C(e),{key:Object.freeze({...e}),nodes:B(t)})}traceChain(e){return this.traces.get(C(e))?.nodes}set(e,t,i){if(!t.trim())throw new TypeError("field is required");const r=C(e),o=this.changes.get(r)??{key:Object.freeze({...e}),values:Object.create(null)};o.values[t]=i,this.changes.set(r,o)}snapshot(){return[...this.changes.values()].map(e=>({key:Object.freeze({...e.key}),values:Object.freeze({...e.values})}))}change(e){return Object.freeze({...this.changes.get(C(e))?.values??{}})}captureFields(e,t){const i=C(e),r=this.changes.get(i)?.values??{},o=new Map(t.map(s=>[s,{present:Object.prototype.hasOwnProperty.call(r,s),value:N(r[s])}]));return()=>{const s=this.changes.get(i)??{key:Object.freeze({...e}),values:Object.create(null)};for(const[a,c]of o)c.present?s.values[a]=N(c.value):delete s.values[a];Object.keys(s.values).length?this.changes.set(i,s):this.changes.delete(i)}}discardFields(e,t){const i=C(e),r=this.changes.get(i);if(r){for(const[o,s]of Object.entries(t))Object.prototype.hasOwnProperty.call(r.values,o)&&Object.is(r.values[o],s)&&delete r.values[o];Object.keys(r.values).length||this.changes.delete(i)}}mergeFrom(e){if(e!==this){for(const t of e.snapshotVersions())this.requireMatchingVersion(t.key,t.version);for(const t of e.snapshot())for(const[i,r]of Object.entries(t.values))this.set(t.key,i,r);for(const t of e.newKeys.values())this.markAsNew(t);for(const t of e.deletedKeys.values())this.markAsDeleted(t);for(const t of e.snapshotVersions())this.setOriginalVersion(t.key,t.version);for(const t of e.traces.values())this.setTraceChain(t.key,t.nodes)}}mergeEntityFrom(e,t){if(e===this)return;const i=e.originalVersion(t);i!==void 0&&this.requireMatchingVersion(t,i);for(const[o,s]of Object.entries(e.change(t)))this.set(t,o,s);e.isNew(t)&&this.markAsNew(t),e.isDeleted(t)&&this.markAsDeleted(t),i!==void 0&&this.setOriginalVersion(t,i);const r=e.traceChain(t);r&&this.setTraceChain(t,r)}hasPending(e){const t=C(e);return this.newKeys.has(t)||this.deletedKeys.has(t)||Object.keys(this.changes.get(t)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(e,t){const i=C(e),r=C(t);if(i===r)return;const o=this.originalVersion(e);o!==void 0&&this.requireMatchingVersion(t,o);const s=this.changes.get(i);if(s){this.changes.delete(i);for(const[u,l]of Object.entries(s.values))this.set(t,u,l)}const a=this.originalVersions.get(i);a!==void 0&&(this.originalVersions.delete(i),this.originalVersions.set(r,{key:Object.freeze({...t}),version:a.version})),this.newKeys.delete(i)&&this.newKeys.set(r,Object.freeze({...t})),this.deletedKeys.delete(i)&&this.deletedKeys.set(r,Object.freeze({...t}));const c=this.traces.get(i);c&&(this.traces.delete(i),this.setTraceChain(t,c.nodes))}clearEntity(e){const t=C(e);this.changes.delete(t),this.newKeys.delete(t),this.deletedKeys.delete(t),this.traces.delete(t)}requireMatchingVersion(e,t){const i=this.originalVersion(e);if(i!==void 0&&i!==t)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(e,t){const i=M(t);this.requireMatchingVersion(e,i),this.originalVersions.set(C(e),{key:Object.freeze({...e}),version:i})}acceptCommittedVersion(e,t){const i=M(t);if(this.hasPending(e))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(C(e),{key:Object.freeze({...e}),version:i})}originalVersion(e){return this.originalVersions.get(C(e))?.version}markAsNew(e){this.newKeys.set(C(e),Object.freeze({...e}))}isNew(e){return this.newKeys.has(C(e))}markAsDeleted(e){const t=C(e);this.changes.delete(t),this.deletedKeys.set(t,Object.freeze({...e}))}isDeleted(e){return this.deletedKeys.has(C(e))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}const Ve=new WeakMap;class Ue extends G{constructor(e){super([{ruleId:"entity_version_conflict",location:F.property(e),message:"ENTITY_VERSION_CONFLICT: loaded entity identity must remain unchanged"}]),this.code="ENTITY_VERSION_CONFLICT",this.name="LoadedEntityIdentityError"}}class ${#e;#t;#n;#r;#i;constructor(e={},t,i,r="hydrated"){if(this.#e=N(e),this.#r=r,r==="hydrated"&&t&&i!==void 0){const o=M(i);this.#i=o,o!==0&&(e.id!==void 0&&(this.#n=Object.freeze({...t})),this.#t=Object.freeze({key:Object.freeze({...t}),version:o}))}!this.#n&&t&&e.id!==void 0&&(this.#n=Object.freeze({...t})),Object.freeze(this)}values(){return N(this.#e)}get origin(){return this.#r}get persistedVersion(){return this.#i}changedField(e){return[...new Set([...Object.keys(this.#e),...Object.keys(e)])].sort().find(i=>!Object.prototype.hasOwnProperty.call(this.#e,i)||!Object.prototype.hasOwnProperty.call(e,i)||!yt(this.#e[i],e[i]))}validateNativeIdentity(e,t,i){const r=this.#n;if(r&&(r.entity!==e.entity||!Object.is(r.id,e.id)||!Object.is(r.id,t)))throw new Ue("id");if(this.#t){let o;try{o=M(i)}catch{throw new Ue("version")}if(o!==this.#t.version)throw new Ue("version")}}validateMutationVersion(e,t){if(!(!this.#t||!e.hasPending(t))&&(this.#t.key.entity!==t.entity||!Object.is(this.#t.key.id,t.id)||e.isNew(t)||e.originalVersion(t)!==this.#t.version))throw new Ue("version")}static captureFor(e,t,i,r,o="hydrated"){const s=new $(t,i,r,o);return Ve.set(e,s),s}static forEntity(e){return Ve.get(e)}static restoreFor(e,t){t?Ve.set(e,t):Ve.delete(e)}discardRestoredFields(e,t,i){const r=this.#t;if(!r||r.key.entity!==t.entity||!Object.is(r.key.id,t.id)||e.originalVersion(t)!==r.version||e.isNew(t)||e.isDeleted(t))return;const o=Object.create(null);for(const[s,a]of Object.entries(e.change(t))){const c=Object.getOwnPropertyDescriptor(this.#e,s);s!=="id"&&s!=="version"&&c&&"value"in c&&c.value!==void 0&&yt(c.value,a)&&(o[s]=a)}e.discardFields(t,o),Object.keys(o).length&&i?.(N(o))}}function yt(n,e,t={nodes:4096},i=0){if(--t.nodes<0||i>64||typeof n!=typeof e)return!1;if(typeof n=="number")return Number.isFinite(n)&&Number.isFinite(e)&&Object.is(n,e);if(n===null||e===null||typeof n!="object")return Object.is(n,e);if(n instanceof Date||e instanceof Date)return n instanceof Date&&e instanceof Date&&Number.isFinite(n.getTime())&&n.getTime()===e.getTime();if(n instanceof Uint8Array||e instanceof Uint8Array)return n instanceof Uint8Array&&e instanceof Uint8Array&&n.length===e.length&&n.every((a,c)=>a===e[c]);if(Array.isArray(n)!==Array.isArray(e)||!Array.isArray(n)&&(Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)||Array.isArray(n)&&n.length!==e.length)return!1;const r=Object.getOwnPropertyDescriptors(n),o=Object.getOwnPropertyDescriptors(e),s=Object.keys(r).filter(a=>r[a].enumerable);return s.length!==Object.keys(o).filter(a=>o[a].enumerable).length?!1:s.every(a=>Object.prototype.hasOwnProperty.call(o,a)&&o[a].enumerable&&"value"in r[a]&&"value"in o[a]&&yt(r[a].value,o[a].value,t,i+1))}const Ae=new WeakMap;class Dt{static run(e,t,i,r){const o=new Map(Object.entries(i?.columns??{}).map(([l,d])=>[d.modelName??l,{...d}])),s=()=>t.action==="Create"||t.action==="Update"&&Object.entries(t.payload??{}).some(([l,d])=>{if(l==="id"||l==="version"||l.startsWith("_"))return!1;const h=o.get(l);return h?.createFunction||h?.updateFunction?!1:Object.prototype.hasOwnProperty.call(t.loadedValues??{},l)?new $({[l]:t.loadedValues[l]}).changedField({[l]:d})!==void 0:!0}),a=s(),c=[...o].filter(([,l])=>l.createFunction||l.updateFunction).map(([l])=>({field:l,present:Object.prototype.hasOwnProperty.call(t.payload??{},l),value:N(t.payload?.[l])})),u=Ae.get(t);Ae.set(t,{context:e,eligible:a,columns:o,now:e.getResource("fixTime")});try{const l=r();if(t.action==="Update"&&!s())for(const d of c)d.present?t.payload[d.field]=N(d.value):delete t.payload[d.field];return l}finally{u?Ae.set(t,u):Ae.delete(t)}}static apply(e,t,i,r,o=[]){const s=Ae.get(t),a=()=>new G([{ruleId:"invalid_type",entityType:String(t.entity),location:F.property(i),message:`Context Fix failed at ${t.entity}.${i}`}]);if(!s||s.context!==e)throw a();if(!s.eligible)return;const c=s.columns.get(i),u=t.action==="Create"?c?.createFunction:c?.updateFunction;if(!c||!u||u!==r)throw a();try{const l=e.getResource("contextFixResolver");let d;if(l)d=l(e,Object.freeze({entity:String(t.entity),field:i,function:r,arguments:Object.freeze([...o]),action:t.action,now:new Date(s.now.getTime())}));else if(r==="now")d=new Date(s.now.getTime());else if(r==="uniStr"){const h=new Uint8Array(16);globalThis.crypto.getRandomValues(h),d=(o[0]??"")+Array.from(h,f=>f.toString(16).padStart(2,"0")).join("")}else throw a();if(d instanceof Promise)throw d.catch(()=>{}),a();if(!this.validValue(c,d))throw a();t.payload[i]=N(d),e.recordFixEvidence({entityType:String(t.entity),modelPath:i,source:r==="now"?"clock":"context",sourceLabel:r==="now"?"graphClock":`contextFunction:${r}`})}catch{throw a()}}static captureUndo(e,t){if(!(e.ledgerRoot instanceof wn)||!e.ledgerKey)return;const i=Object.entries(t?.columns??{}).filter(([,r])=>r.createFunction||r.updateFunction).map(([r,o])=>o.modelName??r);return i.length?e.ledgerRoot.captureFields(e.ledgerKey,i):void 0}static validValue(e,t){if(t===null)return!0;switch(e.logicalType){case"text":return typeof t=="string";case"datetime":case"date":return t instanceof Date&&Number.isFinite(t.getTime());case"boolean":return typeof t=="boolean";case"double":return typeof t=="number"&&Number.isFinite(t);case"integer":return typeof t=="number"&&Number.isSafeInteger(t);case"decimal":return typeof t=="string"&&ue(t)===t;case"long":return typeof t=="string"&&be(t)===t;case"time":return typeof t=="string"&&Ce(t)===t;case"json":return t!==void 0&&!(t instanceof Promise);default:return!1}}}var vn={};const Sn="TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS",En="I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK",bt="[REDACTED]";let Ft=!1;function On(n){const e=Array.from(n);return e.length<8||/^[0-9]+$/.test(n)?"*".repeat(e.length):e.slice(0,2).join("")+"*".repeat(e.length-4)+e.slice(-2).join("")}function gi(){const e=vn?.[Sn]===En;return e&&!Ft&&(Ft=!0,console.warn("TeaQL: sensitive plaintext logging enabled; application data may be written to disk. Authentication secrets remain redacted.")),e}function fe(n){const e=n.toLowerCase().replace(/[^a-z0-9]/g,"");return["password","passwd","passphrase","privatekey","secret","accesstoken","refreshtoken","idtoken","apikey","authorization","credential","sessiontoken","magiclinktoken"].some(t=>e.includes(t))}function ot(n){return!!n&&typeof n=="object"&&wt(n,new WeakSet)}function wt(n,e){if(!n||typeof n!="object"||e.has(n))return!1;e.add(n);try{return Array.isArray(n)?n.some(t=>wt(t,e)):Object.entries(n).some(([t,i])=>fe(t)||wt(i,e))}finally{e.delete(n)}}function J(n){return n==null||n===""?[]:typeof n=="object"?vt(n,new WeakSet):[String(n)]}function vt(n,e){if(n==null||n==="")return[];if(typeof n=="object"){if(e.has(n))return[];e.add(n);try{return Array.isArray(n)?n.flatMap(t=>vt(t,e)):n instanceof Date?[n.toISOString()]:Object.values(n).flatMap(t=>vt(t,e))}finally{e.delete(n)}}return[String(n)]}function re(n,e){return[...new Set(e)].sort((t,i)=>i.length-t.length).reduce((t,i)=>t?.split(i).join(bt),n)}function Xe(n,e=new WeakSet){if(n==null)return null;if(typeof n=="object"){if(e.has(n))return bt;e.add(n);try{if(Array.isArray(n))return n.map(t=>Xe(t,e));if("type"in n)return Xe(n.value,e);if(!(n instanceof Date))return bt}finally{e.delete(n)}}return On(n instanceof Date?n.toISOString():String(n))}const yi=Symbol("TeaQL.CheckerPresentation"),bi=new WeakMap,we=new WeakMap,at=n=>{const e=n[yi];return e&&bi.get(e)};function St(n,e){const t=Object.freeze({});bi.set(t,e),Object.defineProperty(n,yi,{value:t,enumerable:!0,configurable:!0})}function _t(n){const e=at(n);return e?.masked&&Object.is(e.value,n.inputValue)&&e.length!==void 0?e.length:typeof n.inputValue=="string"?Array.from(n.inputValue).length:0}function jn(n,e,t,i){const r=n.location.segments.filter(a=>a.kind==="property").map(a=>a.name),o=r[r.length-1]??"",s=t?.(n.entityType?.trim()?n.entityType:e,o);return r.some(fe)||s==="credential"||ot(n.inputValue)?"credential":!i&&(s==="masked"||o.startsWith("#"))?"masked":void 0}function kn(n,e){const t=n.systemValue;return t==null||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?t:e==="credential"||ot(t)?"[REDACTED]":t}function Tn(n){const e=Xe(n),t=i=>Array.isArray(i)?Object.freeze(i.map(t)):i;return t(e)}function zt(n,e,t,i){const r={...n},o=at(n),s=jn(n,e,t,i);e&&!r.entityType?.trim()&&(r.entityType=e);const a=o?.masked&&Object.is(o.value,n.inputValue)&&(o.kind==="credential"||s!=="credential");let c=n.inputValue;!a&&c!==null&&c!==void 0&&(s==="credential"?c="[REDACTED]":s==="masked"&&(c=Tn(c)));const u=kn(n,s),l=!Object.is(c,n.inputValue)||!Object.is(u,n.systemValue);Object.prototype.hasOwnProperty.call(n,"inputValue")&&(r.inputValue=c),Object.prototype.hasOwnProperty.call(n,"systemValue")&&(r.systemValue=u);const d=[...Object.is(c,n.inputValue)?[]:J(n.inputValue),...Object.is(u,n.systemValue)?[]:J(n.systemValue)],f=!!a||!Object.is(c,n.inputValue)?{masked:!0,value:c,length:_t(n),kind:a?o.kind:s}:{};return!l&&o?.message!==void 0&&o.message===n.message&&(f.message=o.message,f.automatic=o.automatic),{value:r,state:f,changed:l,secrets:d}}function Vt(n){return[...new Set(n.flatMap(e=>e?[e,JSON.stringify(e).slice(1,-1)]:[]))].sort((e,t)=>t.length-e.length)}function Ye(n,e,t,i=[]){const r=gi(),o=n.map(l=>zt(l,e,t,r)),s=n.flatMap(l=>we.get(l)?.redactions??[]),a=i.flatMap(l=>Object.entries(l).flatMap(([d,h])=>{const f=t?.(e,d);return fe(d)||ot(h)||f==="credential"||!r&&(f==="masked"||d.startsWith("#"))?J(h):[]})),c=Vt([...s,...a,...o.flatMap(l=>l.secrets)]),u=o.map(l=>(l.value.message!==void 0&&(l.value.message=re(l.value.message,c)),St(l.value,{...l.state,message:l.value.message}),we.set(l.value,{redactions:c,length:l.state.length??_t(l.value),input:l.value.inputValue,system:l.value.systemValue}),l.value));return{values:u,finish(l){const d=l.map(f=>zt(f,e,t,r)),h=Vt([...c,...d.flatMap(f=>f.secrets)]);return d.map(f=>(f.state.message===void 0&&(f.value.message=re(f.value.message,h)),St(f.value,{...f.state,message:f.value.message}),f.value))},close(){for(const l of u)we.delete(l)}}}function wi(n){return we.get(n)?.length??_t(n)}function Je(n,e){return re(e,we.get(n)?.redactions??[])??""}function vi(n){const e=we.get(n);e&&Object.is(e.input,n.inputValue)&&Object.is(e.system,n.systemValue)&&St(n,{...at(n),message:n.message,automatic:!0})}function Ln(n){const e=at(n);return e?.automatic===!0&&e.message===n.message}function Si(n,e,t,i,r=[]){if(!e.length){const s=n.translateCheckResults(e,t);if(!s.length)return;const a=Ye(s,t,i,r);try{e.splice(0,e.length,...a.finish(a.values))}finally{a.close()}return}const o=Ye(e,t,i,r);try{const s=n.translateCheckResults(o.values,t);e.splice(0,e.length,...o.finish(s))}finally{o.close()}}const In="teaql.i18n/v1",Pn="en",_n={en:{messages:{"checker.required":"The {location} is required","checker.min":"The {location} should be equal or greater than {system}, but input is {input}","checker.max":"The {location} should be equal or less than {system}, but input is {input}","checker.minLength":"The length of {location} should be equal or greater than {system}, but the length of {input} is {input_len}","checker.maxLength":"The length of {location} should be equal or less than {system}, but the length of {input} is {input_len}"},vocabulary:{}},"zh-CN":{messages:{"checker.required":"{location} 是必填项","checker.min":"{location} 应该大于等于 {system},但输入值为 {input}","checker.max":"{location} 应该小于等于 {system},但输入值为 {input}","checker.minLength":"{location} 的长度应大于等于 {system},但实际长度为 {input_len}","checker.maxLength":"{location} 的长度应小于等于 {system},但实际长度为 {input_len}"},vocabulary:{}},"zh-TW":{messages:{"checker.required":"{location} 是必填的","checker.min":"{location} 應該等於或大於 {system},但輸入為 {input}","checker.max":"{location} 應該等於或小於 {system},但輸入為 {input}","checker.minLength":"{location} 的長度應該等於或大於 {system},但 {input} 的長度是 {input_len}","checker.maxLength":"{location} 的長度應該等於或小於 {system},但 {input} 的長度是 {input_len}"},vocabulary:{}},ja:{messages:{"checker.required":"{location} は必須です","checker.min":"{location} は {system} 以上である必要があります。入力値は {input} です","checker.max":"{location} は {system} 以下である必要があります。入力値は {input} です","checker.minLength":"{location} の長さは {system} 以上である必要があります。実際の長さは {input_len} です","checker.maxLength":"{location} の長さは {system} 以下である必要があります。実際の長さは {input_len} です"},vocabulary:{}},ko:{messages:{"checker.required":"{location}은(는) 필수입니다","checker.min":"{location}은(는) {system} 이상이어야 하지만 입력값은 {input}입니다","checker.max":"{location}은(는) {system} 이하여야 하지만 입력값은 {input}입니다","checker.minLength":"{location}의 길이는 {system} 이상이어야 하지만 실제 길이는 {input_len}입니다","checker.maxLength":"{location}의 길이는 {system} 이하여야 하지만 실제 길이는 {input_len}입니다"},vocabulary:{}},de:{messages:{"checker.required":"{location} ist erforderlich","checker.min":"{location} muss mindestens {system} sein, aber die Eingabe ist {input}","checker.max":"{location} darf höchstens {system} sein, aber die Eingabe ist {input}","checker.minLength":"Die Länge von {location} muss mindestens {system} sein, ist aber {input_len}","checker.maxLength":"Die Länge von {location} darf höchstens {system} sein, ist aber {input_len}"},vocabulary:{}},fr:{messages:{"checker.required":"{location} est obligatoire","checker.min":"{location} doit être supérieur ou égal à {system}, mais la valeur saisie est {input}","checker.max":"{location} doit être inférieur ou égal à {system}, mais la valeur saisie est {input}","checker.minLength":"La longueur de {location} doit être supérieure ou égale à {system}, mais elle est {input_len}","checker.maxLength":"La longueur de {location} doit être inférieure ou égale à {system}, mais elle est {input_len}"},vocabulary:{}},es:{messages:{"checker.required":"{location} es requerido/a","checker.min":"{location} debe ser mayor o igual que {system}, pero el valor ingresado es {input}","checker.max":"{location} debe ser menor o igual que {system}, pero el valor ingresado es {input}","checker.minLength":"La longitud de {location} debe ser mayor o igual que {system}, pero es {input_len}","checker.maxLength":"La longitud de {location} debe ser menor o igual que {system}, pero es {input_len}"},vocabulary:{}},pt:{messages:{"checker.required":"{location} é obrigatório","checker.min":"{location} deve ser maior ou igual a {system}, mas a entrada é {input}","checker.max":"{location} deve ser menor ou igual a {system}, mas a entrada é {input}","checker.minLength":"O comprimento de {location} deve ser maior ou igual a {system}, mas é {input_len}","checker.maxLength":"O comprimento de {location} deve ser menor ou igual a {system}, mas é {input_len}"},vocabulary:{}},ar:{messages:{"checker.required":"{location} مطلوب","checker.min":"يجب أن يكون {location} مساويًا أو أكبر من {system}، لكن المُدخل هو {input}","checker.max":"يجب أن يكون {location} مساويًا أو أصغر من {system}، لكن المُدخل هو {input}","checker.minLength":"يجب أن يكون طول {location} مساويًا أو أكبر من {system}، لكن الطول هو {input_len}","checker.maxLength":"يجب أن يكون طول {location} مساويًا أو أصغر من {system}، لكن الطول هو {input_len}"},vocabulary:{}},th:{messages:{"checker.required":"{location} เป็นสิ่งจำเป็น","checker.min":"{location} ควรจะเท่ากับหรือมากกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.max":"{location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.minLength":"ความยาวของ {location} ควรจะเท่ากับหรือมากกว่า {system} แต่ความยาวคือ {input_len}","checker.maxLength":"ความยาวของ {location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ความยาวคือ {input_len}"},vocabulary:{}},id:{messages:{"checker.required":"{location} wajib diisi","checker.min":"{location} harus sama dengan atau lebih besar dari {system}, tetapi input adalah {input}","checker.max":"{location} harus sama dengan atau lebih kecil dari {system}, tetapi input adalah {input}","checker.minLength":"Panjang {location} harus sama dengan atau lebih besar dari {system}, tetapi panjangnya {input_len}","checker.maxLength":"Panjang {location} harus sama dengan atau lebih kecil dari {system}, tetapi panjangnya {input_len}"},vocabulary:{}},fil:{messages:{"checker.required":"Ang {location} ay kinakailangan","checker.min":"Ang {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang input ay {input}","checker.max":"Ang {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang input ay {input}","checker.minLength":"Ang haba ng {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang haba ay {input_len}","checker.maxLength":"Ang haba ng {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang haba ay {input_len}"},vocabulary:{}},uk:{messages:{"checker.required":"{location} є обов'язковим","checker.min":"{location} повинен бути рівним або більшим за {system}, але ввідне значення {input}","checker.max":"{location} повинен бути рівним або меншим за {system}, але ввідне значення {input}","checker.minLength":"Довжина {location} повинна бути рівною або більшою за {system}, але довжина становить {input_len}","checker.maxLength":"Довжина {location} повинна бути рівною або меншою за {system}, але довжина становить {input_len}"},vocabulary:{}},vi:{messages:{"checker.required":"{location} là bắt buộc","checker.min":"{location} phải lớn hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.max":"{location} phải nhỏ hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.minLength":"Độ dài của {location} phải lớn hơn hoặc bằng {system}, nhưng độ dài là {input_len}","checker.maxLength":"Độ dài của {location} phải nhỏ hơn hoặc bằng {system}, nhưng độ dài là {input_len}"},vocabulary:{}}},An={schema:In,defaultLocale:Pn,locales:_n},pe=["en","zh-CN","zh-TW","ja","ko","de","fr","es","pt","ar","th","id","fil","uk","vi"];class Ut extends Error{constructor(e){super(`Unsupported locale: ${e}`),this.localeCode=e}}const Rn={"en-us":"en","en-gb":"en",zh:"zh-CN","zh-hans":"zh-CN","zh-sg":"zh-CN",cn:"zh-CN","zh-hant":"zh-TW","zh-hk":"zh-TW","zh-mo":"zh-TW",tw:"zh-TW","ja-jp":"ja","ko-kr":"ko","de-de":"de","fr-fr":"fr","es-mx":"es","pt-br":"pt","pt-pt":"pt","ar-sa":"ar","th-th":"th","id-id":"id",tl:"fil","fil-ph":"fil","uk-ua":"uk","vi-vn":"vi"};function ke(n){if(typeof n!="string"||!n.trim())throw new Ut(n);const e=n.trim().replace(/_/g,"-").toLowerCase(),t=pe.find(r=>r.toLowerCase()===e);if(t)return t;const i=Rn[e];if(!i)throw new Ut(n);return i}const ye=class ye{constructor(e,t){if(this.data=e,this.fallback=t,e.schema!=="teaql.i18n/v1")throw new Error("Unsupported i18n schema");Object.keys(e.locales).forEach(ke)}message(e,t){return this.data.locales[e]?.messages[t]??this.fallback?.data.locales[e]?.messages[t]??this.data.locales.en?.messages[t]??this.fallback?.data.locales.en?.messages[t]??t}applicationMessage(e,t){return this===ye.builtin?void 0:this.data.locales[e]?.messages[t]}translate(e,t){const r={required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"}[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,o=this.message(t,r);if(o===r&&e.message?.trim())return e;const s=String(e.inputValue),a={"{location}":e.location.nativePath(),"{system}":String(e.systemValue),"{input}":s,"{input_len}":String(wi(e))},c=o===ye.builtin.message(t,r);return e.message=o.split(/(\{(?:location|system|input|input_len)\})/g).map(u=>Object.prototype.hasOwnProperty.call(a,u)?a[u]:c?u:Je(e,u)).join(""),vi(e),e}};ye.builtin=new ye(An);let $e=ye;const Cn="teaql.checker-messages/v1",$n="en",Nn=JSON.parse('{"en":{"rules":{"checker.required":{"one":"The {field} is required.","two":"The {field} of {object} is required.","deep":"The {field} is required.\\nLocation: {objectPath}"},"checker.min":{"one":"The {field} must be at least {system}.","two":"The {field} of {object} must be at least {system}.","deep":"The {field} must be at least {system}.\\nLocation: {objectPath}"},"checker.max":{"one":"The {field} must not exceed {system}.","two":"The {field} of {object} must not exceed {system}.","deep":"The {field} must not exceed {system}.\\nLocation: {objectPath}"},"checker.minLength":{"one":"The {field} must contain at least {system} {unit}; its current length is {input_len}.","two":"The {field} of {object} must contain at least {system} {unit}; its current length is {input_len}.","deep":"The {field} must contain at least {system} {unit}; its current length is {input_len}.\\nLocation: {objectPath}"},"checker.maxLength":{"one":"The {field} must not exceed {system} {unit}; its current length is {input_len}.","two":"The {field} of {object} must not exceed {system} {unit}; its current length is {input_len}.","deep":"The {field} must not exceed {system} {unit}; its current length is {input_len}.\\nLocation: {objectPath}"},"checker.invalid":{"one":"The {field} is invalid.","two":"The {field} of {object} is invalid.","deep":"The {field} is invalid.\\nLocation: {objectPath}"}},"locationPatterns":{"reference":"the {relation}","item":"the {ordinal} {relation}","separator":" → "}},"zh-CN":{"rules":{"checker.required":{"one":"请填写{field}。","two":"请填写{object}的{field}。","deep":"请填写{field}。\\n位置:{objectPath}"},"checker.min":{"one":"{field}不得小于{system}。","two":"{object}的{field}不得小于{system}。","deep":"{field}不得小于{system}。\\n位置:{objectPath}"},"checker.max":{"one":"{field}不得大于{system}。","two":"{object}的{field}不得大于{system}。","deep":"{field}不得大于{system}。\\n位置:{objectPath}"},"checker.minLength":{"one":"{field}至少需要{system}{unit},当前长度为{input_len}。","two":"{object}的{field}至少需要{system}{unit},当前长度为{input_len}。","deep":"{field}至少需要{system}{unit},当前长度为{input_len}。\\n位置:{objectPath}"},"checker.maxLength":{"one":"{field}最多允许{system}{unit},当前长度为{input_len}。","two":"{object}的{field}最多允许{system}{unit},当前长度为{input_len}。","deep":"{field}最多允许{system}{unit},当前长度为{input_len}。\\n位置:{objectPath}"},"checker.invalid":{"one":"{field}无效。","two":"{object}的{field}无效。","deep":"{field}无效。\\n位置:{objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"第{position}{classifier}{relation}","separator":" → "}},"zh-TW":{"rules":{"checker.required":{"one":"請填寫{field}。","two":"請填寫{object}的{field}。","deep":"請填寫{field}。\\n位置:{objectPath}"},"checker.min":{"one":"{field}不得小於{system}。","two":"{object}的{field}不得小於{system}。","deep":"{field}不得小於{system}。\\n位置:{objectPath}"},"checker.max":{"one":"{field}不得大於{system}。","two":"{object}的{field}不得大於{system}。","deep":"{field}不得大於{system}。\\n位置:{objectPath}"},"checker.minLength":{"one":"{field}至少需要{system}{unit},目前長度為{input_len}。","two":"{object}的{field}至少需要{system}{unit},目前長度為{input_len}。","deep":"{field}至少需要{system}{unit},目前長度為{input_len}。\\n位置:{objectPath}"},"checker.maxLength":{"one":"{field}最多允許{system}{unit},目前長度為{input_len}。","two":"{object}的{field}最多允許{system}{unit},目前長度為{input_len}。","deep":"{field}最多允許{system}{unit},目前長度為{input_len}。\\n位置:{objectPath}"},"checker.invalid":{"one":"{field}無效。","two":"{object}的{field}無效。","deep":"{field}無效。\\n位置:{objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"第{position}{classifier}{relation}","separator":" → "}},"ja":{"rules":{"checker.required":{"one":"{field}は必須です。","two":"{object}の{field}は必須です。","deep":"{field}は必須です。\\n場所: {objectPath}"},"checker.min":{"one":"{field}は{system}以上である必要があります。","two":"{object}の{field}は{system}以上である必要があります。","deep":"{field}は{system}以上である必要があります。\\n場所: {objectPath}"},"checker.max":{"one":"{field}は{system}以下である必要があります。","two":"{object}の{field}は{system}以下である必要があります。","deep":"{field}は{system}以下である必要があります。\\n場所: {objectPath}"},"checker.minLength":{"one":"{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。","two":"{object}の{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。","deep":"{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。\\n場所: {objectPath}"},"checker.maxLength":{"one":"{field}は最大{system}{unit}です。現在の長さは{input_len}です。","two":"{object}の{field}は最大{system}{unit}です。現在の長さは{input_len}です。","deep":"{field}は最大{system}{unit}です。現在の長さは{input_len}です。\\n場所: {objectPath}"},"checker.invalid":{"one":"{field}が無効です。","two":"{object}の{field}が無効です。","deep":"{field}が無効です。\\n場所: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{position}番目の{relation}","separator":" → "}},"ko":{"rules":{"checker.required":{"one":"{field} 항목은 필수입니다.","two":"{object}의 {field} 항목은 필수입니다.","deep":"{field} 항목은 필수입니다.\\n위치: {objectPath}"},"checker.min":{"one":"{field} 값은 {system} 이상이어야 합니다.","two":"{object}의 {field} 값은 {system} 이상이어야 합니다.","deep":"{field} 값은 {system} 이상이어야 합니다.\\n위치: {objectPath}"},"checker.max":{"one":"{field} 값은 {system} 이하여야 합니다.","two":"{object}의 {field} 값은 {system} 이하여야 합니다.","deep":"{field} 값은 {system} 이하여야 합니다.\\n위치: {objectPath}"},"checker.minLength":{"one":"{field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","two":"{object}의 {field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","deep":"{field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.\\n위치: {objectPath}"},"checker.maxLength":{"one":"{field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","two":"{object}의 {field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","deep":"{field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.\\n위치: {objectPath}"},"checker.invalid":{"one":"{field} 항목이 유효하지 않습니다.","two":"{object}의 {field} 항목이 유효하지 않습니다.","deep":"{field} 항목이 유효하지 않습니다.\\n위치: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{position}번째 {relation}","separator":" → "}},"de":{"rules":{"checker.required":{"one":"Das Feld {field} ist erforderlich.","two":"Das Feld {field} bei {object} ist erforderlich.","deep":"Das Feld {field} ist erforderlich.\\nPosition: {objectPath}"},"checker.min":{"one":"Das Feld {field} muss mindestens {system} betragen.","two":"Das Feld {field} bei {object} muss mindestens {system} betragen.","deep":"Das Feld {field} muss mindestens {system} betragen.\\nPosition: {objectPath}"},"checker.max":{"one":"Das Feld {field} darf höchstens {system} betragen.","two":"Das Feld {field} bei {object} darf höchstens {system} betragen.","deep":"Das Feld {field} darf höchstens {system} betragen.\\nPosition: {objectPath}"},"checker.minLength":{"one":"Das Feld {field} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","two":"Das Feld {field} bei {object} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","deep":"Das Feld {field} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.\\nPosition: {objectPath}"},"checker.maxLength":{"one":"Das Feld {field} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","two":"Das Feld {field} bei {object} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","deep":"Das Feld {field} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.\\nPosition: {objectPath}"},"checker.invalid":{"one":"Das Feld {field} ist ungültig.","two":"Das Feld {field} bei {object} ist ungültig.","deep":"Das Feld {field} ist ungültig.\\nPosition: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} Nr. {position}","separator":" → "}},"fr":{"rules":{"checker.required":{"one":"Le champ {field} est obligatoire.","two":"Le champ {field} de {object} est obligatoire.","deep":"Le champ {field} est obligatoire.\\nEmplacement: {objectPath}"},"checker.min":{"one":"Le champ {field} doit être au moins égal à {system}.","two":"Le champ {field} de {object} doit être au moins égal à {system}.","deep":"Le champ {field} doit être au moins égal à {system}.\\nEmplacement: {objectPath}"},"checker.max":{"one":"Le champ {field} ne doit pas dépasser {system}.","two":"Le champ {field} de {object} ne doit pas dépasser {system}.","deep":"Le champ {field} ne doit pas dépasser {system}.\\nEmplacement: {objectPath}"},"checker.minLength":{"one":"Le champ {field} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.","two":"Le champ {field} de {object} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.","deep":"Le champ {field} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.\\nEmplacement: {objectPath}"},"checker.maxLength":{"one":"Le champ {field} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.","two":"Le champ {field} de {object} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.","deep":"Le champ {field} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.\\nEmplacement: {objectPath}"},"checker.invalid":{"one":"Le champ {field} est invalide.","two":"Le champ {field} de {object} est invalide.","deep":"Le champ {field} est invalide.\\nEmplacement: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} n° {position}","separator":" → "}},"es":{"rules":{"checker.required":{"one":"El campo {field} es obligatorio.","two":"El campo {field} de {object} es obligatorio.","deep":"El campo {field} es obligatorio.\\nUbicación: {objectPath}"},"checker.min":{"one":"El campo {field} debe ser al menos {system}.","two":"El campo {field} de {object} debe ser al menos {system}.","deep":"El campo {field} debe ser al menos {system}.\\nUbicación: {objectPath}"},"checker.max":{"one":"El campo {field} no debe superar {system}.","two":"El campo {field} de {object} no debe superar {system}.","deep":"El campo {field} no debe superar {system}.\\nUbicación: {objectPath}"},"checker.minLength":{"one":"El campo {field} debe contener al menos {system} {unit}; su longitud actual es {input_len}.","two":"El campo {field} de {object} debe contener al menos {system} {unit}; su longitud actual es {input_len}.","deep":"El campo {field} debe contener al menos {system} {unit}; su longitud actual es {input_len}.\\nUbicación: {objectPath}"},"checker.maxLength":{"one":"El campo {field} no debe superar {system} {unit}; su longitud actual es {input_len}.","two":"El campo {field} de {object} no debe superar {system} {unit}; su longitud actual es {input_len}.","deep":"El campo {field} no debe superar {system} {unit}; su longitud actual es {input_len}.\\nUbicación: {objectPath}"},"checker.invalid":{"one":"El campo {field} no es válido.","two":"El campo {field} de {object} no es válido.","deep":"El campo {field} no es válido.\\nUbicación: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} n.º {position}","separator":" → "}},"pt":{"rules":{"checker.required":{"one":"O campo {field} é obrigatório.","two":"O campo {field} de {object} é obrigatório.","deep":"O campo {field} é obrigatório.\\nLocalização: {objectPath}"},"checker.min":{"one":"O campo {field} deve ser pelo menos {system}.","two":"O campo {field} de {object} deve ser pelo menos {system}.","deep":"O campo {field} deve ser pelo menos {system}.\\nLocalização: {objectPath}"},"checker.max":{"one":"O campo {field} não deve exceder {system}.","two":"O campo {field} de {object} não deve exceder {system}.","deep":"O campo {field} não deve exceder {system}.\\nLocalização: {objectPath}"},"checker.minLength":{"one":"O campo {field} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.","two":"O campo {field} de {object} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.","deep":"O campo {field} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.\\nLocalização: {objectPath}"},"checker.maxLength":{"one":"O campo {field} não deve exceder {system} {unit}; o comprimento atual é {input_len}.","two":"O campo {field} de {object} não deve exceder {system} {unit}; o comprimento atual é {input_len}.","deep":"O campo {field} não deve exceder {system} {unit}; o comprimento atual é {input_len}.\\nLocalização: {objectPath}"},"checker.invalid":{"one":"O campo {field} é inválido.","two":"O campo {field} de {object} é inválido.","deep":"O campo {field} é inválido.\\nLocalização: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} n.º {position}","separator":" → "}},"ar":{"rules":{"checker.required":{"one":"الحقل {field} مطلوب.","two":"الحقل {field} في {object} مطلوب.","deep":"الحقل {field} مطلوب.\\nالموقع: {objectPath}"},"checker.min":{"one":"يجب ألا تقل قيمة الحقل {field} عن {system}.","two":"يجب ألا تقل قيمة الحقل {field} في {object} عن {system}.","deep":"يجب ألا تقل قيمة الحقل {field} عن {system}.\\nالموقع: {objectPath}"},"checker.max":{"one":"يجب ألا تزيد قيمة الحقل {field} عن {system}.","two":"يجب ألا تزيد قيمة الحقل {field} في {object} عن {system}.","deep":"يجب ألا تزيد قيمة الحقل {field} عن {system}.\\nالموقع: {objectPath}"},"checker.minLength":{"one":"يجب ألا يقل طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.","two":"يجب ألا يقل طول الحقل {field} في {object} عن {system} {unit}؛ الطول الحالي هو {input_len}.","deep":"يجب ألا يقل طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.\\nالموقع: {objectPath}"},"checker.maxLength":{"one":"يجب ألا يزيد طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.","two":"يجب ألا يزيد طول الحقل {field} في {object} عن {system} {unit}؛ الطول الحالي هو {input_len}.","deep":"يجب ألا يزيد طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.\\nالموقع: {objectPath}"},"checker.invalid":{"one":"الحقل {field} غير صالح.","two":"الحقل {field} في {object} غير صالح.","deep":"الحقل {field} غير صالح.\\nالموقع: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} رقم {position}","separator":" → "}},"th":{"rules":{"checker.required":{"one":"ต้องระบุ{field}","two":"ต้องระบุ{field}ของ{object}","deep":"ต้องระบุ{field}\\nตำแหน่ง: {objectPath}"},"checker.min":{"one":"{field}ต้องมีค่าอย่างน้อย {system}","two":"{field}ของ{object}ต้องมีค่าอย่างน้อย {system}","deep":"{field}ต้องมีค่าอย่างน้อย {system}\\nตำแหน่ง: {objectPath}"},"checker.max":{"one":"{field}ต้องมีค่าไม่เกิน {system}","two":"{field}ของ{object}ต้องมีค่าไม่เกิน {system}","deep":"{field}ต้องมีค่าไม่เกิน {system}\\nตำแหน่ง: {objectPath}"},"checker.minLength":{"one":"{field}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}","two":"{field}ของ{object}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}","deep":"{field}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}\\nตำแหน่ง: {objectPath}"},"checker.maxLength":{"one":"{field}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}","two":"{field}ของ{object}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}","deep":"{field}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}\\nตำแหน่ง: {objectPath}"},"checker.invalid":{"one":"{field}ไม่ถูกต้อง","two":"{field}ของ{object}ไม่ถูกต้อง","deep":"{field}ไม่ถูกต้อง\\nตำแหน่ง: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation}ลำดับที่ {position}","separator":" → "}},"id":{"rules":{"checker.required":{"one":"Kolom {field} wajib diisi.","two":"Kolom {field} pada {object} wajib diisi.","deep":"Kolom {field} wajib diisi.\\nLokasi: {objectPath}"},"checker.min":{"one":"Nilai {field} minimal {system}.","two":"Nilai {field} pada {object} minimal {system}.","deep":"Nilai {field} minimal {system}.\\nLokasi: {objectPath}"},"checker.max":{"one":"Nilai {field} maksimal {system}.","two":"Nilai {field} pada {object} maksimal {system}.","deep":"Nilai {field} maksimal {system}.\\nLokasi: {objectPath}"},"checker.minLength":{"one":"Panjang {field} minimal {system} {unit}; panjang saat ini {input_len}.","two":"Panjang {field} pada {object} minimal {system} {unit}; panjang saat ini {input_len}.","deep":"Panjang {field} minimal {system} {unit}; panjang saat ini {input_len}.\\nLokasi: {objectPath}"},"checker.maxLength":{"one":"Panjang {field} maksimal {system} {unit}; panjang saat ini {input_len}.","two":"Panjang {field} pada {object} maksimal {system} {unit}; panjang saat ini {input_len}.","deep":"Panjang {field} maksimal {system} {unit}; panjang saat ini {input_len}.\\nLokasi: {objectPath}"},"checker.invalid":{"one":"Kolom {field} tidak valid.","two":"Kolom {field} pada {object} tidak valid.","deep":"Kolom {field} tidak valid.\\nLokasi: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} ke-{position}","separator":" → "}},"fil":{"rules":{"checker.required":{"one":"Kinakailangan ang {field}.","two":"Kinakailangan ang {field} ng {object}.","deep":"Kinakailangan ang {field}.\\nLokasyon: {objectPath}"},"checker.min":{"one":"Ang {field} ay dapat hindi bababa sa {system}.","two":"Ang {field} ng {object} ay dapat hindi bababa sa {system}.","deep":"Ang {field} ay dapat hindi bababa sa {system}.\\nLokasyon: {objectPath}"},"checker.max":{"one":"Ang {field} ay dapat hindi lumampas sa {system}.","two":"Ang {field} ng {object} ay dapat hindi lumampas sa {system}.","deep":"Ang {field} ay dapat hindi lumampas sa {system}.\\nLokasyon: {objectPath}"},"checker.minLength":{"one":"Ang {field} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","two":"Ang {field} ng {object} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","deep":"Ang {field} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.\\nLokasyon: {objectPath}"},"checker.maxLength":{"one":"Ang {field} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","two":"Ang {field} ng {object} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","deep":"Ang {field} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.\\nLokasyon: {objectPath}"},"checker.invalid":{"one":"Hindi wasto ang {field}.","two":"Hindi wasto ang {field} ng {object}.","deep":"Hindi wasto ang {field}.\\nLokasyon: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} bilang {position}","separator":" → "}},"uk":{"rules":{"checker.required":{"one":"Поле {field} є обов’язковим.","two":"Поле {field} для {object} є обов’язковим.","deep":"Поле {field} є обов’язковим.\\nРозташування: {objectPath}"},"checker.min":{"one":"Значення поля {field} має бути не менше {system}.","two":"Значення поля {field} для {object} має бути не менше {system}.","deep":"Значення поля {field} має бути не менше {system}.\\nРозташування: {objectPath}"},"checker.max":{"one":"Значення поля {field} має бути не більше {system}.","two":"Значення поля {field} для {object} має бути не більше {system}.","deep":"Значення поля {field} має бути не більше {system}.\\nРозташування: {objectPath}"},"checker.minLength":{"one":"Поле {field} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.","two":"Поле {field} для {object} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.","deep":"Поле {field} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.\\nРозташування: {objectPath}"},"checker.maxLength":{"one":"Поле {field} має містити не більше {system} {unit}; поточна довжина — {input_len}.","two":"Поле {field} для {object} має містити не більше {system} {unit}; поточна довжина — {input_len}.","deep":"Поле {field} має містити не більше {system} {unit}; поточна довжина — {input_len}.\\nРозташування: {objectPath}"},"checker.invalid":{"one":"Поле {field} є недійсним.","two":"Поле {field} для {object} є недійсним.","deep":"Поле {field} є недійсним.\\nРозташування: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} № {position}","separator":" → "}},"vi":{"rules":{"checker.required":{"one":"Trường {field} là bắt buộc.","two":"Trường {field} của {object} là bắt buộc.","deep":"Trường {field} là bắt buộc.\\nVị trí: {objectPath}"},"checker.min":{"one":"Giá trị {field} phải ít nhất là {system}.","two":"Giá trị {field} của {object} phải ít nhất là {system}.","deep":"Giá trị {field} phải ít nhất là {system}.\\nVị trí: {objectPath}"},"checker.max":{"one":"Giá trị {field} không được vượt quá {system}.","two":"Giá trị {field} của {object} không được vượt quá {system}.","deep":"Giá trị {field} không được vượt quá {system}.\\nVị trí: {objectPath}"},"checker.minLength":{"one":"Độ dài {field} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.","two":"Độ dài {field} của {object} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.","deep":"Độ dài {field} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.\\nVị trí: {objectPath}"},"checker.maxLength":{"one":"Độ dài {field} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.","two":"Độ dài {field} của {object} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.","deep":"Độ dài {field} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.\\nVị trí: {objectPath}"},"checker.invalid":{"one":"Trường {field} không hợp lệ.","two":"Trường {field} của {object} không hợp lệ.","deep":"Trường {field} không hợp lệ.\\nVị trí: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} thứ {position}","separator":" → "}}}'),xn={schema:Cn,defaultLocale:$n,locales:Nn},Ei=new WeakMap;function Oi(n,e){const t=Object.freeze({locale:n,render:(i,r)=>Et(e,i,r)});return Ei.set(t,e),t}function ji(n,e){const t=Ei.get(n);return t?Oi(n.locale,Object.freeze(t.map(i=>typeof i=="string"?e(i):i))):P()}const P=()=>{throw new TypeError("Invalid Checker message catalog")},qn=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);function Q(n){return!n||typeof n!="object"||Array.isArray(n)?P():n}function se(n){return typeof n!="string"||!n.trim()?P():n}function ve(n,e){Object.keys(n).some(t=>!e.includes(t))&&P()}function ki(n){if(typeof n!="string")return P();let e=0;const t=()=>{for(;/[\t\n\r ]/.test(n[e]??"x");)e++};function i(){if(n[e]!=='"')return P();const s=e++;for(;e!o.has(a))?P():Object.freeze(r)}function Et(n,e,t){return n.map(i=>typeof i=="string"?t?t(i):i:e[i.argument]??"-").join("")}function Mn(n){const e=n%100n,t=e>=11n&&e<=13n?"th":n%10n===1n?"st":n%10n===2n?"nd":n%10n===3n?"rd":"th";return String(n)+t}var ne,ze;const K=class K{constructor(e,t){Pe(this,ne);Pe(this,ze);_e(this,ne,e),_e(this,ze,t),Object.freeze(this)}static fromJson(e){return this.parse(e,!1)}static parse(e,t){const i=Q(ki(e));if(ve(i,["schema","defaultLocale","locales"]),i.schema!=="teaql.checker-messages/v1"||i.defaultLocale!=="en")return P();const r=Object.create(null);for(const[o,s]of Object.entries(Q(i.locales))){const a=ke(o);if(qn(r,a))return P();const c=Q(s);ve(c,["rules","locationPatterns"]);const u=Object.create(null);for(const[d,h]of Object.entries(c.rules===void 0?{}:Q(c.rules))){if(!d.startsWith("checker.")||d.length===8)return P();const f=Object.create(null);for(const[p,m]of Object.entries(Q(h))){if(!["one","two","deep"].includes(p))return P();let b=["field","system","input","input_len","unit"];const g=["field"];if(["checker.required","checker.invalid"].includes(d)?b=["field"]:["checker.min","checker.max"].includes(d)?(b=["field","system","input"],g.push("system")):["checker.minLength","checker.maxLength"].includes(d)&&(b=["field","system","input_len","unit"],g.push("system","input_len","unit")),p!=="one"){const y=p==="two"?"object":"objectPath";b.push(y),g.push(y)}f[p]=ut(m,b,g)}u[d]=Object.freeze(f)}let l;if(c.locationPatterns!==void 0){const d=Q(c.locationPatterns);ve(d,["reference","item","separator"]);const h=ut(d.reference,["relation"],["relation"]),f=ut(d.item,["relation","position","ordinal","classifier"],["relation"]);if(!f.some(m=>typeof m!="string"&&["position","ordinal"].includes(m.argument)))return P();const p=se(d.separator);if(/[{}\r\n\u0000-\u001f\u007f-\u009f]/u.test(p))return P();l=Object.freeze({reference:h,item:f,separator:p})}r[a]=Object.freeze({rules:Object.freeze(u),patterns:l})}if(t)for(const o of pe){const s=r[o];if(!s?.patterns)return P();for(const a of["checker.required","checker.min","checker.max","checker.minLength","checker.maxLength","checker.invalid"])for(const c of["one","two","deep"])if(!s.rules[a]?.[c])return P()}return new K(Object.freeze(r),!t)}lookup(e,t,i){const r=x(this,ne)[e]?.rules[t]?.[i];return r&&Oi(e,r)}override(e,t,i){return x(this,ze)?this.lookup(e,t,i):void 0}select(e,t,i){for(const r of[e,"en"]){const o=this.lookup(r,t,i)??K.builtin.lookup(r,t,i);if(o)return o}return K.builtin.lookup(e,"checker.invalid",i)}patterns(e){return x(this,ne)[e]?.patterns??x(K.builtin,ne)[e].patterns}projectPatterns(e,t){const i=x(this,ne)[e]?.patterns;if(this===K.builtin||!i)return K.builtin;const r=o=>Object.freeze(o.map(s=>typeof s=="string"?t(s):s));return new K(Object.freeze({[e]:Object.freeze({rules:Object.freeze({}),patterns:Object.freeze({reference:r(i.reference),item:r(i.item),separator:t(i.separator)})})}),!1)}reference(e,t){return Et(this.patterns(e).reference,{relation:t})}item(e,t,i,r){if(!Number.isSafeInteger(i)||i<0)return P();const o=BigInt(i)+1n;return Et(this.patterns(e).item,{relation:t,position:String(o),ordinal:Mn(o),classifier:r})}separator(e){return this.patterns(e).separator}};ne=new WeakMap,ze=new WeakMap,K.builtin=K.parse(JSON.stringify(xn),!0);let oe=K;const Dn={en:{currentObject:"current object",utf16:"UTF-16 code units",scalar:"Unicode scalar values",byte:"bytes"},"zh-CN":{currentObject:"当前对象",utf16:"个 UTF-16 代码单元",scalar:"个 Unicode 标量值",byte:"字节"},"zh-TW":{currentObject:"目前物件",utf16:"個 UTF-16 程式碼單元",scalar:"個 Unicode 純量值",byte:"位元組"},ja:{currentObject:"現在のオブジェクト",utf16:"UTF-16コード単位",scalar:"Unicodeスカラー値",byte:"バイト"},ko:{currentObject:"현재 객체",utf16:"UTF-16 코드 단위",scalar:"유니코드 스칼라 값",byte:"바이트"},de:{currentObject:"aktuelles Objekt",utf16:"UTF-16-Codeeinheiten",scalar:"Unicode-Skalarwerte",byte:"Bytes"},fr:{currentObject:"objet actuel",utf16:"unités de code UTF-16",scalar:"valeurs scalaires Unicode",byte:"octets"},es:{currentObject:"objeto actual",utf16:"unidades de código UTF-16",scalar:"valores escalares Unicode",byte:"bytes"},pt:{currentObject:"objeto atual",utf16:"unidades de código UTF-16",scalar:"valores escalares Unicode",byte:"bytes"},ar:{currentObject:"الكائن الحالي",utf16:"وحدات ترميز UTF-16",scalar:"قيم Unicode القياسية",byte:"بايت"},th:{currentObject:"ออบเจ็กต์ปัจจุบัน",utf16:"หน่วยรหัส UTF-16",scalar:"ค่าสเกลาร์ Unicode",byte:"ไบต์"},id:{currentObject:"objek saat ini",utf16:"unit kode UTF-16",scalar:"nilai skalar Unicode",byte:"bita"},fil:{currentObject:"kasalukuyang bagay",utf16:"yunit ng code na UTF-16",scalar:"scalar na halaga ng Unicode",byte:"byte"},uk:{currentObject:"поточний об’єкт",utf16:"кодових одиниць UTF-16",scalar:"скалярних значень Unicode",byte:"байтів"},vi:{currentObject:"đối tượng hiện tại",utf16:"đơn vị mã UTF-16",scalar:"giá trị vô hướng Unicode",byte:"byte"}},Fn={locales:Dn},Se=()=>{throw new TypeError("Invalid Checker presentation metadata")};function Ze(n){return n.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu," ").trim()}function Qe(n){const e=Object.create(null);for(const[t,i]of Object.entries(Q(n))){const r=ke(t);if(Object.prototype.hasOwnProperty.call(e,r))return Se();e[r]=se(i)}return Object.freeze(e)}const Te=Fn.locales;for(const n of pe){for(const e of Object.values(Te[n]))(!e||Ze(e)!==e)&&Se();Object.freeze(Te[n])}Object.freeze(Te);function zn(n,e){return Te[n][e]}class Vn{#e;constructor(e){const t=Q(e);if(ve(t,["labels","fields"]),this.labels=Qe(t.labels??{}),!Array.isArray(t.fields))throw new TypeError("Invalid Checker presentation fields");const i=new Map,r=[];for(const s of t.fields){const a=Q(s);ve(a,["name","targetType","labels","classifiers","aliases"]);const c=se(a.name),u=a.targetType===void 0?void 0:se(a.targetType);if(a.aliases!==void 0&&!Array.isArray(a.aliases))throw new TypeError("Invalid Checker presentation aliases");const l=Object.freeze((a.aliases??[]).map(se)),d=Object.freeze({name:c,targetType:u,labels:Qe(a.labels??{}),classifiers:Qe(a.classifiers??{}),aliases:l});for(const h of[c,...l]){if(i.has(h))throw new TypeError("Ambiguous Checker presentation identity");i.set(h,d)}r.push(d)}this.#e=i;const o=s=>Object.entries(s).sort(([a],[c])=>a.localeCompare(c));this.fingerprint=JSON.stringify([o(this.labels),r.sort((s,a)=>s.name.localeCompare(a.name)).map(s=>[s.name,s.targetType,o(s.labels),o(s.classifiers),[...s.aliases].sort()])]),Object.freeze(this)}field(e){return this.#e.get(e)}}var de,Z;const ie=class ie{constructor(e,t,i){Pe(this,de);Pe(this,Z);this.revision=e,_e(this,de,t),_e(this,Z,i),Object.freeze(this)}static fromJson(e){const t=Q(ki(e));if(ve(t,["schema","revision","entities","currentObject"]),t.schema!=="teaql.checker-model/v1")return Se();const i=se(t.revision),r=new Map;for(const[o,s]of Object.entries(Q(t.entities)))se(o),r.set(o,new Vn(s));return new ie(i,r,Object.freeze({...x(this.empty,Z),...Qe(t.currentObject??{})}))}entity(e){return e===void 0?void 0:x(this,de).get(e)}currentLabels(){return x(this,Z)}merge(e){if(this===ie.empty)return e;if(e===ie.empty||this===e)return this;const t=new Map(x(this,de));let i=!1;for(const[r,o]of x(e,de)){const s=t.get(r);if(s&&s.fingerprint!==o.fingerprint)return Se();s||(t.set(r,o),i=!0)}for(const r of pe)if(x(this,Z)[r]!==x(e,Z)[r])return Se();return i?new ie(this.revision+"+"+e.revision,t,x(this,Z)):this}};de=new WeakMap,Z=new WeakMap,ie.empty=new ie("unconfigured",new Map,Object.freeze(Object.fromEntries(pe.map(e=>[e,Te[e].currentObject]))));let te=ie;class Le{constructor(e,t,i,r){this.model=e,this.origin=t,this.shape=i,this.#e=r,Object.freeze(this)}#e;static capture(e,t,i){let r=e.entity(t),o=!r;const s=[];for(const c of i.segments)if(c.kind==="property"){const u=r?.field(c.name);r=e.entity(u?.targetType),s.push({identity:c.name,field:u,indices:[]})}else{if(!Number.isSafeInteger(c.index)||c.index<0)return Se();s.length||(s.push({indices:[]}),o=!0);const u=s[s.length-1];u.indices.push(c.index),u.indices.length>1&&(o=!0)}(!s.length||s[s.length-1].indices.length)&&(o=!0);const a=o||s.length>2?"deep":s.length===1?"one":"two";return new Le(e,t,a,Object.freeze(s.map(c=>Object.freeze({...c,indices:Object.freeze(c.indices)}))))}relocate(e){return Le.capture(this.model,this.origin,e)}render(e,t,i){const r=new Set,o=t.locale,s=(m,b)=>{let g=m[o];g?.trim()||(r.add("CHECKER_MESSAGE_LABEL_FALLBACK"),g=m.en);const y=Ze(g?.trim()?g:b.replace(/_/g," "));return y||(r.add("CHECKER_MESSAGE_LABEL_FALLBACK"),Te[o].currentObject)},a=()=>s(this.model.currentLabels(),"current object"),c=this.model.entity(this.origin),u=c?s(c.labels,this.origin):a(),l=m=>s(m.field?.labels??{},m.field?.name??m.identity??"current object"),d=this.#e[this.#e.length-1],h=Object.fromEntries(["system","input","input_len","unit"].filter(m=>Object.prototype.hasOwnProperty.call(i,m)).map(m=>[m,i[m]]));h.field=d?.identity?l(d):u;const f=this.#e.length-(d?.identity&&!d.indices.length?1:0),p=[];for(const m of this.#e.slice(0,f)){const b=m.identity?l(m):u;if(!m.indices.length)p.push(e.reference(o,b));else for(let g=0;gn.presentation.render(n.catalog,n.selection,n.arguments),Li=Symbol("TeaQL.NaturalCheckerPresentation"),Ii=new WeakMap,At=n=>{const e=n[Li];return e&&Ii.get(e)};function Pi(n,e,t,i){const r=Object.freeze({});Ii.set(r,Object.freeze({presentation:e,automaticMessage:t,plan:i})),Object.defineProperty(n,Li,{value:r,enumerable:!0,configurable:!0})}function Ot(n){const e=At(n);return e?.automaticMessage!==void 0&&e.automaticMessage===n.message||Ln(n)}function _i(n,e){return n.map(t=>{const i={...t},r=Ot(t);return Pi(i,Le.capture(e.model,e.entity,t.location),r?t.message:void 0,r?At(t)?.plan:void 0),i})}const Un=Object.freeze({required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"});function Bt(n){return n===null?"null":n===void 0?"undefined":typeof n=="string"?Ze(n):typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):n instanceof Date&&Object.getPrototypeOf(n)===Date.prototype&&Number.isFinite(n.getTime())?n.toISOString():"[value omitted]"}const Bn=["CHECKER_MESSAGE_LABEL_FALLBACK","CHECKER_MESSAGE_GENERIC_RULE","CHECKER_MESSAGE_RENDER_FALLBACK"];function Kn(n,e,t){const i=s=>Je(e,s),r=new Map,o=Object.fromEntries(pe.map(s=>[s,Object.freeze(Object.fromEntries(["one","two","deep"].map(a=>{let c,u,l=!1;for(const f of[s,"en"]){if(c=n.catalog.override(f,t,a),c){l=!0;break}const p=n.legacy.applicationMessage(f,t);if(p!==void 0){u=Object.freeze(p.split(/(\{(?:location|system|input|input_len)\})/g).map(m=>/^\{(?:location|system|input|input_len)\}$/.test(m)?Object.freeze({argument:m.slice(1,-1)}):i(m)));break}if(c=oe.builtin.lookup(f,t,a),c)break}const d=!c&&!u;d&&(c=oe.builtin.select(s,"checker.invalid",a)),c&&l&&(c=ji(c,i));const h=c?.locale??s;return r.has(h)||r.set(h,n.catalog.projectPatterns(h,i)),[a,Object.freeze({selection:c,legacy:u,catalog:r.get(h),generic:d,application:l})]})))]));return Object.freeze({locales:Object.freeze(o)})}function Qn(n,e){if(n.literal!==void 0)return Object.freeze({literal:e(n.literal)});const t={};for(const i of pe){const r={};for(const o of["one","two","deep"]){const s=n.locales[i][o];r[o]=Object.freeze({...s,selection:s.application&&s.selection?ji(s.selection,e):s.selection,legacy:s.legacy&&Object.freeze(s.legacy.map(a=>typeof a=="string"?e(a):a)),catalog:s.catalog.projectPatterns(s.selection?.locale??i,e)})}t[i]=Object.freeze(r)}return Object.freeze({locales:Object.freeze(t)})}function Ai(n,e){return Object.freeze({system:Bt(n.systemValue),input:Bt(n.inputValue),input_len:String(wi(n)),unit:zn(e,"scalar")})}function Kt(n,e,t,i){if(n.literal!==void 0)return Object.freeze({message:n.literal,warnings:Object.freeze([])});const r=n.locales[i][e.shape],o=Ai(t,r.selection?.locale??i);if(r.legacy){const a={...o,location:t.location.nativePath()};return Object.freeze({message:r.legacy.map(c=>typeof c=="string"?c:a[c.argument]??"-").join(""),warnings:Object.freeze([])})}const s=e.render(r.catalog,r.selection,o);return r.generic?Object.freeze({...s,warnings:Object.freeze([...s.warnings,"CHECKER_MESSAGE_GENERIC_RULE"])}):s}function Qt(n,e,t=new Set,i){if(e.message?.trim()&&!Ot(e))return e;const r=h=>{const f=Bn.includes(h)?h:"CHECKER_MESSAGE_RENDER_FALLBACK";if(!t.has(f)){t.add(f);try{n.warning(f)}catch{}}},o=At(e),s=i?.model??o?.presentation.model??n.model,a=i?.entity??o?.presentation.origin;let c;try{c=Le.capture(s,a,e.location)}catch{r("CHECKER_MESSAGE_RENDER_FALLBACK"),c=Le.capture(te.empty,void 0,F.root())}const u=Un[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,l=ke(n.locale);let d=Ot(e)?o?.plan:void 0;d&&(d=Qn(d,h=>Je(e,h)));try{let h;if(d)h=Kt(d,c,e,l);else{d=Kn(n,e,u);const f=d.locales[l][c.shape];if(n.renderer===Ti||f.legacy)h=Kt(d,c,e,l);else{const p=Object.freeze({presentation:c,catalog:f.catalog,selection:f.selection,arguments:Ai(e,f.selection.locale)}),m=n.renderer(p);h=Object.freeze({...m,message:Je(e,m.message)}),d=Object.freeze({literal:h.message})}}if(!h||typeof h.message!="string"||!h.message.trim())throw new Error("Empty rendered message");for(const f of h.warnings)r(f);e.message=h.message}catch{r("CHECKER_MESSAGE_RENDER_FALLBACK");const h=c.render(oe.builtin,oe.builtin.select(l,"checker.invalid",c.shape),{});e.message=h.message;for(const f of h.warnings)r(f);d=Object.freeze({literal:e.message})}return Pi(e,c,e.message,d),vi(e),e}class Gn{constructor(e,t,i={}){this.entity=e,this.#e=new Set(t),this.#t=Object.freeze({...i}),Object.freeze(this)}#e;#t;validate(e,t=!1){const i=Object.keys(e).flatMap(r=>{const o=this.#e.has(r)?t&&Object.prototype.hasOwnProperty.call(this.#t,r)?this.#t[r]:void 0:"unknown_field";return o?[{ruleId:o,location:F.property(r),message:o==="unknown_field"?"Expected a canonical model field name":"Field is immutable after create"}]:[]});if(i.length)throw new G(i)}}var Wn={};class V extends Error{constructor(){super("Runtime logging initialization failed"),this.name="RuntimeLoggingError"}}const Ri=new TextEncoder,Gt=new Map,Hn=["TEAQL_DOMAIN","TEAQL_LOG_ENDPOINT","TEAQL_LOG_MAX_SIZE","TEAQL_LOG_MAX_FILES","TEAQL_LOG_FORMAT"],Ci=new Set(["timestamp","level","log_name","runtime","event","message"]),Xn=/^\d{4}-\d\d-\d\dT\S+(?:Z|\+00:00) \[TeaQL\]\[.*\]\[(?:INFO|WARN|ERROR)\] .+ runtime=\S+$/u;function $i(){return typeof process<"u"&&!!process.versions?.node&&!(typeof window<"u"&&typeof window.document<"u")}function Ni(){const n=typeof require=="function"?require:typeof process<"u"&&typeof process.getBuiltinModule=="function"?e=>process.getBuiltinModule(e):void 0;if(!n)throw new V;return{fs:n("node:fs"),path:n("node:path"),url:n("node:url")}}function xi(){const n={};for(const e of Hn)n[e]=Wn[e];return n}function Yn(n){return typeof n=="string"&&n.length>0&&n!=="."&&n!==".."&&!/[<>:"/\\|?*\u0000-\u001f\u007f]/u.test(n)&&!/[. ]$/u.test(n)&&!/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(n)&&!/[\uD800-\uDFFF]/u.test(n)&&Ri.encode(n).byteLength<=255}function Jn(n){const e=/^([0-9]+)\s*(K|KB|M|MB|G|GB)?$/u.exec(n.trim().toUpperCase());if(!e)throw new V;const t={K:1024n,KB:1024n,M:1048576n,MB:1048576n,G:1073741824n,GB:1073741824n}[e[2]]??1n,i=BigInt(e[1])*t;if(i<=0n||i>9223372036854775807n)throw new V;return i}function Me(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t)}function le(n,e){return n.replace(/[\\\u0000-\u001f\u007f-\u009f\u2028\u2029\ud800-\udfff]/gu,t=>t==="\\"?e?"\\\\":t:"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function qi(n){return`[TeaQL][${le(n.log_name,!0)}][${n.level}] ${le(n.event,!0)}`}function Wt(n){let e=`${le(n.timestamp,!0)} ${qi(n)} runtime=${n.runtime} + ${le(n.message,!0)} +`;for(const t of Object.keys(n).filter(i=>!Ci.has(i)).sort()){const i=n[t];t==="sql"&&typeof i=="string"?e+=` sql: +`+i.split(` +`).map(r=>" "+le(r,!0)+` +`).join(""):e+=" "+le(t,!0)+"="+le(Me(i),!1)+` +`}return e}function Ht(n,e,t){const i={timestamp:new Date().toISOString(),level:"ERROR",log_name:n,runtime:"typescript",event:"logging.failure",message:"Runtime logging failed",error_code:e};try{t?Ni().fs.writeSync(2,Me(i)+` +`):console.error(`[TeaQL][${n}][ERROR] logging.failure`,i)}catch{}}class Zn{constructor(e={}){this.server=e.platform==="server"||e.platform!=="browser"&&$i();let t="teaql";try{const i=this.server?e.environment??xi():{},r=e.logName!==void 0?e.logName:i.TEAQL_DOMAIN||(e.modelNames?.length===1?e.modelNames[0]:"teaql");if(!Yn(r))throw new V;this.logName=t=r;const o=e.logFormat!==void 0?e.logFormat:i.TEAQL_LOG_FORMAT??"json";if(o!=="json"&&o!=="human")throw new V;this.logFormat=o,this.maxSize=Jn(i.TEAQL_LOG_MAX_SIZE??"50M");const s=i.TEAQL_LOG_MAX_FILES??"7";if(!/^[0-9]+$/u.test(s)||BigInt(s)>2147483647n)throw new V;if(this.maxFiles=Number(s),this.server){this.native=Ni();const{fs:a,path:c,url:u}=this.native;let l=i.TEAQL_LOG_ENDPOINT||`./logs/${r}.log`;if(["stdout","stderr","-"].includes(l))this.stream=l;else{if(l.startsWith("file:")){const h=new URL(l);if(h.hostname&&h.hostname!=="localhost"||h.search||h.hash)throw new V;l=u.fileURLToPath(h)}else if(l.includes("://"))throw new V;let d=c.resolve(e.workingDirectory??process.cwd(),l);a.mkdirSync(c.dirname(d),{recursive:!0}),d=c.join(a.realpathSync(c.dirname(d)),c.basename(d));try{d=a.realpathSync(d)}catch(h){if(h.code!=="ENOENT")throw h}this.path=d}}this.emit(this.record("INFO","runtime.start","TeaQL runtime started",{}))}catch{throw Ht(t,"log_destination_unavailable",this.server),new V}}record(e,t,i,r){return Object.freeze({...r,timestamp:new Date().toISOString(),level:e,log_name:this.logName,runtime:"typescript",event:t,message:i})}write(e,t,i,r={}){try{if(!["INFO","WARN","ERROR"].includes(e))throw new Error;return this.emit(this.record(e,t,i,r)),!0}catch{return Ht(this.logName,"log_write_failed",this.server),!1}}archives(){const{fs:e,path:t}=this.native,i=t.basename(this.path)+".";return e.readdirSync(t.dirname(this.path)).filter(r=>r.startsWith(i)&&/^[1-9][0-9]*$/u.test(r.slice(i.length))).map(r=>{const o=Number(r.slice(i.length)),s=t.join(t.dirname(this.path),r);if(!Number.isSafeInteger(o)||!e.lstatSync(s).isFile())throw new Error;return{number:o,path:s}}).sort((r,o)=>o.number-r.number)}emit(e){if(!this.server){const c=e.level==="WARN"?"warn":e.level==="ERROR"?"error":"info";console[c](this.logFormat==="human"?Wt(JSON.parse(Me(e))):qi(e),e);return}const{fs:t}=this.native,i=Me(e),r=Ri.encode(this.logFormat==="human"?Wt(JSON.parse(i)):i+` +`);if(this.stream){t.writeSync(this.stream==="stderr"?2:1,r);return}const o=this.path+".lock",s=Date.now()+3e4;let a;for(;;)try{a=t.openSync(o,"wx",384);break}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{this.checkPresentation();const c=this.archives();for(const d of c)d.number>this.maxFiles&&t.unlinkSync(d.path);let u;try{u=t.statSync(this.path,{bigint:!0})}catch(d){if(d.code!=="ENOENT")throw d}if(u){if(!u.isFile())throw new Error;if(u.size>0n&&(u.size+BigInt(r.byteLength)>this.maxSize||u.mtime.toISOString().slice(0,10)!==new Date().toISOString().slice(0,10))){for(const d of c.filter(h=>h.number<=this.maxFiles))d.number===this.maxFiles?t.unlinkSync(d.path):t.renameSync(d.path,this.path+"."+(d.number+1));this.maxFiles===0?t.unlinkSync(this.path):t.renameSync(this.path,this.path+".1")}}const l=t.openSync(this.path,"a",384);try{let d=0;for(;d=0)break}const a=new Uint8Array(s);let c=0;for(const u of o)a.set(u,c),c+=u.length;r=new TextDecoder("utf-8",{fatal:!0}).decode(a)}finally{e.closeSync(i)}if(!(this.logFormat==="human"&&Xn.test(r))){if(this.logFormat==="json")try{const o=JSON.parse(r);if(o&&!Array.isArray(o)&&[...Ci].every(s=>typeof o[s]=="string")&&["INFO","WARN","ERROR"].includes(o.level))return}catch{}throw new V}}}function er(){const n=$i(),e=n?xi():{},t=n?process.cwd():"",i=Me([n,t,e]);let r=Gt.get(i);return r||(r=new Zn({environment:e,workingDirectory:t}),Gt.set(i,r)),r}function tr(n,e){return{start(t){const i=H(n,t);let r=!1;function o(s){if(r)return!1;r=!0;const a=s===void 0?void 0:s instanceof Error&&/^(CheckException|RequestIntentError|MutationIntentError)$/u.test(s.constructor.name)?"validation":s instanceof Error&&s.constructor.name==="MutationPolicyError"?"authorization":ln(s),c=s===void 0?"success":"failure",u=s===void 0?"INFO":["validation","authorization","conflict"].includes(a)?"WARN":"ERROR";return e.write(u,`operation.${c}`,`TeaQL operation ${c}`,{category:t.family.toUpperCase(),outcome:c,error_code:a,trace_id:i.correlation?.()?.traceId}),!0}return{...i,success(s){o()&&i.success(s)},failure(s){o(s)&&i.failure(s)}}},recordsSQLDiagnostics:()=>n?.recordsSQLDiagnostics?.()??!1,recordDiagnostic:t=>n?.recordDiagnostic?.(t),inject:t=>n?.inject?.(t),flush:()=>n?.flush?.(),shutdown:()=>n?.shutdown?.()}}class ir{now(){return new Date}}class U extends Error{constructor(e){super(`Object storage: ${e}`),this.code=e,this.name="StorageError"}}const Mi=Symbol.for("nodejs.util.inspect.custom"),De=()=>{throw new U("InvalidInput")};function nr(n){return(typeof n!="string"||!n||/[^\x20-\x7e]/.test(n))&&De(),n}class rr{#e;#t;constructor(e=300,t,i){(!Number.isInteger(e)||e<=0||e>604800||t!==void 0&&!["inline","attachment"].includes(t))&&De(),i!==void 0&&(nr(i),(!t||/[\/\\"]/.test(i))&&De()),this.#e=e,this.#t=t+(i===void 0?"":`; filename="${i}"`),t===void 0&&(this.#t=void 0)}get seconds(){return this.#e}get contentDisposition(){return this.#t}toString(){return"ObjectReadUrlOptions[details=masked]"}[Mi](){return this.toString()}}function Xt(n){return n instanceof U?n:new U("Unavailable")}const Yt=n=>String(n??"").replace(/[\x00-\x1f\x7f-\x9f]/g," ");class Jt{constructor(e,t){this.invocation=e,this.operation=t,this.scope=H(e.context.getResource("runtimeTelemetry"),{family:"object_storage",name:t})}#e=!1;#t=performance.now();finish(e){if(this.#e)return;this.#e=!0,e==="success"?this.scope.success():this.scope.failure(new U(e==="cancelled"?"Io":e));const t=Object.freeze({operation:this.operation,comment:Yt(this.invocation.comment),traceId:Yt(this.invocation.context.getResource("traceId")),outcome:e,elapsedMs:performance.now()-this.#t});try{const i=this.invocation.context.getResource("objectStorageObserver");i?i(t):console.info(`ObjectStorage operation=${t.operation} comment=${t.comment} trace=${t.traceId} outcome=${t.outcome} elapsedMs=${t.elapsedMs.toFixed(3)}`)}catch{}}}class sr{#e;#t;#n;constructor(e,t,i){this.#e=e,this.#t=t,this.#n=i}get metadata(){return this.#e}get stream(){return this.#t}close(){return this.#n()}toString(){return"ObjectContent[masked]"}[Mi](){return this.toString()}}class or{#e;#t;constructor(e,t){(typeof t!="string"||!t.trim())&&De();const i=e.getResource("objectStorageProvider");if(!i)throw new U("NotConfigured");this.#e=Object.freeze({context:e,comment:t}),this.#t=i}async#n(e,t){const i=new Jt(this.#e,e);try{const r=await(i.scope.run?i.scope.run(t):t());return i.finish("success"),r}catch(r){const o=Xt(r);throw i.finish(o.code),o}}async put(e,t,i){const r=t[Symbol.asyncIterator]();let o=!1;const s={next:async()=>{const a=await r.next();return a.done&&(o=!0),a},return:async()=>(o||(o=!0,await r.return?.()),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}};return this.#n("put",async()=>{try{return await this.#t.put(this.#e,e,s,i)}finally{await s.return()}})}async putBytes(e,t,i){return this.put(e,(async function*(){yield t})(),i)}async get(e){const t=new Jt(this.#e,"get");let i;try{i=await(t.scope.run?t.scope.run(()=>this.#t.get(this.#e,e)):this.#t.get(this.#e,e))}catch(c){const u=Xt(c);throw t.finish(u.code),u}let r=!1,o=!1;const s=async()=>{if(!r){r=!0;try{await i.close(),t.finish("cancelled")}catch{throw t.finish("Io"),new U("Io")}}},a={[Symbol.asyncIterator]:async function*(){if(o||r)throw new U("Io");o=!0;let c=i.metadata.size;try{for await(const u of i.stream){if(!(u instanceof Uint8Array)||u.byteLength>c)throw new U("Io");c-=u.byteLength,yield u}if(c!==0)throw new U("Io");t.finish("success")}catch{throw t.finish("Io"),new U("Io")}finally{await s()}}};return new sr(i.metadata,a,s)}async getBytes(e,t){(!Number.isSafeInteger(t)||t<0)&&De();const i=await this.get(e);try{if(i.metadata.size>t)throw new U("TooLarge");const r=[];let o=0;for await(const c of i.stream){if(c.byteLength>t-o)throw new U("TooLarge");o+=c.byteLength,r.push(c)}const s=new Uint8Array(o);let a=0;for(const c of r)s.set(c,a),a+=c.byteLength;return s}finally{await i.close()}}head(e){return this.#n("head",()=>this.#t.head(this.#e,e))}async exists(e){return await this.head(e)!==void 0}delete(e){return this.#n("delete",()=>this.#t.delete(this.#e,e))}getReadUrl(e,t=new rr){return this.#n("read_url",()=>this.#t.getReadUrl(this.#e,e,t))}}function jt(n){if(typeof n=="number"&&(!Number.isSafeInteger(n)||n<=0))throw new RangeError("Internal ID must be a positive safe integer when supplied as a number");if(typeof n!="string"&&typeof n!="number"&&typeof n!="bigint")throw new TypeError("Internal ID must be an exact positive integer");const e=String(n);if(!/^[1-9][0-9]*$/.test(e))throw new TypeError("Internal ID must be a canonical positive integer");if(BigInt(e)>(1n<<63n)-1n)throw new RangeError("Internal ID exceeds signed 64-bit range");return e}const Di=Symbol("teaql.context.schema-capability");function ar(n,e,t,i){if(i&&!n.trim())throw new Error("Missing SQL template");let r=0;const o=new Set,s=u=>{if(u<0||u>=e.length)throw new Error("SQL bind count mismatch");return o.add(u),i?i(u):Fi(e[u],t)};let a="",c="sql";for(let u=0;u=0&&f=0&&ft.toString(16).padStart(2,"0")).join("")}'`:W(typeof n=="object"?JSON.stringify(n):String(n))}function W(n){return`'${n.replace(/'/g,"''")}'`}const Zt="[REDACTED]",dt="[REDACTED SQL; NOT REPLAYABLE]",cr=`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN +`,Ne=new WeakMap,kt=new WeakMap,zi=new WeakMap;function ei(n,e,t=[]){zi.set(n,{bindings:e?q(e):void 0,intentValues:Object.freeze(t.map(Fe))})}function et(n){const e=n.parameterLogPolicies,t=!!e&&e.length===n.parameters.length,i=fe(n.parameterizedSQL)&&(n.sqlOrigin!=="generated"||!t);return n.parameters.map((r,o)=>{if(i||ot(r))return"credential";const s=t?e[o]:void 0;return s==="plain"||s==="masked"||s==="credential"?s:"unknown"})}function Tt(n,e){return n==="credential"||n==="unknown"||!e&&n!=="plain"}function ti(n){if(!n)return[];const e=et(n);return n.parameters.flatMap((t,i)=>Tt(e[i],!1)?J(t):[])}function Fe(n){return n instanceof Date?new Date(n.getTime()):n instanceof Uint8Array?new Uint8Array(n):Array.isArray(n)?Object.freeze(n.map(Fe)):n&&typeof n=="object"?Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Fe(t)]))):n}function q(n,e){const t=e?[e,n]:[n];return Object.freeze({parameterizedSQL:"",sqlOrigin:"generated",parameters:Object.freeze(t.flatMap(i=>i.parameters.map(Fe))),parameterLogPolicies:Object.freeze(t.flatMap(et))})}function Vi(n,e,t=[]){const i=gi()&&n.logMode!=="masked",r=Ne.get(n);if(r!==void 0&&(!r||i))return n;const o=kt.get(n);if(!i&&o)return o;const s=tt(n,i,e,t);if(Ne.set(s,i),i){const a=tt(n,!1,e,t);Ne.set(a,!1),kt.set(s,a)}return s}function lr(n){const e=kt.get(n);if(e)return e;if(Ne.get(n)===!1)return n;const t=tt(n,!1);return Ne.set(t,!1),t}function tt(n,e,t,i=[]){const r=zi.get(n);r?.bindings&&(t=q(r.bindings,t)),r&&(i=[...i,...r.intentValues]);const o=n.parameterLogPolicies,s=!o||o.length===n.parameters.length,a=fe(n.parameterizedSQL)&&(n.sqlOrigin!=="generated"||!o||!s),c=et(n),u=c.map(E=>Tt(E,e)),l=n.parameters.flatMap((E,k)=>u[k]?J(E):[]);if(t){const E=et(t);l.push(...t.parameters.flatMap((k,j)=>Tt(E[j],e)?J(k):[]))}const d=[...l,...i.flatMap(J)],h=!e&&n.logMode==="debug-plaintext"&&!t,f=E=>h&&E?Zt:re(E,d),p=n.parameters.map((E,k)=>u[k]?c[k]==="masked"?Xe(E):Zt:Fe(E)),m=n.parameterizedSQL.replace(/\$[0-9]+|@p[0-9]+/gi,"?"),b=(!e||a)&&n.sqlOrigin!=="generated"&&/['"`$]|--|\/\*|\b\d+\b|:[A-Za-z_]/.test(m),g=n.databaseKind??"sqlite";let y=dt,O=b?"untrusted-literal-sql":s?void 0:"policy-count-mismatch";if(!b&&s)try{y=ar(n.parameterizedSQL,p,g,E=>Fi(p[E],g)+(u[E]?" /* masked */":"")),y=(e?u.some(Boolean)?`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN; PARTIALLY MASKED; NOT REPLAYABLE +`:cr:`-- TeaQL MASKED; NOT REPLAYABLE +`)+y}catch{y=dt,O="unsupported-or-mismatched-bindings"}return Object.freeze({...n,...n.statements?{statements:Object.freeze(n.statements.map(E=>tt(E,e,q(n,t),i)))}:{},parameterizedSQL:b?dt:n.sqlOrigin==="generated"?n.parameterizedSQL:re(n.parameterizedSQL,l),parameters:Object.freeze(p),parameterLogPolicies:Object.freeze(c),maskedParameters:Object.freeze(u),logMode:e?"debug-plaintext":"masked",omissionReason:O,debugSQL:y,comment:f(n.comment),purpose:f(n.purpose),auditReason:f(n.auditReason),...n.traceChain?{traceChain:Object.freeze(n.traceChain.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j])))))}:{},resultSummary:n.resultCount!==void 0?`${n.resultCount} rows returned`:n.affectedRows!==void 0?`${n.affectedRows} rows affected`:re(n.resultSummary,l),tracePath:Object.freeze(n.tracePath.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j]))))),...n.traceChain?{traceChain:Object.freeze(n.traceChain.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j])))))}:{},...n.mutationLineage?{mutationLineage:Object.freeze(n.mutationLineage.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j])))))}:{}})}const ii="__teaql_prepared_reference",A=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class I extends G{constructor(e=""){super([{ruleId:"mutation_changed_after_preparation",location:e?F.property(e):F.root(),message:"Mutation differs from its prepared and reviewed state; prepare and review it again"}]),this.code="MUTATION_CHANGED_AFTER_PREPARATION",this.name="PreparedMutationError"}}class ur{constructor(){this.sources=[],this.objects=new WeakMap,this.tokens=new Map,this.entries=[],this.aliases=new Map,this.bindings=[],this.metadata=[],this.sealed=!1}get rootEntity(){return this.sources[0]?.key.entity??this.entries[0]?.key.entity}get size(){return this.entries.length}register(e,t,i,r,o){if(this.sealed)throw new I;if(this.objects.has(e))return;const s={object:e,token:Symbol("prepared entity"),root:t,key:{...i},origin:{...i},references:r,read:o};this.objects.set(e,s),this.tokens.set(s.token,s),this.sources.push(s)}members(e){return e.map(t=>{const i=this.objects.get(t);if(!i)throw new I;return i.token})}bind(e){this.bindings.push({read:e,value:e()})}bindMetadata(e){this.metadata.push({read:e,value:new $(e())})}captureInput(){for(const e of this.sources)e.native=new $(this.canonical(e.read(),e.references))}resolved(e){return this.aliases.get(A(e))??e}canonical(e,t){const i={...e};for(const[r,o]of Object.entries(t)){const s=i[r];if(!s||typeof s!="object")continue;const a=this.objects.get(s);if(a){if(a.key.entity!==o)throw new I(r);i[r]={[ii]:a.token}}else if(s.id!==void 0&&s.id!==null)i[r]=s.id;else throw new I(r)}return i}materialize(e,t=!1){return Object.fromEntries(Object.entries(e).map(([i,r])=>{const o=r&&typeof r=="object"?r[ii]:void 0;if(typeof o!="symbol")return[i,r];const s=this.tokens.get(o);if(!s)throw new I(i);const a=this.resolved(s.origin);if(!t&&!this.aliases.has(A(s.origin))&&s.root.isNew(s.key))throw new I(i);return[i,a.id]}))}difference(e,t){return new $(this.materialize(e.values(),!0)).changedField(this.materialize(t,!0))}rootState(e,t,i){return{values:new $(this.canonical(e.change(t),i)),version:e.originalVersion(t),fresh:e.isNew(t),deleted:e.isDeleted(t),trace:new $({trace:e.traceChain(t)})}}assertRoot(e,t,i,r){if(e.originalVersion(t)!==r.version)throw new I("version");if(e.isNew(t)!==r.fresh||e.isDeleted(t)!==r.deleted)throw new I;const o=this.difference(r.values,this.canonical(e.change(t),i));if(o!==void 0)throw new I(o);if(r.trace.changedField({trace:e.traceChain(t)})!==void 0)throw new I("comment")}assertNative(e){if(!e.native)throw new I;const t=this.difference(e.native,this.canonical(e.read(),e.references));if(t!==void 0)throw new I(t==="__teaql_comment"?"comment":t==="__teaql_key"?"id":t.startsWith("__teaql_")?"":t)}remember(e,t,i){if(this.sealed)throw new I;const r=t.ledgerRoot,o=t.ledgerKey??{entity:String(t.entity),id:t.id??Symbol("unassigned")};if(this.entries.some(c=>r&&c.root===r&&A(c.key)===A(o)))throw new I("id");const s=new $(this.canonical(t.payload??{},i)),a={request:e,root:r,key:{...o},mutation:{...t,payload:void 0},references:i,values:s,input:new $(this.canonical(e.mutation.payload??{},i)),loaded:new $(this.canonical(e.loadedValues(),i)),state:r?this.rootState(r,o,i):void 0,status:"prepared"};return this.entries.push(a),{...t,id:t.id??t.ledgerKey?.id,payload:this.materialize(s.values(),!0)}}normalizeRestored(e){if(this.sealed)throw new I;const t=e.ledgerRoot,i=e.ledgerKey;if(e.action!=="Update"||!t||!i)return;const r=this.sources.find(l=>l.root===t&&A(l.key)===A(i)),o=r?.object,s=o?.teaqlRestoreFixedValues;if(!r||typeof s!="function")return;const a=$.forEntity(r.object);let c;if(a?.discardRestoredFields(t,i,l=>{c=l}),!c)return;e.payload={...t.change(i)};const u=c;return{empty:!t.hasPending(i),restore:()=>{this.assertNative(r);const l=new $({...r.native.values(),...this.canonical(u,r.references)});s.call(o,N(u));const d=this.difference(l,this.canonical(r.read(),r.references));if(d!==void 0)throw new I(d);r.native=l}}}seal(){if(!this.sealed){for(const e of this.sources)this.assertNative(e);for(const e of this.entries)e.root&&e.state&&this.assertRoot(e.root,e.key,e.references,e.state);for(const e of this.sources)e.state=this.rootState(e.root,e.key,e.references);this.sealed=!0,this.validate()}}validate(){for(const e of this.bindings)if(e.read()!==e.value)throw new I("context");for(const e of this.metadata)if(e.value.changedField(e.read())!==void 0)throw new I("metadata");for(const e of this.sources)this.assertNative(e),e.state&&this.assertRoot(e.root,e.key,e.references,e.state);for(const e of this.entries)e.root&&e.state&&this.assertRoot(e.root,this.resolved(e.key),e.references,e.state)}entry(e){const t=e.mutation,i=this.entries.find(r=>r.request===e||t.ledgerRoot&&r.root===t.ledgerRoot&&t.ledgerKey&&A(this.resolved(r.key))===A(t.ledgerKey))??this.entries.find(r=>!r.root&&r.status==="prepared"&&r.mutation.entity===t.entity&&r.mutation.action===t.action&&r.mutation.id===t.id&&this.difference(r.root&&t.action==="Update"?r.values:r.input,this.canonical(t.payload??{},r.references))===void 0);if(!i)throw new I;return i}replay(e){if(!this.sealed)return;this.validate();const t=this.entry(e),i=e.mutation,r=t.mutation;if(t.status!=="prepared")throw new I;if(i.entity!==r.entity||i.action!==r.action)throw new I;if(i.id!==r.id)throw new I("id");if(i.action!=="Create"&&M(i.version!==void 0?i.version:i.expectedVersion)!==(r.version??r.expectedVersion))throw new I("version");if(e.comment!==r.comment)throw new I("comment");let o=this.difference(t.root&&i.action==="Update"?t.values:t.input,this.canonical(i.payload??{},t.references));if(o!==void 0)throw new I(o);if(o=this.difference(t.loaded,this.canonical(e.loadedValues(),t.references)),o!==void 0)throw new I(o);return{...r,ledgerKey:i.ledgerKey,ledgerRoot:i.ledgerRoot,payload:N(this.materialize(t.values.values()))}}providerResult(e,t){if(!this.sealed)return;this.validate();const i=this.entry(e);if(i.status!=="prepared")throw new I;i.result={id:t.id,version:t.version},i.status="executed",this.sources.some(r=>r.root===i.root&&A(r.key)===A(i.key))||(i.status="applied")}applied(e,t,i){if(!this.sealed)return;const r=this.entries.find(o=>o.root===e&&A(this.resolved(o.key))===A(t));if(!r||r.status!=="executed"||r.result?.id!==i.id||t.entity!==i.entity)throw new I("id");if(A(t)!==A(i)){if(r.mutation.action!=="Create"||this.aliases.has(A(r.key)))throw new I("id");this.aliases.set(A(r.key),{...i})}r.status="applied",r.state=this.rootState(e,i,r.references);for(const o of this.sources)o.root===e&&A(o.key)===A(t)&&(o.key={...i},o.native=new $(this.canonical(o.read(),o.references)),o.state=this.rootState(e,i,o.references))}committed(e,t){for(const i of this.entries)i.root===e&&A(this.resolved(i.key))===A(t)&&(i.status="committed",i.state=this.rootState(e,t,i.references));for(const i of this.sources)i.root===e&&A(i.key)===A(t)&&(i.state=this.rootState(e,t,i.references))}complete(){if(this.sealed&&(this.validate(),this.entries.some(e=>e.status!=="applied"&&e.status!=="committed")))throw new I}}const ni=new WeakMap,ht=new WeakMap,Lt=new WeakMap,Ui=new WeakMap;function Bi(n){if(!["named-count","facet","relation-count","relation-select","aggregate","pagination"].includes(n.kind)||n.method!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n.method)||n.alias!==void 0&&typeof n.alias!="string"||n.relation!==void 0&&typeof n.relation!="string")throw new Error("QUERY_OPERATION_INVALID: invalid generated operation descriptor");return Object.freeze({kind:n.kind,method:n.method,alias:n.alias,relation:n.relation})}function dr(n){const e=Bi(n),t=i=>"'"+i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+"'";return e.method?e.method+"("+(e.alias!==void 0?t(e.alias):e.kind==="relation-select"?"...":"")+")":"framework: "+e.kind+(e.relation?" "+e.relation:"")+(e.alias!==void 0?" "+t(e.alias):"")}const ge=Symbol("runtime request binding");class hr extends Error{constructor(e,t,i){super(`${e}: ${i} request requires a non-blank ${t}; supply it at the request entry point`),this.code=e,this.field=t,this.requestKind=i,this.name="RequestIntentError"}}function Ee(n,e,t){if(typeof n!="string"||new RegExp("^\\p{White_Space}*$","u").test(n))throw new hr(e==="comment"?"REQUEST_COMMENT_REQUIRED":"QUERY_PURPOSE_REQUIRED",e,t);return n}class it{#e;#t;constructor(e,t){this.#e=Ee(e,"comment","query"),this.#t=Ee(t,"purpose","query"),Object.freeze(this)}get comment(){return this.#e}get purpose(){return this.#t}}class Ie{#e;constructor(e){this.#e=Ee(e,"comment","mutation"),Object.freeze(this)}get comment(){return this.#e}get auditReason(){return this.#e}readbackIntent(){return new it(this.#e,"verify persisted mutation result")}}class L{#e;#t;#n;#r;#i;#o;#s;constructor(e,t,i){const r=e,o=Mt(e),s=o instanceof L?o:void 0;if(this.#e=t===void 0?s?.intent??new it(r?._comment??r?.commentText,r?._purpose??r?.purposeText):new it(t?.comment,t?.purpose),i&&i[ge]!==!0)throw new Error("QUERY_REQUEST_OWNERSHIP_INVALID: request binding is runtime-owned");const a=s&&s.intent.comment===this.#e.comment&&s.purpose===this.#e.purpose?s:void 0;this.#s=i?.invocation??(i?.parent?i.parent.#s:void 0)??(a?a.#s:void 0)??Object.freeze({}),this.#n=i?i.parent:a?.parentRequest,this.#r=Ee(i?.comment??a?.comment??this.#e.comment,"comment","query"),this.#i=i?.name??a?.requestName??String(r.entity??"query"),this.#o=i?.operation??a?.operation,this.#t=N(e);const c=this.#t;for(const[u,l]of[["commentText",this.comment],["purposeText",this.purpose],["_comment",this.comment],["_purpose",this.purpose]])Object.defineProperty(c,u,{value:l,enumerable:!u.startsWith("_"),configurable:!0,writable:!1});ht.set(c,B(i?.source??a?.traceSource??ht.get(e)??mi(String(r.entity),this.intent.comment,this.purpose))),pn(c,this),Object.freeze(this)}get intent(){return this.#e}get query(){return this.#t}get comment(){return this.#r}get purpose(){return this.#e.purpose}get traceSource(){return ht.get(this.#t)}get parentRequest(){return this.#n}get rootRequest(){let e=this;for(;e.parentRequest;)e=e.parentRequest;return e}get requestName(){return this.#i}get operation(){return this.#o}get traceChain(){const e=[];for(let t=this;t;t=t.parentRequest)e.push({kind:"comment",name:t.requestName,detail:t.comment});return B([{kind:"purpose",name:this.rootRequest.requestName,detail:this.purpose},...e.reverse()])}withQuery(e){const t=Mt(e);if(t instanceof L&&t.#s!==this.#s)throw new Error("QUERY_SCOPE_OWNER_MISMATCH: replacement belongs to another query invocation");return new L(e,this.intent,{[ge]:!0,parent:this.parentRequest,comment:this.comment,name:this.requestName,operation:this.operation,source:this.traceSource,invocation:this.#s})}deriveOperation(e,t){const i=Bi(t);return new L(e,this.intent,{[ge]:!0,parent:this,comment:dr(i),name:String(e.entity??this.requestName),operation:i,source:this.traceSource})}deriveHelper(e,t){return new L(e,this.intent,{[ge]:!0,parent:this,comment:Ee(t,"comment","query"),name:String(e.entity??this.requestName),source:this.traceSource})}derive(e,t,i){if(i)return this.deriveOperation(this.query,i).deriveChild(e,t);const r=`${String(this.query.entity)}.${t}`;return this.deriveChild(e,t,void 0,r)}deriveAggregate(e,t,i){const r=this.parentRequest?.operation?.kind==="facet"?this.parentRequest:void 0,o=r?r.deriveHelper(e,"aggregate "+r.operation.relation):this.deriveOperation(e,i),s=[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}],a=new L(e,this.intent,{[ge]:!0,parent:o.parentRequest,comment:o.comment,name:o.requestName,operation:o.operation,source:s});return(e._comment??e.commentText)===void 0?a:a.deriveChild(e)}deriveChild(e,t,i,r){const o=e,s=o._comment??o.commentText;return new L(e,this.intent,{[ge]:!0,parent:this,comment:s===void 0?i??`load ${String(o.entity)}`:Ee(s,"comment","query"),name:r??String(o.entity),source:t===void 0?this.traceSource:[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}]})}}class ce{#e;#t;constructor(e,t){this.#e=new Ie(t===void 0?e?.comment:t?.comment),this.#t={...e},e.payload&&typeof e.payload=="object"&&(this.#t.payload={...e.payload}),Object.defineProperty(this.#t,"comment",{value:this.#e.comment,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get intent(){return this.#e}get mutation(){return this.#t}get comment(){return this.#e.comment}withLoadedSnapshot(e){return ni.set(this,new $(e.values())),this}loadedValues(){return ni.get(this)?.values()??{}}bindCheckerLoadedValues(e){return Object.defineProperty(e,"loadedValues",{value:Object.freeze({...this.loadedValues()}),enumerable:!1,writable:!1,configurable:!1}),e}get graphSession(){return Lt.get(this)?.session}scopeFor(e){const t=Lt.get(this),i=yn(t?.parent,e.entity,e.id,this.comment,t?.localComment);return t&&Ui.set(i,t.session),i}traceFor(e){const t=this.#t,i=t.ledgerRoot?.traceChain(t.ledgerKey??e);return i?.length?B(i):this.scopeFor(e).recover()}auditProjection(e,t,i){const r=[...J(t),...J(this.#t.id),...i?ti(i):J(this.loadedValues()),...ti(this.graphSession?.logBindings)];return Object.freeze({reason:re(this.comment,r),mutationLineage:B(this.traceFor(e).map(o=>({...o,detail:re(o.detail,r)})))})}}class fr{#e;#t;#n=0;#r=!1;#i=new ur;constructor(e){this.#e=new Ie(e?.comment),Object.freeze(this)}get intent(){return this.#e}sealPreparedGraph(){this.#i.seal(),this.#r=!0}get isPreparedSealed(){return this.#r}get preparedRootEntity(){return this.#i.rootEntity}registerSource(e,t,i,r,o){this.#i.register(e,t,i,r,o)}sourceMembers(e){return this.#i.members(e)}captureInputSources(){this.#i.captureInput()}bindExecutionReference(e){this.#i.bind(e)}bindExecutionMetadata(e){this.#i.bindMetadata(e)}capturePreparedMutation(e,t,i){return this.#i.remember(e,t,i)}normalizePreparedMutation(e){return this.#i.normalizeRestored(e)}replayPreparedMutation(e){return this.#i.replay(e)}validatePreparedSources(){this.#i.validate()}recordPreparedResult(e,t){this.#i.providerResult(e,t)}acceptPreparedResult(e,t,i){this.#i.applied(e,t,i)}finishPreparedCommit(e,t){this.#i.committed(e,t)}requirePreparedComplete(){this.#i.complete()}get isPreparedEmpty(){return this.#r&&this.#n===0}recordPreparedMutation(){if(this.#r)throw new Error("GRAPH_PREPARATION_SEALED: cannot add mutations after complete preparation");this.#n++}requireMutationAllowed(){if(this.isPreparedEmpty)throw new Error("GRAPH_PREPARATION_EMPTY: complete graph has no admitted mutations")}discardRestoredFields(e,t,i,r){if(e.entity!==i.entity)throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");e.validate(t.change(i),!t.isNew(i)),r?.discardRestoredFields(t,i)}request(e,t,i){if(t&&Ui.get(t)!==this)throw new Error("GRAPH_TRACE_SCOPE_MISMATCH: parent scope belongs to another graph invocation");const r=new ce(e,this.#e);return Lt.set(r,{session:this,parent:t,localComment:i}),r}captureLogBindings(e){this.#t=q(e,this.#t)}get logBindings(){return this.#t}}class ri extends Error{constructor(e){super("GRAPH_ALREADY_COMMITTED: post-commit processing failed; do not retry as an uncommitted mutation"),this.cause=e,this.committed=!0,this.name="GraphCommittedError"}}const pr="MUTATION-POLICY-001",mr="MUTATION-POLICY-002";class D extends Error{constructor(e){super(e),this.name="MutationPolicyError"}}class Wr{constructor(e){this.resolver=e}resolve(e){return this.resolver(e)}}class Hr{constructor(e){this.finder=e}findApproval(e){return this.finder(e)}}class gr{onWarning(e,t){!t.firstOccurrence||typeof console>"u"||console.warn(`TeaQL mutation policy warning code=${t.warningCode} requestKey=${t.snapshot.requestKey} source=${t.snapshot.source} approval=${t.snapshot.approvalStatus}`)}}let si=0;class yr{constructor(){this.profile={warningSink:new gr},this.emittedWarnings=new Set,this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.remaining=new Map}setRegistry(e){this.profile.registry=e}setApprovalProvider(e){this.profile.approvalProvider=e}setWarningSink(e){this.profile.warningSink=e}beginGraph(){if(this.graphActive)throw new D("mutation policy graph is already active");this.graphActive=!0,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}endGraph(){this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}recordPreflight(e){if(!this.graphActive)return;if(this.graphReviewed)throw new D("mutation preflight cannot change after policy review");const t=oi(e);this.rootEntity??=t.entity,this.auditReason??=Be(e),this.preflight.push(t),this.preflightKeys.push(ci(e,t))}enterMutation(e,t){const i=oi(t);if(!this.graphActive)return{snapshot:this.review(e,this.plan(i.entity,Be(t),[i]))};if(!this.graphReviewed){if(this.profile.registry&&this.preflight.length===0)throw new D("customer mutation policy requires complete graph preflight before provider mutation");if(!this.profile.registry&&this.preflight.length===0)return{snapshot:this.review(e,this.plan(i.entity,Be(t),[i]))};const r=this.preflight.length?this.preflight:[i];this.graphSnapshot=this.review(e,this.plan(this.rootEntity??r[0].entity,this.auditReason??Be(t),r)),this.remaining.clear();const o=this.preflight.length?this.preflightKeys:r.map(Qi);for(const s of o)this.remaining.set(s,(this.remaining.get(s)??0)+1);this.graphReviewed=!0}return this.consume(ci(t,i)),{snapshot:this.graphSnapshot}}prepareGraphReview(e,t){if(!this.graphActive||this.graphReviewed||this.preflight.length===0)return;const i=this.preflight;this.graphSnapshot=this.review(e,this.plan(t??this.rootEntity??i[0].entity,this.auditReason,i)),this.remaining.clear();for(const r of this.preflightKeys)this.remaining.set(r,(this.remaining.get(r)??0)+1);this.graphReviewed=!0}ensureGraphComplete(){if(this.graphReviewed&&this.remaining.size)throw new D("reviewed mutation plan contains operations that were not executed")}review(e,t){br(t);const i=ai(t),r=this.profile.registry?.resolve(i.requestKey);let o,s,a,c;if(!r)o="generated_default",a="not_applicable",c=[pr];else{s=wr(r.identity);const l=r.review(e,i);if(!l||l.verdict!=="allow"&&l.verdict!=="deny")throw new D("customer mutation policy returned an invalid decision");if(l.verdict==="deny")throw new D(`[MUTATION POLICY DENIED] ${l.code||"MUTATION-POLICY-DENIED"}: ${l.message||"mutation rejected"}`);o="customer";const d=this.profile.approvalProvider?.findApproval(s);a=vr(d,s)?"approved":"missing",c=a==="approved"?[]:[mr]}const u=Object.freeze({executionId:i.executionId,requestKey:i.requestKey,source:o,policy:s,approvalStatus:a,warningCodes:Object.freeze([...c]),operations:Object.freeze(i.operations.map(l=>Object.freeze({kind:l.kind,entity:l.entity,entityId:he(l.entityId),changedFields:Object.freeze(Object.keys(l.changedValues).sort())})))});for(const l of c)this.emitWarning(e,u,l);return u}plan(e,t,i){return si+=1,ai({executionId:`teaql-mutation-${si}`,requestKey:`${e}.saveGraph`,rootEntityType:e,auditReason:new Ie(t).comment,operations:i})}consume(e){const t=this.remaining.get(e)??0;if(t<1)throw new D("provider mutation is not present in the reviewed graph plan");t===1?this.remaining.delete(e):this.remaining.set(e,t-1)}emitWarning(e,t,i){const r=t.policy?`${t.policy.policyId}:${t.policy.version}:${t.policy.fingerprint}`:"none",o=`${t.requestKey}|${r}|${i}`,s=!this.emittedWarnings.has(o);this.emittedWarnings.add(o);try{this.profile.warningSink.onWarning(e,Object.freeze({snapshot:t,warningCode:i,firstOccurrence:s}))}catch{}}}function oi(n){const e=String(n?.entity??"").trim(),t=String(n?.action??"").toLowerCase(),i={create:"create",update:"update",delete:"delete",recover:"recover"};if(!e||!i[t])throw new D("mutation must contain a supported entity operation");const r=n?.payload&&typeof n.payload=="object"?n.payload:{};return Object.freeze({kind:i[t],entity:e,entityId:he(n?.id??r.id),originalVersion:n?.version??n?.expectedVersion,changedValues:Ki(r)})}function Be(n){return new Ie(n?.comment).comment}function br(n){if(new Ie(n?.auditReason),!n.executionId?.trim())throw new D("execution id is required");if(!n.requestKey?.trim())throw new D("request key is required");if(!n.rootEntityType?.trim())throw new D("root entity type is required");if(!n.operations.length)throw new D("mutation plan is empty")}function wr(n){if(!n||!n.policyId?.trim()||!n.version?.trim()||!n.fingerprint?.trim())throw new D("customer mutation policy identity is invalid");return Object.freeze({policyId:n.policyId.trim(),version:n.version.trim(),fingerprint:n.fingerprint.trim()})}function vr(n,e){return!!n&&Sr(n.policy,e)&&!!n.approvedBy?.trim()&&n.approvedAt instanceof Date&&Number.isFinite(n.approvedAt.getTime())&&n.approvedAt.getTime()!==0}function Sr(n,e){return n.policyId===e.policyId&&n.version===e.version&&n.fingerprint===e.fingerprint}function ai(n){return Object.freeze({executionId:n.executionId,requestKey:n.requestKey,rootEntityType:n.rootEntityType,auditReason:n.auditReason,operations:Object.freeze(n.operations.map(e=>Object.freeze({kind:e.kind,entity:e.entity,entityId:he(e.entityId),originalVersion:e.originalVersion,changedValues:Ki(e.changedValues)})))})}function he(n,e=new WeakSet){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return n;if(n instanceof Date)return n.toISOString();if(typeof n=="object"){if(e.has(n))throw new D("mutation policy values must not contain cycles");e.add(n);try{if(Array.isArray(n))return Object.freeze(n.map(i=>he(i,e)));const t=n;return"id"in t&&Object.keys(t).some(i=>i!=="id")?he(t.id,e):Object.freeze(Object.fromEntries(Object.entries(t).map(([i,r])=>[i,he(r,e)])))}finally{e.delete(n)}}return String(n)}function Ki(n){return Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>[e,he(t)])))}function Qi(n){return nt({kind:n.kind,entity:n.entity,entityId:n.entityId,originalVersion:n.originalVersion,changedValues:n.changedValues})}function ci(n,e){const t=n?.ledgerKey;return t&&typeof t=="object"&&String(t.entity??"").trim()&&t.id!==void 0&&t.id!==null?`ledger:${String(t.entity).trim()}:${nt(t.id)}`:`operation:${Qi(e)}`}function nt(n){return typeof n=="bigint"?JSON.stringify(`${n.toString()}n`):n===void 0?'""':n===null||typeof n!="object"?JSON.stringify(n):Array.isArray(n)?`[${n.map(nt).join(",")}]`:`{${Object.entries(n).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${nt(t)}`).join(",")}}`}const li=new WeakMap;let Er=1;function Or(n){if(!n||typeof n!="object"&&typeof n!="function")return String(n);const e=n;let t=li.get(e);return t||(t=Er++,li.set(e,t)),String(t)}class ft extends Error{constructor(e,t,i){super(`context root ${e}: expected ${t}`),this.reason=e,this.expectedType=t,this.activeRoot=i,this.name="ContextRootError"}}class rt{constructor(e=er()){this.businessClock=new ir,this.mutationPolicy=new yr,this.resources=new Map,this.continuousPageCursors=new Map,this.retainedIdSets=new Map,this.idSetBuilds=new Map,this.continuousPageRuntime={owner:"",get:(t,i)=>this.getContinuousPageCursor(t,i),put:(t,i,r)=>this.putContinuousPageCursor(t,i,r),observe:(t,i)=>{this.continuousPagePlan=t,this.continuousPageCursorId=i}},this.idSetPaginationRuntime={owner:"",scope:"",get:t=>this.idSetStore().get(t),put:(t,i)=>this.idSetStore().put(t,i),build:(t,i)=>this.singleFlightIdSetBuild(t,i),observe:(t,i)=>{this.idSetPaginationPlan=t,this.idSetPaginationCount=i,this.idSetPaginationCountAccuracy=t==="ID_SET_BUILD"||t==="ID_SET_HIT"?"EXACT":t==="ID_SET_FALLBACK_LIMIT_EXCEEDED"?"LOWER_BOUND":"UNKNOWN"}},this.userIdentifier="",this.continuousPagePlan="DISABLED",this.idSetPaginationPlan="ID_SET_DISABLED",this.idSetPaginationCountAccuracy="UNKNOWN",this.locale="en",this.i18nCatalog=$e.builtin,this.naturalCatalog=oe.builtin,this.naturalModel=te.empty,this.naturalRenderer=Ti,this.naturalWarning=t=>{this.runtimeLogger.write("WARN","checker.warning","TeaQL checker warning",{category:"VALIDATION",error_code:t})},this.runtimeLogger=e}withInternalIdGenerator(e){if(!e||typeof e.generateId!="function")throw new TypeError("Internal ID generator must provide generateId(entity, context)");return this.insertResource("idGenerator",e)}async generateInternalId(e){if(typeof e!="string"||!e.trim()||e!==e.trim())throw new TypeError("Internal ID entity type is required");if(this.resources.has("idGenerator")){const i=this.getResource("idGenerator");if(!i||typeof i.generateId!="function")throw new TypeError("Configured internal ID generator must provide generateId(entity, context)");return jt(await i.generateId(e,this))}const t=this.requireResource("dataService");if(typeof t.reserveInternalId!="function")throw new TypeError("Configured data service must provide reserveInternalId(entity, context)");return jt(await t.reserveInternalId(e,this))}withBusinessClock(e){if(!e||typeof e.now!="function")throw new TypeError("Business clock must provide now()");return this.businessClock=e,this}businessTime(){const e=this.businessClock.now();if(!(e instanceof Date)||!Number.isFinite(e.getTime()))throw new TypeError("Business clock returned an invalid Date");return new Date(e.getTime())}businessDate(){return this.businessTime().toISOString().slice(0,10)}withObjectStorage(e){return this.insertResource("objectStorageProvider",e)}withObjectStorageObserver(e){return this.insertResource("objectStorageObserver",e)}objectStorage(e){return new or(this,e)}async withQueryRequest(e,t){const i=this.requireResource("dataService");return i.withQueryRequest?i.withQueryRequest(e,t):t()}get checkerPresentationModel(){return this.naturalModel}installCheckerPresentationModel(e){if(!(e instanceof te))throw new TypeError("Checker presentation model required");return this.naturalModel=e,this}installCheckerMessageCatalog(e){const t=oe.fromJson(e);return this.naturalCatalog=t,this}installCheckerMessageRenderer(e){if(typeof e!="function")throw new TypeError("Checker renderer required");return this.naturalRenderer=e,this}installCheckerMessageWarning(e){if(typeof e!="function")throw new TypeError("Checker warning sink required");return this.naturalWarning=e,this}captureCheckerMessages(e=te.empty){return Object.freeze({model:this.naturalModel===te.empty?e:this.naturalModel,catalog:this.naturalCatalog,legacy:this.i18nCatalog,locale:ke(this.locale),renderer:this.naturalRenderer,warning:this.naturalWarning})}translateCheckResultsFrom(e,t,i={}){const r=this.captureCheckerMessages(i.defaultModel).model,o=_i(t,Object.freeze({model:r,entity:e}));return t.splice(0,t.length,...o),Si(this,t,e,i.privacyPolicy??(()=>{}),i.checkedValues??[]),t}renderCheckerGraphResults(e,t,i){if(t.legacy.translate!==$e.prototype.translate||this.translateCheckResults!==rt.prototype.translateCheckResults)return[...e];const r=Ye(e),o=new Set;try{return r.finish(r.values.map(s=>Qt(t,s,o,i)))}finally{r.close()}}setLocaleCode(e){const t=ke(e);return this.locale=t,this}setLanguageCode(e){return this.setLocaleCode(e)}installI18nCatalog(e){if(!e)throw new Error("catalog is required");return this.i18nCatalog=e,this}installIdSetPaginationStore(e){if(!e)throw new Error("ID set pagination store is required");return this.insertResource("idSetPaginationStore",e)}translateCheckResults(e,t){if(!e.length)return e;const i=Ye(e,t);try{const r=this.i18nCatalog.translate!==$e.prototype.translate,o=this.captureCheckerMessages(),s=new Set,a=i.values.map(c=>r?this.i18nCatalog.translate(c,this.locale):Qt(o,c,s));return e.splice(0,e.length,...i.finish(a)),e}finally{i.close()}}withMutationPolicyRegistry(e){if(!e||typeof e.resolve!="function")throw new TypeError("mutation policy registry must expose resolve(requestKey)");return this.mutationPolicy.setRegistry(e),this}withMutationPolicyApprovalProvider(e){if(!e||typeof e.findApproval!="function")throw new TypeError("mutation policy approval provider must expose findApproval(identity)");return this.mutationPolicy.setApprovalProvider(e),this}withMutationGovernanceSink(e){if(!e||typeof e.onWarning!="function")throw new TypeError("mutation governance sink must expose onWarning(context, warning)");return this.mutationPolicy.setWarningSink(e),this}reviewMutationPlan(e){return this.mutationPolicy.review(this,e)}beginMutationPolicyGraph(){this.mutationPolicy.beginGraph()}prepareMutationPolicyGraph(e){this.mutationPolicy.prepareGraphReview(this,e)}recordMutationPolicyPreflight(e){this.mutationPolicy.recordPreflight(e)}enterMutationPolicy(e){return this.mutationPolicy.enterMutation(this,e).snapshot}ensureMutationPolicyGraphComplete(){this.mutationPolicy.ensureGraphComplete()}endMutationPolicyGraph(){this.mutationPolicy.endGraph()}beginFixEvidence(){return this.insertResource("fixEvidenceCurrent",[])}recordFixEvidence(e){const t=String(e.sourceLabel||""),i=t.toLowerCase();if(!e.entityType||!e.modelPath||!t||i.includes("authorization")||i.includes("cookie")||i.includes("token="))throw new TypeError("Fix evidence must contain only safe framework provenance labels");const r=this.getResource("fixEvidenceCurrent")??[];return this.getResource("fixEvidenceCurrent")||this.insertResource("fixEvidenceCurrent",r),r.push(Object.freeze({...e})),this}finishFixEvidence(){const e=this.getResource("fixEvidenceCurrent")??[];return this.insertResource("fixEvidenceLast",Object.freeze([...e])),this.removeResource("fixEvidenceCurrent")}lastFixEvidence(){return this.getResource("fixEvidenceLast")??[]}insertResource(e,t){return this.resources.set(e,t),this}getResource(e){return this.resources.get(e)}removeResource(e){return this.resources.delete(e),this}requireResource(e){const t=this.getResource(e);if(t===void 0)throw new Error(`Required UserContext resource is missing: ${e}`);return t}ensureSchema(){const e=this.requireResource("dataService"),t=e[Di];if(!t)throw new Error("Configured dataService is not a schema-aware TeaQL provider");return t.call(e,this)}withActiveRoot(e){if(!e||!e.entity||e.id===void 0||e.id===null)throw new TypeError("active root must be a typed entity reference");return this.insertResource("activeRoot",Object.freeze({...e}))}requireActiveRoot(e){const t=this.getResource("activeRoot");if(!t)throw new ft("missing",e);if(t.entity!==e)throw new ft("type_mismatch",e,t);const i=t.id;if(!(typeof i=="number"?Number.isSafeInteger(i)&&i>0:typeof i=="bigint"?i>0n:typeof i=="string"&&/^[1-9][0-9]*$/.test(i)))throw new ft("invalid_id",e,t);return t}prepareQuery(e){this.continuousPageRuntime.owner=this.userIdentifier,this.idSetPaginationRuntime.owner=this.userIdentifier;const t=this.getResource("activeRoot");return this.idSetPaginationRuntime.scope=[this.userIdentifier,t?`${t.entity}:${String(t.id)}`:"-",Or(this.getResource("dataService"))].join("|"),e.bindContinuousPageRuntime(this.continuousPageRuntime).bindIdSetPaginationRuntime(this.idSetPaginationRuntime)}getContinuousPageCursor(e,t){const i=`${e}:${t}`,r=this.continuousPageCursors.get(i);if(r&&r.expiresAt<=Date.now()){this.continuousPageCursors.delete(i);return}return r}putContinuousPageCursor(e,t,i){if(this.continuousPageCursors.size>=4096){const r=[...this.continuousPageCursors.entries()].sort((o,s)=>o[1].expiresAt-s[1].expiresAt)[0];r&&this.continuousPageCursors.delete(r[0])}this.continuousPageCursors.set(`${e}:${t}`,i)}getRetainedIdSet(e){const t=this.retainedIdSets.get(e);if(t&&t.expiresAt<=Date.now()){this.retainedIdSets.delete(e);return}return t}idSetStore(){return this.getResource("idSetPaginationStore")??{get:e=>this.getRetainedIdSet(e),put:(e,t)=>this.putRetainedIdSet(e,t),invalidate:e=>{this.retainedIdSets.delete(e)}}}putRetainedIdSet(e,t){if(t.ids.byteLength>268435456)throw new Error("ID set exceeds the process-local store memory ceiling");const r=()=>[...this.retainedIdSets.values()].reduce((o,s)=>o+s.ids.byteLength,0);for(;this.retainedIdSets.size>=64||r()+t.ids.byteLength>268435456;){const o=[...this.retainedIdSets.entries()].sort((s,a)=>s[1].expiresAt-a[1].expiresAt)[0];if(!o)break;this.retainedIdSets.delete(o[0])}this.retainedIdSets.set(e,t)}async singleFlightIdSetBuild(e,t){const i=this.idSetBuilds.get(e);if(i)return{value:await i,built:!1};const r=t();this.idSetBuilds.set(e,r);try{return{value:await r,built:!0}}finally{this.idSetBuilds.delete(e)}}}function ui(n,e,t){if(!(n==null||typeof n=="number"&&Number.isInteger(n)&&n>=-2147483648&&n<=2147483647))return new G([{ruleId:"invalid_type",entityType:e,location:F.property(t),message:`Invalid field ${t}: expected an exact signed 32-bit Integer`}])}class Ge{constructor(e,t){this.entityType=e;const i=[];for(const[r,o]of Object.entries(t?.columns??{})){if(o.integer32!==void 0&&typeof o.integer32!="boolean")throw new TypeError("INVALID_INTEGER32_METADATA");if(!o.integer32)continue;const s=o.modelName??r;if(o.logicalType!=="integer"||o.decode!=="number"||["id","version"].includes(r)||["id","version"].includes(s)||Object.values(t?.relations??{}).some(a=>!a.many&&a.localKey===r))throw new TypeError(`INVALID_INTEGER32_METADATA: ${e}.${s}`);i.push(Object.freeze({native:r,canonical:s,column:o.columnName}))}this.fields=Object.freeze(i),Object.freeze(this)}checkMutation(e,t=[]){for(const i of this.fields){const r=ui(e[i.canonical],this.entityType,i.canonical);r&&!t.some(o=>o.ruleId==="invalid_type"&&o.location.modelPath()===i.canonical)&&t.push(...r.violations)}return t}read(e,t){const i=this.fields.find(o=>o.native===e);if(!i||t==null)return t;if(typeof t=="bigint"&&t>=-2147483648n&&t<=2147483647n)return Number(t);const r=ui(t,this.entityType,i.canonical);if(r)throw r;return t}}function Gi(n){for(const[e,t]of Object.entries(n))new Ge(e,t)}function Wi(n,e){const t=n.defaultDomainRoot,i=e.defaultDomainRoot;if(t&&i&&(t.entity!==i.entity||t.id!==i.id))throw new Error("Cannot compose Runtime Modules with different Default Domain Roots");const r=new Map;for(const o of[...n.constants??[],...e.constants??[]])r.set(`${o.entity}:${o.id}`,o);return{defaultDomainRoot:i??t,constants:[...r.values()],ensure:n.ensure&&e.ensure?async o=>{await n.ensure(o),await e.ensure(o)}:e.ensure??n.ensure}}class It{constructor(e={},t={},i={},r=te.empty){Gi(e),this.schemas=Object.freeze({...e}),this.checkers=Object.freeze({...t}),this.checkerPresentationModel=r,this.bootstrap=Object.freeze({defaultDomainRoot:i.defaultDomainRoot,constants:Object.freeze([...i.constants??[]]),ensure:i.ensure})}and(e){return new It({...this.schemas,...e.schemas},{...this.checkers,...e.checkers},Wi(this.bootstrap,e.bootstrap),this.checkerPresentationModel.merge(e.checkerPresentationModel))}withCheckerPresentation(e){return new It({...this.schemas},{...this.checkers},this.bootstrap,this.checkerPresentationModel.merge(e))}}class Y{constructor(e,t,i){this.field=e,this.expr=t,this.direction=i}static new(e,t){return new Y(e,null,t)}static expr(e,t){return new Y("",e,t)}static asc(e){return Y.new(e,"Asc")}static desc(e){return Y.new(e,"Desc")}}class st{constructor(e,t,i,r){this.enabledValue=e,this.cacheExpiredMillis=t,this.propagateValue=i,this.propagateCacheExpiredMillis=r}static enabled(e){return new st(!0,e,!1,0)}propagate(e){return this.propagateValue=!0,this.propagateCacheExpiredMillis=e,this}}let jr=class Hi{constructor(e){this.hardLimitValue=1e4,this.filterCondition=null,this.limitValue=0,this.offsetValue=0,this.orderItems=[],this.selectItems=[],this.properties=[],this.joins=[],this.groupByItems=[],this.aggregateItems=[],this.facets=[],this.relations=[],this.relationAggregates=[],this.deletionVisibility="live",this.entity=e,Object.defineProperty(this,"hardLimitValue",{enumerable:!1,writable:!0,value:1e4}),Object.defineProperty(this,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"topNProbeThreshold",{enumerable:!1,writable:!0,value:void 0})}comment(e){return this.commentText=e,this}purpose(e){return this.purposeText=e,this}facetBy(e,t,i,r=!0,o){return this.facets.push({facetName:e,relationName:t,query:i.toQuery(),includeAllFacets:r,operation:o}),this}clone(){const e=N(this);for(const t of["commentText","purposeText","_comment","_purpose"]){const i=Object.getOwnPropertyDescriptor(e,t);i&&"value"in i&&i.configurable&&Object.defineProperty(e,t,{...i,writable:!0})}return e}filter(e){return this.filterCondition=e,this}withDeletedRows(){return this.deletionVisibility="all",this}deletedRowsOnly(){return this.deletionVisibility="deleted",this}limit(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.limitValue=e,this}optimizeForContinuousPageFetch(){return this.optimizeForContinuousPageFetchWith("default",600)}optimizeForContinuousPageFetchWith(e,t){if(!e?.trim())throw new Error("continuous page namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("continuous page ttlSeconds must be a positive integer");return this.continuousPageFetchOptions={namespace:e,ttlSeconds:t},this}bindContinuousPageRuntime(e){return this.continuousPageRuntimeContext=e,this}localContinuousPageOptions(){return this.continuousPageFetchOptions}localContinuousPageRuntime(){return this.continuousPageRuntimeContext}clearContinuousPageRuntime(){return this.continuousPageRuntimeContext=void 0,this}optimizePaginationWithIdSet(){return this.optimizePaginationWithIdSetConfig("default",600,3e6)}optimizePaginationWithIdSetConfig(e,t,i){if(!e?.trim())throw new Error("ID set namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("ID set ttlSeconds must be a positive integer");if(!Number.isSafeInteger(i)||i<=0)throw new Error("ID set maxIds must be a positive integer");return this.idSetPaginationOptions={namespace:e,ttlSeconds:t,maxIds:i},this}bindIdSetPaginationRuntime(e){return this.idSetPaginationRuntimeContext=e,this}localIdSetPaginationOptions(){return this.idSetPaginationOptions}localIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext}clearIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext=void 0,this}topNProbeParentThreshold(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("topNProbeParentThreshold must be a non-negative safe integer");return this.topNProbeThreshold=e,this}localTopNProbeParentThreshold(){return this.topNProbeThreshold}prepareForList(){if(!Number.isSafeInteger(this.offsetValue)||this.offsetValue<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");if(this.limitValue&&(!Number.isSafeInteger(this.limitValue)||this.limitValue<1))throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.applyListLimit(this.hardLimitValue),this}forExactCount(e="__teaql_total"){const t=new Hi(this.entity);return t.filterCondition=N(this.filterCondition),t.commentText=this.commentText,t.purposeText=this.purposeText,t.deletionVisibility=this.deletionVisibility,t.aggregate("Count","id",e),je(this,t),t}applyListLimit(e){if(this.limitValue||(this.limitValue=e),this.limitValue>e)throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${e}`)}offset(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");return this.offsetValue=e,this}relation(e){return this.relations.push({name:e}),this}relationQuery(e,t,i="id",r="id",o=!0,s){return this.relations.push({name:e,query:t,localKey:i,foreignKey:r,many:o,operation:s}),this}relationAggregate(e,t,i,r=!0,o){return this.relationAggregates.push({relationName:e,alias:t,query:i,singleResult:r,operation:o}),this}order(e){return this.orderItems.push(e),this}select(e){return this.selectItems.push(...e),this}enableAggregationCacheFor(e){return this.aggregationCache=st.enabled(e),this}propagateAggregationCache(e){return this.aggregationCache||(this.aggregationCache=st.enabled(0)),this.aggregationCache.propagate(e),this}aggregate(e,t,i){return this.aggregateItems.push({function:e,field:t,alias:i}),this}groupBy(e,t){if(t!==void 0){if(typeof t!="string"||!t.trim())throw new TypeError("Group alias must be a non-empty string");const i=this.groupByAliases?.[e];if(i!==void 0&&i!==t)throw new Error("Grouping field already has a different alias");this.groupByAliases??=Object.create(null),this.groupByAliases[e]=t}return this.groupByItems.push(e),this}};function kr(n,e){if(n.logMode!=="masked")throw new Error("Telemetry requires safe SQL projection");const t=(i=[])=>JSON.stringify(i.map(r=>({kind:r.kind,name:r.name,detail:r.detail??""})));return Object.freeze({body:"TeaQL SQL execution",correlation:e,attributes:Object.freeze({"teaql.trace_chain":t(n.traceChain),"teaql.trace_path":t(n.tracePath),"teaql.mutation_lineage":t(n.mutationLineage),"teaql.intent.comment":n.comment??n.auditReason??"","teaql.intent.purpose":n.purpose??"","teaql.sql.debug":n.debugSQL,"teaql.sql.log_mode":n.logMode,"teaql.sql.operation":n.operation,"teaql.sql.outcome":n.executionOutcome??"unknown","teaql.sql.elapsed_us":n.elapsedMicros,...n.resultCount===void 0?{}:{"teaql.sql.result_count":n.resultCount},...n.affectedRows===void 0?{}:{"teaql.sql.affected_rows":n.affectedRows}})})}function pt(n,e=!1){try{e?console.warn(n):console.info(n)}catch{}}class ee extends Array{static get[Symbol.species](){return Array}constructor(e=[],t={}){if(super(),typeof e=="number")this.length=e;else for(const i of e)super.push(i);Object.setPrototypeOf(this,ee.prototype),t.totalCount!==void 0&&di(t.totalCount),this.totalCount=t.totalCount,this.aggregations=Oe(t.aggregations??{}),this.summary=Oe(t.summary??{}),this.facets=Oe(t.facets??{}),this.isLoaded=t.isLoaded??!0}static empty(){return new ee([],{isLoaded:!1})}get data(){return this}withTotalCount(e){return di(e),this.totalCount=e,this}withFacet(e,t){return this.facets[e]=t,this}facet(e){return this.facets[e]}totalCountOrLength(){return this.totalCount??this.length}mapSmart(e){return new ee(Array.from(this,e),{totalCount:this.totalCount,aggregations:this.aggregations,summary:this.summary,facets:this.facets,isLoaded:this.isLoaded})}filterSmart(e){return new ee(this.filter(e),{isLoaded:this.isLoaded})}flatMapSmart(e){return new ee(this.flatMap((t,i)=>Array.from(e(t,i))),{isLoaded:this.isLoaded})}get(e){return Number.isInteger(e)&&e>=0&&e=this.length?!1:(this[e]=t,!0)}first(){return this.get(0)}last(){return this.get(this.length-1)}mergeBy(e,t){const i=new Map;this.forEach((r,o)=>i.set(t(r),o));for(const r of e){const o=t(r),s=i.get(o);s!==void 0?this[s]=r:(i.set(o,this.length),this.push(r))}}identityMap(e){return new Map(Array.from(this,t=>[e(t),t]))}groupBy(e){const t=new Map;for(const i of this){const r=e(i),o=t.get(r)??[];o.push(i),t.set(r,o)}return t}ids(){return Array.from(this,e=>e.id??null)}mapById(){const e=new Map;for(const t of this)t.id!==void 0&&t.id!==null&&e.set(t.id,t);return e}versions(){return Array.from(this,e=>e.version??null)}removeFacet(e){const t=this.facets[e];return delete this.facets[e],t}takeFacets(){const e=this.facets;return this.facets={},e}}function di(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("totalCount must be an exact non-negative safe integer")}function Oe(n){return n instanceof ee?n.mapSmart(Oe):n instanceof Date?new Date(n.getTime()):Array.isArray(n)?n.map(Oe):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Oe(t)])):n}function Tr(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Pt(n){if(n&&typeof n=="object"){const e=n;return e.id??e.Id}return n}function Lr(n,e){const t=Tr(e);for(const i of[e,`${e}Id`,t,`${t}_id`]){const r=Pt(n[i]);if(r!=null)return r}}function Ir(n){return n.function.toLowerCase()==="count"?0:null}function Pr(n,e){return typeof n=="number"&&typeof e=="number"?n-e:n instanceof Date&&e instanceof Date?n.getTime()-e.getTime():String(n).localeCompare(String(e))}async function _r(n,e,t,i,r,o){const s=i.clone();s.facets=[],s.relations=[],s.relationAggregates=[],s.orderItems=[],s.aggregateItems=[],s.groupByItems=[],s.groupByAliases=void 0,s.offsetValue=0,s.limitValue=0,s.selectItems=[...new Set([r,...o.map(l=>l.field)])],s.comment(`aggregate ${r}`),je(i,s);const a=await n.executeQuery(t.deriveHelper(e(s),`aggregate ${r}`).query),c=new Map,u=new Map;for(const l of a){const d=Lr(l,r);if(d==null)continue;const h=String(d),f=c.get(h)??{},p=u.get(h)??{};for(const m of o){const b=m.function.toLowerCase(),g=l[m.field];if(b==="count")g!=null&&(f[m.alias]=Number(f[m.alias]??0)+1);else if(b==="sum"||b==="avg"){if(g!=null){const y=Number(g);if(!Number.isFinite(y))throw new Error(`Facet aggregate ${m.alias} requires numeric values`);f[m.alias]=Number(f[m.alias]??0)+y,b==="avg"&&(p[m.alias]=(p[m.alias]??0)+1)}}else if(b==="min"||b==="max"){if(g!=null){const y=f[m.alias],O=y==null?0:Pr(g,y);(y==null||b==="min"&&O<0||b==="max"&&O>0)&&(f[m.alias]=g)}}else throw new Error(`Unsupported facet aggregate: ${m.function}`)}c.set(h,f),u.set(h,p)}for(const[l,d]of c){const h=u.get(l)??{};for(const f of o){if(f.function.toLowerCase()!=="avg")continue;const p=h[f.alias]??0;d[f.alias]=p?Number(d[f.alias]??0)/p:null}}return c}async function Xi(n,e,t,i){const r=new L(t);t=r.query;const o={};for(const s of i){const a=r.deriveOperation(t,s.operation??{kind:"facet",relation:s.relationName,alias:s.facetName}),c=a.deriveChild(s.query.clone(),s.relationName),u=c.query,l=u.facets;u.facets=[];const d=u.aggregateItems.map(g=>({function:String(g.function),field:String(g.field),alias:String(g.alias)})),h=d.length?d:[{function:"Count",field:"id",alias:"__teaql_facet_membership_count"}];let f;if(n.executeFacetAggregates)f=await n.executeFacetAggregates(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName,h);else if(n.executeFacetMembership&&h.every(g=>g.function.toLowerCase()==="count")){const g=await n.executeFacetMembership(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName);f=new Map([...g].map(([y,O])=>[y,Object.fromEntries(h.map(w=>[w.alias,O]))]))}else f=await _r(n,e,a,t,s.relationName,h);u.aggregateItems=[],u.groupByItems=[],u.groupByAliases=void 0;for(const g of u.relationAggregates){if(g.query.entity!==t.entity)continue;const y=t.clone();y.selectItems=["id"],y.properties=[],y.relations=[],y.relationAggregates=[],y.facets=[],y.aggregateItems=[],y.groupByItems=[],y.groupByAliases=void 0,y.orderItems=[],y.offsetValue=0,y.limitValue=0;const O={id:{$inSubquery:{query:y,field:"id"}}};g.query.filterCondition=g.query.filterCondition?{$and:[g.query.filterCondition,O]}:O,je(t,g.query)}if(!s.includeAllFacets){const g={id:{$in:[...f.keys()]}};u.filterCondition=u.filterCondition?{$and:[u.filterCondition,g]}:g}je(t,u);const m=(await n.executeQuery(c.withQuery(e(u)).query)).map(g=>{const y=String(Pt(g.id??g.Id)),O=f.get(y),w={...g};for(const E of d)w[E.alias]=O?.[E.alias]??Ir(E);return w}).filter(g=>s.includeAllFacets||f.has(String(Pt(g.id??g.Id)))),b=new ee(m);l.length&&(b.facets=await Xi(n,e,c.withQuery(u).query,l)),o[s.facetName]=b}return o}function Ar(n){const e=new Map;for(const t of Object.values(n))for(const i of Object.values(t.relations||{})){if(!i.many)continue;const r=n[i.targetEntity],o=r?.columns[i.foreignKey]?.columnName,s=r?.columns.id?.columnName;if(!r||!o||!s)continue;const a=`idx_${r.table}_${o}_${s}`;let c=2166136261;for(let d=0;d>>0).toString(36),l=a.length<=30?a:`${a.slice(0,Math.max(1,29-u.length))}_${u}`;e.set(l,{name:l,table:r.table,foreignColumn:o,idColumn:s})}return[...e.values()]}async function Rr(n,e,t,i){const r=Number(i);if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ID space floor ${i} for ${t}`);for(let o=1;o<=100;o+=1){const s=await n.query(`SELECT current_level AS id FROM teaql_id_space WHERE type_name = ${e(1)}`,[t]);if(!s.rowCount){try{if((await n.query(`INSERT INTO teaql_id_space(type_name, current_level) VALUES (${e(1)}, ${e(2)})`,[t,r])).rowCount===1)return}catch(u){if(!(await n.query(`SELECT current_level FROM teaql_id_space WHERE type_name = ${e(1)}`,[t])).rowCount)throw u}continue}const a=Number(s.rows[0].id);if(a>=r)return;const c=await n.query(`UPDATE teaql_id_space SET current_level = ${e(1)} WHERE type_name = ${e(2)} AND current_level = ${e(3)}`,[r,t,a]);if(c.rowCount===1)return;if(c.rowCount!==0)throw new Error(`ID space floor update for ${t} changed ${c.rowCount} rows on attempt ${o}`)}throw new Error(`Unable to synchronize ID space floor for ${t} after 100 optimistic-lock attempts`)}function Cr(n,e){return n===e?!0:(n instanceof Date&&(n=n.getTime()),e instanceof Date&&(e=e.getTime()),n!=null&&e!==null&&e!==void 0&&String(n)===String(e))}function We(n){return Object.freeze(n.map((e,t)=>Object.freeze({...e,level:t})))}function mt(n,e,t,i,r,o){const s=n.traceFor({entity:String(e.entity),id:r}),a=gt([...s,{kind:"entity",name:String(e.entity),entityId:r,detail:""}],t,i);return{auditReason:n.comment,tracePath:We(a.tracePath),mutationLineage:s,targetID:r,inheritedBindings:q(o,n.graphSession?.logBindings)}}class $r{constructor(e){this.logger=e}write(e){const t=Vi(e),i=t.executionOutcome??"unknown";this.logger().write(i==="failure"||i==="cancelled"?"ERROR":i==="retrying"?"WARN":"INFO",i==="retrying"?"sql.retry":`sql.${i}`,"TeaQL SQL execution",{category:"SQL",outcome:i,sql:t.debugSQL,comment:t.comment,purpose:t.purpose,audit_reason:t.auditReason,trace_chain:t.traceChain,trace_path:t.tracePath,mutation_lineage:t.mutationLineage,elapsed_us:t.elapsedMicros,result_count:t.resultCount,affected_rows:t.affectedRows,omission_reason:t.omissionReason,trace_id:t.telemetryCorrelation?.traceId})}}class Xr{constructor(){this.mode="all",this.entries=[]}record(e){const t=e.operation==="select";this.mode==="disabled"||this.mode==="select"&&!t||this.mode==="mutation"&&t||this.entries.push(Object.freeze({...e,...e.traceChain?{traceChain:B(e.traceChain)}:{},parameters:Object.freeze([...e.parameters])}))}setMode(e){return this.mode=e,this.entries=[],this}enableAll(){return this.setMode("all")}enableSelect(){return this.setMode("select")}enableMutation(){return this.setMode("mutation")}disable(){return this.setMode("disabled")}snapshot(){return[...this.entries]}}class Nr{constructor(e,t){this.driver=e,this.bootstrapTail=Promise.resolve(),this.sqlTrace=[],this.internalQueryToken=Symbol("teaql-internal-query"),this.bindLogPolicies=new WeakMap,this.bindOperandSources=new WeakMap,this.derivedQueryBindings=new WeakMap,this.derivedRelationAssembly=new WeakMap,this.checkerPrivacyPolicy=(i,r)=>{const o=i?this.schemas[i]:void 0;if(!o)return;const s=Object.keys(o.columns).find(c=>c===r||o.columns[c].modelName===r||o.columns[c].columnName===r)??r,a=this.fieldLogPolicy(o,s);return a==="masked"||a==="credential"?a:void 0},this.auditEvents=[],this.diagnosticSQLLogSink=new $r(()=>this.userContext.runtimeLogger),this.queryLoggingEnabled=!0,this.mutationLoggingEnabled=!0,this.customTelemetry=!1,this.checkers={},this.checkerPresentationModel=te.empty,this.userContext=new rt,this.bootstrap={},this.graphAuditActions=[],this.graphCommitActions=[],this.graphRollbackActions=[],this.graphSaveTail=Promise.resolve(),Gi(t),this.schemas={...t}}fieldLogPolicy(e,t){const i=e.columns[t],r=i?.modelName??i?.columnName??t;return fe(r)||fe(t)?"credential":e.auditMaskFields?e.auditMaskFields?.includes(r)||e.auditMaskFields?.includes(t)?"masked":i?.logPolicy??"unknown":"unknown"}bindValue(e,t,i,r){const o=this.bindLogPolicies.get(e)??e.map(()=>"unknown");e.push(t),o.push(i),this.bindLogPolicies.set(e,o),r!==void 0&&this.bindOperandSources.set(e,q({parameterizedSQL:"",parameters:[r],parameterLogPolicies:[i],sqlOrigin:"generated"},this.bindOperandSources.get(e)))}queryLogBindings(e,t){return q({parameterizedSQL:e,parameters:t,parameterLogPolicies:this.bindLogPolicies.get(t),sqlOrigin:"generated"},this.bindOperandSources.get(t))}install(e){const t=this.checkerPresentationModel.merge(e.checkerPresentationModel);return Object.assign(this.schemas,e.schemas),Object.assign(this.checkers,e.checkers),this.bootstrap=Wi(this.bootstrap,e.bootstrap),this.checkerPresentationModel=t,this}setUserContext(e){return this.userContext=e,this}async reserveInternalId(e,t){if(!(t instanceof rt))throw new TypeError("UserContext is required for ID reservation");if(this.schema(e),this.activeGraph)throw new Error("Internal ID reservation is not allowed inside an active graph save");const i=this.graphSaveTail;let r;this.graphSaveTail=new Promise(o=>{r=o}),await i;try{return await this.driver.transaction(async o=>{const s=jt(await this.driver.nextId(o,e));if(!Number.isSafeInteger(Number(s)))throw new RangeError("SQL internal ID space exhausted its exact integer range");return s})}finally{r()}}schema(e){const t=this.schemas[e];if(!t)throw new Error(`Unknown TeaQL entity: ${e}`);return t}toRuntimeMutationRecord(e,t){const i={};for(const[r,o]of Object.entries(t)){const s=e.columns[r]?r:Object.keys(e.columns).find(a=>e.columns[a].modelName===r||e.columns[a].columnName===r);s&&(i[s]=o)}return i}encode(e,t){const i=e?.id??e;if(i!==void 0){if(this.requireFiniteFloatingPoint(i,t),t?.logicalType==="decimal"&&i!==null){if(t.decode!=="decimal"){if(typeof i=="number"&&(!Number.isFinite(i)||Number.isInteger(i)&&!Number.isSafeInteger(i)))throw new TypeError("Legacy Decimal requires a finite JSON-safe number");return this.driver.encode(i,t)}return this.driver.encode(ue(i),t)}return t?.logicalType==="long"&&i!==null?this.driver.encode(be(i),t):t?.logicalType==="time"&&i!==null?this.driver.encode(Ce(i),t):this.driver.encode(i,t)}}requireFiniteFloatingPoint(e,t){if(!(t?.logicalType!=="double"||e===null||e===void 0)&&(typeof e!="number"||!Number.isFinite(e)))throw new TypeError(`Invalid numeric field ${t.modelName??t.columnName}: expected a finite Float/Double number`)}validateFloatingMutation(e){const t=this.schemas[e.entity];if(!t)return;const i=this.toRuntimeMutationRecord(t,e.payload||{});for(const[r,o]of Object.entries(i))this.requireFiniteFloatingPoint(o,t.columns[r])}decodeRow(e,t,i=[],r){const o=this.schema(e),s={...t},a=new Ge(e,o);for(const[c,u]of Object.entries(o.columns)){if(r&&!Object.prototype.hasOwnProperty.call(r,c))continue;const l=r?.[c]??c;if(i.some(h=>h.name===l))continue;const d=s[l];if(d!=null){if(c==="version"){s[l]=M(d);continue}if(u.decode==="number"&&(s[l]=Number(a.read(c,d))),this.requireFiniteFloatingPoint(s[l],u),u.decode==="string"&&(s[l]=String(d)),u.decode==="decimal"){if(typeof d!="string")throw new TypeError(`Inexact Decimal readback for ${c}`);s[l]=ue(d)}if(u.decode==="long"){if(typeof d!="string"&&typeof d!="bigint")throw new TypeError(`Inexact Long readback for ${c}`);s[l]=be(d)}u.decode==="time"&&(s[l]=Ce(d)),u.decode==="date"&&(d instanceof Date?s[l]=u.logicalType==="date"?d.toISOString().slice(0,10):d.toISOString():u.logicalType==="datetime"&&typeof d=="number"&&(s[l]=new Date(d).toISOString())),u.logicalType==="boolean"&&(s[l]=!!d)}}for(const c of i){const u=s[c.name];if(u!=null)if(c.exactDecimal){if(typeof u!="string")throw new TypeError(`Inexact Decimal aggregate ${c.name}`);s[c.name]=ue(u)}else s[c.name]=Number(u)}return s}get auditTrace(){return[...this.auditEvents]}setAuditSink(e){return this.auditSink=e,this}setRuntimeTelemetrySink(e){return this.telemetrySink=e,this}setDiagnosticSQLLogSink(e){return this.diagnosticSQLLogSink=e,this}setQueryLoggingEnabled(e){return this.queryLoggingEnabled=e,this}setMutationLoggingEnabled(e){return this.mutationLoggingEnabled=e,this}setRuntimeTelemetry(e){return this.customTelemetry=!0,this.runtimeTelemetry=e,this}operationTelemetry(){return tr(this.runtimeTelemetry,this.userContext.runtimeLogger)}attachStandardTelemetryStartup(e){this.telemetryStartup=e.then(async t=>{if(t){if(this.customTelemetry){await t.release();return}this.standardTelemetryHandle=t,this.runtimeTelemetry=t.telemetry}}).catch(()=>{pt("TeaQL telemetry: initialization failed; business continues without export.",!0)})}async flushTelemetry(){await this.telemetryStartup;try{await this.standardTelemetryHandle?.flush()}catch{pt("TeaQL telemetry: export flush failed; business outcome unchanged.",!0)}}async withQueryRequest(e,t){try{new L(e)}catch(i){throw this.userContext.runtimeLogger.write("WARN","query.rejected","TeaQL query rejected",{category:"SQL",outcome:"rejected",error_code:"request_intent"}),i}return await this.telemetryStartup,me(this.operationTelemetry(),{family:"query",name:`${String(e.entity)}.request`,attributes:{"teaql.entity.type":String(e.entity)}},t,i=>Array.isArray(i)?{attributes:{"teaql.result.cardinality":i.length}}:{})}recordSQL(e,t,i,r,o,s,a={},c="success",u,l){const h=e==="select"?this.queryLoggingEnabled:this.mutationLoggingEnabled,{targetID:f,inheritedBindings:p,...m}=a,b=Object.freeze({operation:e,...m,executionOutcome:c,telemetryCorrelation:l?Object.freeze({traceId:l.traceId,spanId:l.spanId}):void 0,traceChain:B(a.traceChain??[]),tracePath:We(a.tracePath??[]),...a.traceChain?{traceChain:B(a.traceChain)}:{},...a.mutationLineage?{mutationLineage:B(a.mutationLineage)}:{},parameterizedSQL:t,parameters:Object.freeze([...i]),debugSQL:"",databaseKind:this.driver.databaseKind,sqlOrigin:"generated",parameterLogPolicies:Object.freeze([...this.bindLogPolicies.get(i)??i.map(()=>"unknown")]),elapsedMicros:Math.max(0,(Date.now()-r)*1e3),resultCount:o,affectedRows:s,resultSummary:o!==void 0?`${o} rows returned`:s!==void 0?`${s} rows affected`:`statement ${c}; row count unknown`}),g=p&&u?q(u,p):p??u,y=this.bindOperandSources.get(i),O=y?q(y,g):g;if(ei(b,O,f===void 0?[]:[f]),this.runtimeTelemetry?.recordDiagnostic)try{this.runtimeTelemetry.recordsSQLDiagnostics?.()!==!1&&this.runtimeTelemetry.recordDiagnostic(kr(lr(b),l))}catch{pt("TeaQL telemetry: SQL diagnostic rejected; business outcome unchanged.",!0)}if(!this.telemetrySink&&!(h&&this.diagnosticSQLLogSink))return b;try{const w=Vi(b);try{this.telemetrySink?.record(w)}catch{}if(h)try{this.diagnosticSQLLogSink?.write(w)}catch{}}catch{}return b}queryLogIntent(e){const t=new L(e),i=gt(t.traceSource,this.driver.databaseKind,"select");return{comment:t.intent.comment,purpose:t.purpose,traceChain:t.traceChain,tracePath:We(i.tracePath)}}async executeLoggedSQL(e,t,i,r,o,s,a){await this.telemetryStartup;const c=H(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.${e}`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.execution":"statement","teaql.provider.operation":e==="select"?"query":e}}),u=c.correlation?.(),l=Date.now();let d;try{d=await(c.run?c.run(o):o())}catch(f){try{const p=this.recordSQL(e,t,i,l,void 0,void 0,r,"failure",s,u);a?.push(p)}finally{throw c.failure(f),f}}const h=this.recordSQL(e,t,i,l,e==="select"?d.rowCount:void 0,e==="select"?void 0:d.rowCount,r,"success",s,u);return a?.push(h),c.success({attributes:{"teaql.result.cardinality":d.rowCount}}),d}async[Di](e){await this.telemetryStartup,this.schemaReady||(this.schemaReady=this.driver.ensureSchema(this.schemas)),await this.schemaReady;const t=this.bootstrapTail;let i;this.bootstrapTail=new Promise(s=>{i=s}),await t,this.userContext=e;const r=e.getResource("bootstrapActor"),o=e.getResource("bootstrapCategory");e.insertResource("bootstrapActor","teaql-generated-bootstrap"),e.insertResource("bootstrapCategory","runtime-bootstrap");try{if(this.bootstrap.ensure){const{runGeneratedBootstrap:s}=await cn(async()=>{const{runGeneratedBootstrap:a}=await import("./entity-creation-Bqaw1C4U.js");return{runGeneratedBootstrap:a}},[]);await s(e,this.bootstrap,()=>this.bootstrap.ensure(e))}else await this.ensureBootstrapData()}finally{r===void 0?e.removeResource("bootstrapActor"):e.insertResource("bootstrapActor",r),o===void 0?e.removeResource("bootstrapCategory"):e.insertResource("bootstrapCategory",o),i()}}invalidateSchemaState(){this.schemaReady=void 0}async ensureBootstrapData(){const e=[...this.bootstrap.defaultDomainRoot?[this.bootstrap.defaultDomainRoot]:[],...this.bootstrap.constants??[]];e.length&&await this.executeGraphSave(new Ie("reconcile model bootstrap data"),async t=>{const i=this.graphMutationSession,r=[];for(const o of e){const s=await this.planBootstrapMutation(i,o);s&&r.push({record:o,request:t.request(s)})}for(const{request:o}of r)this.preflightMutation(o);for(const{request:o}of r)await this.executeMutation(o);for(const o of e)await this.driver.ensureIdFloor(i,o.entity,o.id)})}async planBootstrapMutation(e,t){const i=this.schema(t.entity),r=Object.entries(t.values??{}).map(([p,m])=>{const b=i.columns[p];if(!b)throw new Error(`Unknown bootstrap field ${t.entity}.${p}`);return{column:b.columnName,model:b.modelName??p,original:m,value:this.driver.encode(m,b)}}),o=Object.fromEntries(r.map(p=>[p.model,p.original])),s=new jr(t.entity).filter({id:{$eq:t.id}}).limit(1).comment("inspect model bootstrap record").purpose("ensure model-defined root and constants");s.prepareForList();const a=new L(s),u=`SELECT ${Object.entries(i.columns).map(([p,m])=>this.fieldProjection(p,m,m.columnName)).join(", ")} FROM ${this.driver.identifier(i.table)} WHERE ${this.driver.identifier(i.columns.id?.columnName??"id")} = ${this.driver.placeholder(1)}`,l=[t.id];this.bindLogPolicies.set(l,[this.fieldLogPolicy(i,"id")]);const d=await this.executeLoggedSQL("select",u,l,this.queryLogIntent(a.query),()=>e.query(u,l));if(!d.rowCount)return{entity:t.entity,action:"Create",id:t.id,version:0,payload:o};const h=d.rows[0];if(r.filter(p=>!Cr(h[p.column],p.value)).length)return{entity:t.entity,action:"Update",id:t.id,version:M(h[i.columns.version?.columnName??"version"]),payload:{...Object.fromEntries(Object.entries(this.decodeRowForSchema(i,h)).map(([p,m])=>[i.columns[p]?.modelName??p,m])),...o}}}async executeGraphSave(e,t,i,r){const o=new fr(e),s=this.userContext;o.bindExecutionReference(()=>this.userContext),o.bindExecutionReference(()=>this.checkerPresentationModel),o.bindExecutionMetadata(()=>({schemas:this.schemas,checkerNames:Object.keys(this.checkers).sort()}));for(const c of Object.keys(this.checkers))o.bindExecutionReference(()=>this.checkers[c]),o.bindExecutionReference(()=>this.checkers[c]?.checkAndFix);await this.telemetryStartup;const a=async()=>{const c=this.graphSaveTail;let u;this.graphSaveTail=new Promise(m=>{u=m}),await c;let l=!1,d=!1,h=!1,f,p;try{o.validatePreparedSources(),this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[];const m=r?.(o);if(r&&typeof m!="boolean")throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED");if(p=s.captureCheckerMessages(this.checkerPresentationModel),o.preparedRootEntity&&(f=Object.freeze({model:p.model,entity:o.preparedRootEntity})),o.captureInputSources(),m===!1){o.sealPreparedGraph(),this.activeGraph=o;try{return await t(o)}finally{this.activeGraph=void 0}}s.beginMutationPolicyGraph(),d=!0,s.insertResource("fixTime",s.businessTime()),s.beginFixEvidence(),l=!0,this.activeGraph=o;try{await i?.(o)}finally{this.activeGraph=void 0}if(i&&!o.isPreparedSealed&&o.sealPreparedGraph(),s.prepareMutationPolicyGraph(o.preparedRootEntity),o.validatePreparedSources(),o.isPreparedEmpty){this.activeGraph=o;try{const O=await t(o);o.requirePreparedComplete(),s.ensureMutationPolicyGraphComplete();for(const w of this.graphCommitActions)await w();return h=!0,O}finally{this.activeGraph=void 0}}const b=await this.driver.transaction(async O=>{this.graphMutationSession=O,this.activeGraph=o;try{const w=await t(o);return o.requirePreparedComplete(),s.ensureMutationPolicyGraphComplete(),w}finally{this.graphMutationSession=void 0,this.activeGraph=void 0}});h=!0;let g,y=!1;for(const O of[...this.graphCommitActions,...this.graphAuditActions])try{await O()}catch(w){y||(g=w),y=!0}if(y)throw new ri(g);return b}catch(m){if(!h)for(const b of[...this.graphRollbackActions].reverse())try{b()}catch{}throw m instanceof G&&f&&p&&m.refreshPresentation(s.renderCheckerGraphResults(m.violations,p,f)),m}finally{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],d&&s.endMutationPolicyGraph(),l&&s.removeResource("fixTime").finishFixEvidence(),u()}};return me(this.operationTelemetry(),{family:"mutation",name:"graph.save",attributes:{"teaql.entity.type":"graph","teaql.mutation.kind":"graph"}},a)}afterGraphCommit(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphCommitActions.push(e)}afterGraphRollback(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphRollbackActions.push(e)}requireGraphOwnership(e){if(e.graphSession!==this.activeGraph||this.graphMutationSession!==void 0&&e.graphSession===void 0)throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability")}async withMutationSession(e,t){return this.requireGraphOwnership(e),e.graphSession?t(this.graphMutationSession):this.driver.transaction(t)}preflightMutation(e){const t=e instanceof ce?e:new ce(e);this.requireGraphOwnership(t),e=this.checkAndFixMutation(t);const i=t.graphSession?.normalizePreparedMutation(e);if(i?.restore&&(this.graphCommitActions.push(i.restore),this.graphRollbackActions.push(i.restore)),i?.empty)return e;if(t.graphSession?.recordPreparedMutation(),t.graphSession){const o=this.schema(e.entity);t.graphSession.captureLogBindings(this.mutationLogBindings(t,e,o))}const r=t.graphSession?t.graphSession.capturePreparedMutation(t,e,this.preparedReferences(e.entity)):e;return this.userContext.recordMutationPolicyPreflight(r),e}mutationLogBindings(e,t,i){const r=o=>{const s=this.toRuntimeMutationRecord(i,o),a=Object.keys(s);return{parameterizedSQL:"",sqlOrigin:"generated",parameters:a.map(c=>s[c]),parameterLogPolicies:a.map(c=>this.fieldLogPolicy(i,c))}};return q(r(t.payload||{}),r(e.loadedValues()))}checkAndFixMutation(e){const t=e instanceof ce?e:new ce(e);this.requireGraphOwnership(t);const i=t.graphSession?.replayPreparedMutation(t);if(i)return i;e=t.mutation;const r=this.schemas[String(e.entity)];if(r){const d=new Gn(String(e.entity),Object.entries(r.columns).map(([h,f])=>f.modelName??h));if(d.validate(e.payload??{},e.action==="Update"),e.ledgerKey&&e.ledgerRoot){if(e.ledgerKey.entity!==e.entity)throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");d.validate(e.ledgerRoot.change(e.ledgerKey),e.action==="Update")}}const o=r?this.checkedMutationVersion(e):void 0;e={...e,payload:{...e?.payload??{}}},t.bindCheckerLoadedValues(e),Object.defineProperty(e,"comment",{value:t.comment,enumerable:!0});const s=String(e.entity),a=new Ge(s,r),c=this.checkers[s];if(!c){const d=a.checkMutation(e.payload||{});if(d.length)throw new G(d);return this.validateFloatingMutation(e),this.sealMutationVersion(e,r?o:void 0,!!r)}const u=[],l=this.userContext.getResource("fixTime")===void 0;l&&this.userContext.insertResource("fixTime",this.userContext.businessTime()).beginFixEvidence();try{if(Dt.run(this.userContext,e,r,()=>c.checkAndFix(this.userContext,e,u)),r&&(e.action!==t.mutation.action||this.checkedMutationVersion(e)!==o))throw new X("invalid_type");a.checkMutation(e.payload||{},u);const d=Object.freeze({model:this.userContext.captureCheckerMessages(this.checkerPresentationModel).model,entity:s});if(u.splice(0,u.length,..._i(u,d)),Si(this.userContext,u,s,this.checkerPrivacyPolicy,[t.loadedValues(),t.mutation.payload??{},e.payload??{}]),u.length)throw new G(u);if(this.validateFloatingMutation(e),e.action!=="Delete"&&e.ledgerKey&&e.ledgerRoot){const h=Dt.captureUndo(e,r);t.graphSession&&h&&this.graphRollbackActions.push(h);for(const[f,p]of Object.entries(e.payload||{}))e.ledgerRoot.set(e.ledgerKey,f,p)}return this.sealMutationVersion(e,o,!!r)}finally{l&&this.userContext.removeResource("fixTime").finishFixEvidence()}}preparedReferences(e){const t=this.schemas[e];return Object.fromEntries(Object.values(t?.relations??{}).filter(i=>!i.many).map(i=>[t.columns[i.localKey]?.modelName??i.localKey,i.targetEntity]))}sealMutationVersion(e,t,i){return i&&["Create","Update","Delete","Recover"].includes(e.action)&&Object.defineProperties(e,{version:{value:t,enumerable:!0,writable:!1,configurable:!1},expectedVersion:{value:t,enumerable:e.expectedVersion!==void 0,writable:!1,configurable:!1},action:{value:e.action,enumerable:!0,writable:!1,configurable:!1}}),e}checkedMutationVersion(e){if(e.action==="Create"){ct("Create");return}if(!["Update","Delete","Recover"].includes(e.action))return;const t=e.version!==void 0,i=e.expectedVersion!==void 0;if(!t&&!i){if(e.action==="Recover")throw new X("invalid_type","Recover");return}const r=M(t?e.version:e.expectedVersion);if(t&&i&&r!==M(e.expectedVersion))throw new X("invalid_type");return ct(e.action,r),r}fieldProjection(e,t,i=e){const r=this.driver.identifier(t.columnName);return`${e==="version"?`CAST(${r} AS ${this.driver.databaseKind==="mysql"?"CHAR":"TEXT"})`:r} AS ${this.driver.identifier(i)}`}async executeMutation(e){await this.telemetryStartup;const t=e instanceof ce?e:new ce(e);if(this.requireGraphOwnership(t),t.graphSession?.requireMutationAllowed(),this.activeGraph&&!this.graphMutationSession)throw new Error("Graph preparation cannot execute mutations before its transaction");e=t.mutation;const i=H(this.operationTelemetry(),{family:"mutation",name:`${String(e?.entity||"unknown")}.${String(e?.action||"unknown").toLowerCase()}`,attributes:{"teaql.entity.type":String(e?.entity||"unknown"),"teaql.mutation.kind":String(e?.action||"unknown").toLowerCase()}}),r=async()=>{try{e=this.checkAndFixMutation(t);const o=this.userContext.enterMutationPolicy(e),s=this.schema(e.entity),a=this.toRuntimeMutationRecord(s,e.payload||{}),c=this.mutationLogBindings(t,e,s),u=this.driver.identifier(s.table),l=[],d=await me(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.mutation`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":String(e.action).toLowerCase()}},()=>this.withMutationSession(t,async b=>{if(e.action==="Create"){const g=e.id?String(e.id):await this.driver.nextId(b,e.entity);e.id&&await this.driver.ensureIdFloor(b,e.entity,g);const y=ct("Create"),O={...a,id:g,version:y},w=Object.keys(s.columns).filter(v=>O[v]!==void 0),E=w.map(v=>this.driver.identifier(s.columns[v].columnName)).join(", "),k=w.map((v,S)=>this.driver.placeholder(S+1)).join(", "),j=w.map(v=>this.encode(O[v],s.columns[v]));this.bindLogPolicies.set(j,w.map(v=>this.fieldLogPolicy(s,v)));const T=`INSERT INTO ${u} (${E}) VALUES (${k})`,R=mt(t,e,this.driver.databaseKind,"insert",g,c);return await this.executeLoggedSQL("insert",T,j,R,()=>b.query(T,j),void 0,l),{success:!0,id:g,version:y,persistedRecord:await this.readPersistedRecord(b,s,g,R,T,j,l)}}if(e.action==="Update"){const g=Object.keys(s.columns).filter(S=>S!=="id"&&S!=="version"&&a[S]!==void 0),y=g.map(S=>this.encode(a[S],s.columns[S]));this.bindLogPolicies.set(y,g.map(S=>this.fieldLogPolicy(s,S)));const O=g.map((S,_)=>`${this.driver.identifier(s.columns[S].columnName)} = `+this.driver.placeholder(_+1)),w=this.driver.identifier("version");O.push(`${w} = ${w} + 1`),this.bindValue(y,String(e.id),this.fieldLogPolicy(s,"id"));const E=[`${this.driver.identifier("id")} = ${this.driver.placeholder(y.length)}`],k=this.checkedMutationVersion(e);E.push(`${w} > 0`,`${w} < 9223372036854775807`),k!==void 0&&(this.bindValue(y,k,this.fieldLogPolicy(s,"version")),E.push(`${w} = ${this.driver.placeholder(y.length)}`));const j=`UPDATE ${u} SET ${O.join(", ")} WHERE ${E.join(" AND ")}`,T=mt(t,e,this.driver.databaseKind,"update",String(e.id),c);if((await this.executeLoggedSQL("update",j,y,T,()=>b.query(j,y),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const v=await this.readPersistedRecord(b,s,String(e.id),T,j,y,l);return{success:!0,id:String(e.id),version:M(v.version),persistedRecord:v}}if(e.action==="Delete"||e.action==="Recover"){const g=this.driver.identifier("version"),y=[String(e.id)];this.bindLogPolicies.set(y,[this.fieldLogPolicy(s,"id")]);const O=[`${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`],w=this.checkedMutationVersion(e),E=e.action==="Recover";O.push(`${g} ${E?"<":">"} 0`),w!==void 0&&(this.bindValue(y,w,this.fieldLogPolicy(s,"version")),O.push(`${this.driver.identifier("version")} = `+this.driver.placeholder(y.length)));const k=`UPDATE ${u} SET ${g} = -${g} ${E?"+":"-"} 1 WHERE ${O.join(" AND ")}`,j=E?"update":"delete",T=mt(t,e,this.driver.databaseKind,j,String(e.id),c);if((await this.executeLoggedSQL(j,k,y,T,()=>b.query(k,y),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const v=await this.readPersistedRecord(b,s,String(e.id),T,k,y,l);return{success:!0,id:String(e.id),version:M(v.version),deleted:!E,persistedRecord:v}}throw new Error(`Unsupported mutation action: ${e.action}`)}));t.graphSession?.recordPreparedResult(t,d);const h=t.auditProjection({entity:String(e.entity),id:d.id},e.payload,c),f=Object.freeze({entity:e.entity,action:e.action,id:String(d.id),...h,recordedAt:new Date().toISOString(),actor:this.userContext.getResource("bootstrapActor"),category:this.userContext.getResource("bootstrapCategory"),changedFields:Object.freeze(Object.keys(e.payload||{}).sort()),version:d.version,mutationGovernance:o}),p=async()=>{this.auditEvents.push(f),this.userContext.runtimeLogger.write("INFO","audit.event","TeaQL audit event",{category:"AUDIT",outcome:"success",audit:f}),this.auditSink&&await me(this.operationTelemetry(),{family:"audit",name:`${e.entity}.audit`,attributes:{"teaql.entity.type":String(e.entity),"teaql.mutation.kind":String(e.action).toLowerCase(),"teaql.audit.changed_field_count":Object.keys(e.payload||{}).length}},async()=>this.auditSink(f))};if(t.graphSession)this.graphAuditActions.push(p);else try{await p()}catch(b){throw new ri(b)}i.success();const m=Object.freeze({...l[0],statements:Object.freeze([...l])});return ei(m,q(c,t.graphSession?.logBindings),[d.id]),{...d,metadata:m}}catch(o){throw i.failure(o),o}};return i.run?i.run(r):r()}async readPersistedRecord(e,t,i,r,o,s,a){const u=`SELECT ${Object.entries(t.columns).map(([w,E])=>this.fieldProjection(w,E)).join(", ")} FROM ${this.driver.identifier(t.table)} WHERE ${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`,l=[i];this.bindLogPolicies.set(l,[this.fieldLogPolicy(t,"id")]);const d=H(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.readback`,attributes:{"teaql.provider.execution":"statement","teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}}),h=Date.now();let f;const p={parameterizedSQL:o,parameters:s,parameterLogPolicies:this.bindLogPolicies.get(s),sqlOrigin:"generated"},m=r.tracePath?.find(w=>w.kind==="operation")?.name??"unknown",b=gt([...mi(m,r.auditReason,"verify persisted mutation result"),...(r.tracePath??[]).filter(w=>w.kind==="relation")],this.driver.databaseKind,"select"),g={...r,tracePath:We(b.tracePath),comment:r.auditReason,purpose:"verify persisted mutation result"},y=w=>a.push(this.recordSQL("select",u,l,h,f?.rowCount,void 0,g,w,p,d.correlation?.()));let O;try{if(f=await(d.run?d.run(()=>e.query(u,l)):e.query(u,l)),d.success({attributes:{"teaql.result.cardinality":f.rowCount}}),f.rowCount!==1)throw new Error(`Persisted ${t.table}(${i}) could not be read back`);O=this.decodeRowForSchema(t,f.rows[0])}catch(w){f||d.failure(w);const E=f?"success":w instanceof Error&&(w.name==="AbortError"||w.name==="TimeoutError")?"cancelled":"failure";try{y(E)}finally{throw w}}return y("success"),O}decodeRowForSchema(e,t){const i={...t},r=Object.keys(this.schemas).find(s=>this.schemas[s]===e)??"Unknown",o=new Ge(r,e);for(const[s,a]of Object.entries(e.columns)){const c=i[s];if(c!=null){if(s==="version"){i[s]=M(c);continue}if(a.decode==="number"&&(i[s]=Number(o.read(s,c))),this.requireFiniteFloatingPoint(i[s],a),a.decode==="string"&&(i[s]=String(c)),a.decode==="decimal"){if(typeof c!="string")throw new TypeError(`Inexact Decimal readback for ${s}`);i[s]=ue(c)}if(a.decode==="long"){if(typeof c!="string"&&typeof c!="bigint")throw new TypeError(`Inexact Long readback for ${s}`);i[s]=be(c)}a.decode==="time"&&(i[s]=Ce(c)),a.decode==="date"&&(c instanceof Date?i[s]=a.logicalType==="date"?c.toISOString().slice(0,10):c.toISOString():a.logicalType==="datetime"&&typeof c=="number"&&(i[s]=new Date(c).toISOString())),a.logicalType==="boolean"&&(i[s]=!!c)}}return i}comparisonSql(e,t,i,r){if(e.logicalType!=="decimal"&&e.logicalType!=="long")return`${t} ${i} ${r}`;if(e.logicalType==="decimal"&&e.decode!=="decimal")return`${t} ${i} ${r}`;const o=e.logicalType==="long"?this.driver.longComparison:this.driver.decimalComparison;if(o)return o.call(this.driver,t,i,r);if(this.driver.databaseKind==="sqlite")throw new Error(`EXACT_${e.logicalType.toUpperCase()}_UNSUPPORTED: this SQLite provider has no exact comparison`);return`${t} ${i} ${r}`}compileExpression(e,t,i){if(Array.isArray(e?.$and))return`(${e.$and.map(s=>this.compileExpression(s,t,i)).join(" AND ")})`;const r=Object.entries(e||{}).map(([o,s])=>{const a=t.columns[o];if(!a)throw new Error(`Unknown field ${o} for SQL query`);const c=this.driver.identifier(a.columnName),u=this.fieldLogPolicy(t,o);if(s?.$eq!==void 0){const l=s.$eq?.id??s.$eq;return l===null?`${c} IS NULL`:(this.bindValue(i,this.encode(l,a),u),this.comparisonSql(a,c,"=",this.driver.placeholder(i.length)))}if(s?.$ne!==void 0){const l=s.$ne?.id??s.$ne;return l===null?`${c} IS NOT NULL`:(this.bindValue(i,this.encode(l,a),u),this.comparisonSql(a,c,"<>",this.driver.placeholder(i.length)))}if(s?.$soundLike!==void 0)return this.bindValue(i,String(s.$soundLike),u),`SOUNDEX(${c}) = SOUNDEX(${this.driver.placeholder(i.length)})`;if(s?.$contains!==void 0)return this.bindValue(i,String(s.$contains),u),this.driver.contains(c,this.driver.placeholder(i.length));if(s?.$notContains!==void 0)return this.bindValue(i,String(s.$notContains),u),`NOT (${this.driver.contains(c,this.driver.placeholder(i.length))})`;for(const[l,d,h,f]of[["$startsWith","","%",!1],["$notStartsWith","","%",!0],["$endsWith","%","",!1],["$notEndsWith","%","",!0]])if(s?.[l]!==void 0){const p=String(s[l]);this.bindValue(i,`${d}${p}${h}`,u,p);const m=`${c} LIKE ${this.driver.placeholder(i.length)}`;return f?`NOT (${m})`:m}if(Array.isArray(s?.$in)){if(!s.$in.length)return"FALSE";const l=s.$in.map(d=>(this.bindValue(i,this.encode(d?.id??d,a),u),this.driver.placeholder(i.length)));return a.logicalType==="decimal"||a.logicalType==="long"?`(${l.map(d=>this.comparisonSql(a,c,"=",d)).join(" OR ")})`:`${c} IN (${l.join(", ")})`}if(Array.isArray(s?.$notIn)){if(!s.$notIn.length)return"TRUE";const l=s.$notIn.map(d=>(this.bindValue(i,this.encode(d?.id??d,a),u),this.driver.placeholder(i.length)));return a.logicalType==="decimal"||a.logicalType==="long"?`(${l.map(d=>this.comparisonSql(a,c,"<>",d)).join(" AND ")})`:`${c} NOT IN (${l.join(", ")})`}for(const[l,d]of[["$inSubquery",!1],["$notInSubquery",!0]]){const h=s?.[l];if(h!==void 0){if((a.logicalType==="decimal"&&a.decode==="decimal"||a.logicalType==="long")&&this.driver.databaseKind==="sqlite")throw new Error(`EXACT_${a.logicalType.toUpperCase()}_UNSUPPORTED: subquery membership needs an exact join`);const f=h.query,p=this.schema(f?.entity),m=String(h.field),b=p.columns[m];if(!b)throw new Error(`Unknown subquery projection ${m} for ${f?.entity}`);const g=this.filters(f).map(w=>this.compileExpression(w,p,i));p.columns.version&&g.push(`${this.driver.identifier(p.columns.version.columnName)} > 0`),d&&g.push(`${this.driver.identifier(b.columnName)} IS NOT NULL`);const y=g.length?` WHERE ${g.join(" AND ")}`:"",O=`SELECT ${this.driver.identifier(b.columnName)} FROM ${this.driver.identifier(p.table)}${y}`;return`${c} ${d?"NOT IN":"IN"} (${O})`}}if(Array.isArray(s?.$between)&&s.$between.length===2){this.bindValue(i,this.encode(s.$between[0],a),u);const l=this.driver.placeholder(i.length);this.bindValue(i,this.encode(s.$between[1],a),u);const d=this.driver.placeholder(i.length);return a.logicalType==="decimal"||a.logicalType==="long"?`(${this.comparisonSql(a,c,">=",l)} AND ${this.comparisonSql(a,c,"<=",d)})`:`${c} BETWEEN ${l} AND ${d}`}if(s?.$isNull===!0)return`${c} IS NULL`;if(s?.$isNull===!1)return`${c} IS NOT NULL`;if(s?.$gte!==void 0)return this.bindValue(i,this.encode(s.$gte,a),u),this.comparisonSql(a,c,">=",this.driver.placeholder(i.length));if(s?.$lte!==void 0)return this.bindValue(i,this.encode(s.$lte,a),u),this.comparisonSql(a,c,"<=",this.driver.placeholder(i.length));if(s?.$gt!==void 0)return this.bindValue(i,this.encode(s.$gt,a),u),this.comparisonSql(a,c,">",this.driver.placeholder(i.length));if(s?.$lt!==void 0)return this.bindValue(i,this.encode(s.$lt,a),u),this.comparisonSql(a,c,"<",this.driver.placeholder(i.length));throw new Error(`Unsupported query predicate for ${o}: ${JSON.stringify(s)}`)});return r.length?`(${r.join(" AND ")})`:"TRUE"}filters(e){return Array.isArray(e._filters)&&e._filters.length?e._filters:e.filterCondition?[e.filterCondition]:[]}groupBy(e){return e._groupBy||e.groupByItems||[]}aggregates(e){return Array.isArray(e._aggregates)?e._aggregates:(e.aggregateItems||[]).map(t=>({func:t.function,field:t.field,retName:t.alias}))}orders(e){return Array.isArray(e._orderBy)?e._orderBy.map(t=>({field:t.f,direction:t.d})):(e.orderItems||[]).map(t=>({field:t.field,direction:t.direction}))}async compileQuery(e,t=!0,i=[]){new it(e?.commentText??e?._comment,e?.purposeText??e?._purpose);const r=this.schema(e.entity),o=[],s=[...new Set(this.groupBy(e))],a=this.aggregates(e),c=e.groupByAliases;if(c!==void 0){if(c===null||typeof c!="object"||Array.isArray(c))throw new Error("Invalid group aliases");for(const[v,S]of Object.entries(c)){if(!s.includes(v))throw new Error("Group alias refers to an ungrouped field");if(typeof S!="string"||!S.trim())throw new Error("Group alias must be a non-empty string")}}const u=a.length||s.length?Object.fromEntries(s.map(v=>[v,c&&Object.prototype.hasOwnProperty.call(c,v)?c[v]:v])):void 0,l=[...Object.values(u??{}),...a.map(v=>v.retName)],d=new Set;for(const v of l){if(this.driver.identifier(v),d.has(v))throw new Error("Duplicate grouped or aggregate output alias");d.add(v)}const h=s.map(v=>{if(!r.columns[v])throw new Error(`Unknown group field: ${v}`);const S=r.columns[v],_=this.driver.identifier(S.columnName);if(S.logicalType==="decimal"&&S.decode!=="decimal")return _;if((S.logicalType==="decimal"||S.logicalType==="long")&&this.driver.databaseKind==="sqlite"){const z=S.logicalType==="long"?this.driver.longOrderExpression:this.driver.decimalOrderExpression;if(z)return z.call(this.driver,_);throw new Error(`EXACT_${S.logicalType.toUpperCase()}_UNSUPPORTED: grouping`)}return _}),f=s.map(v=>`${this.driver.identifier(r.columns[v].columnName)} AS `+this.driver.identifier(u[v])),p=[],m=Array.isArray(e.selectItems)&&e.selectItems.length?[...new Set(["id","version",...e.selectItems])]:Object.keys(r.columns);if(!s.length&&!this.aggregates(e).length){for(const S of i)m.includes(S)||m.push(S);const v=[...(e.relations??[]).map(S=>S.name),...(e.relationAggregates??[]).map(S=>S.relationName)];for(const S of v){const _=r.relations?.[S];if(!_)throw new Error(`Missing relation ${e.entity}.${S}`);m.includes(_.localKey)||m.push(_.localKey)}}for(const v of m)if(!r.columns[v])throw new Error(`Unknown selected field: ${v}`);let b=m.map(v=>{const S=r.columns[v];return this.fieldProjection(v,S)}).join(", ");if(a.length||s.length){const v=a.map(S=>{if(!r.columns[S.field])throw new Error(`Unknown aggregate field: ${S.field}`);const _=r.columns[S.field];if(_.logicalType==="long"&&String(S.func).toLowerCase()!=="count")throw new Error("EXACT_LONG_AGGREGATION_UNSUPPORTED: define overflow and result type first");const z=_.logicalType==="decimal"&&_.decode==="decimal"&&String(S.func).toLowerCase()!=="count";p.push({name:S.retName,exactDecimal:z});const ae=z&&this.driver.databaseKind==="sqlite"?this.driver.decimalAggregateFunction?.(S.func):this.driver.aggregateFunction(S.func);if(!ae)throw new Error("EXACT_DECIMAL_UNSUPPORTED: decimal aggregation");return`${ae}(${this.driver.identifier(r.columns[S.field].columnName)}) AS `+this.driver.identifier(S.retName)});b=[...f,...v].join(", ")}const g=e.__teaqlPartitionBy,y=this.orders(e),O=y.map(v=>{if(!r.columns[v.field])throw new Error(`Unknown order field: ${v.field}`);const S=String(v.direction).toLowerCase()==="desc"?"DESC":"ASC",_=r.columns[v.field];let z=this.driver.identifier(_.columnName);if(_.logicalType==="decimal"&&_.decode!=="decimal")return`${z} ${S}`;if((_.logicalType==="decimal"||_.logicalType==="long")&&this.driver.databaseKind==="sqlite"){const ae=_.logicalType==="long"?this.driver.longOrderExpression:this.driver.decimalOrderExpression;if(ae)z=ae.call(this.driver,z);else throw new Error(`EXACT_${_.logicalType.toUpperCase()}_UNSUPPORTED: ordering`)}return`${z} ${S}`});if(g){const v=r.columns[g];if(!v)throw new Error(`Unknown partition field: ${g}`);const S=O.length?` ORDER BY ${O.join(", ")}`:"";b+=`, ROW_NUMBER() OVER (PARTITION BY ${this.driver.identifier(v.columnName)}${S}) AS `+this.driver.identifier("__teaql_partition_rank")}let w=`SELECT ${b} FROM ${this.driver.identifier(r.table)}`;const k=this.filters(e).map(v=>this.compileExpression(v,r,o)),j=e.deletionVisibility??"live";if(!["live","all","deleted"].includes(j))throw new Error("QUERY_INVALID_DELETION_VISIBILITY");r.columns.version&&j!=="all"&&k.push(`${this.driver.identifier(r.columns.version.columnName)} ${j==="deleted"?"<":">"} 0`),k.length&&(w+=` WHERE ${k.join(" AND ")}`),h.length&&(w+=` GROUP BY ${h.join(", ")}`);const T=e._limit!==void 0?Number(e._limit):Number(e.limitValue||0),R=e._offset!==void 0?Number(e._offset):Number(e.offsetValue||0);if(g){const v=this.driver.identifier("__teaql_partition_rank"),S=[];this.bindValue(o,R,"plain"),S.push(`${v} > ${this.driver.placeholder(o.length)}`),T>0&&(this.bindValue(o,R+T,"plain"),S.push(`${v} <= ${this.driver.placeholder(o.length)}`)),w=`SELECT * FROM (${w}) AS ${this.driver.identifier("__teaql_partitioned")} WHERE ${S.join(" AND ")} ORDER BY ${v}`}else y.length&&(w+=` ORDER BY ${O.join(", ")}`);return!g&&T>0&&(this.bindValue(o,T,"plain"),w+=` LIMIT ${this.driver.placeholder(o.length)}`),!g&&R>0&&(this.bindValue(o,R,"plain"),w+=` OFFSET ${this.driver.placeholder(o.length)}`),t&&this.sqlTrace.push(w),{sql:w,values:o,aggregateNames:p,groupAliases:u}}async executeQuery(e){const t=e instanceof L?e:new L(e);return!t.parentRequest&&!(e instanceof L)&&e?.[this.internalQueryToken]!==!0&&typeof e?.prepareForList=="function"&&e.prepareForList(),this.executeQueryWithIntent(t.query,this.derivedQueryBindings.get(e),this.derivedRelationAssembly.get(e))}async executeDerivedQuery(e,t,i,r){const o=new L(e,i).query;t&&this.derivedQueryBindings.set(o,t),r&&this.derivedRelationAssembly.set(o,r);try{return await this.executeQuery(o)}finally{this.derivedQueryBindings.delete(o),this.derivedRelationAssembly.delete(o)}}descendantBindings(e,t,i,r){if(!(!e.relations?.length&&!e.relationAggregates?.length))return q(this.queryLogBindings(t,i),r)}async queryTreeBindings(e,t,i,r){let o=q(this.queryLogBindings(t,i),r);const s=new L(e).intent,a=[e],c=new Set;for(;a.length;){const u=a.pop();if(!u||c.has(u))continue;if(c.add(u),u!==e){const d=await this.compileQuery(new L(u,s).query,!1);o=q(this.queryLogBindings(d.sql,d.values),o)}const l=mn(u);l&&a.push(l);for(const d of[...u.relations??[],...u.relationAggregates??[]])d.query&&a.push(d.query);for(const d of u.facets??[]){if(!d.query)continue;const h=d.query.clone();h.aggregateItems=[],h.groupByItems=[],h.groupByAliases=void 0,a.push(h)}}return o}async executeQueryWithIntent(e,t,i){await this.telemetryStartup;const r=H(this.operationTelemetry(),{family:"query",name:`${String(e?.entity||"unknown")}.list`,attributes:{"teaql.entity.type":String(e?.entity||"unknown")}}),o=async()=>{try{const s=e?.[this.internalQueryToken]===!0||new L(e).parentRequest!==void 0;if(!s){if(typeof e?.prepareForList!="function")throw new Error("TeaQL list execution requires the formal runtime SelectQuery");e.prepareForList()}const a=s?{query:e,execution:void 0}:await this.prepareIdSetPage(e,t),c=s?a:await this.prepareContinuousPage(a.query);e=new L(e).withQuery(c.query).query;const{sql:u,values:l,aggregateNames:d,groupAliases:h}=await this.compileQuery(e,!0,i?[i.field]:[]);t=await this.queryTreeBindings(e,u,l,t);const p=(await this.executeLoggedSQL("select",u,l,this.queryLogIntent(e),()=>this.driver.query(u,l),t)).rows.map(b=>this.decodeRow(e.entity,b,d,h));if(a.execution?.pageIds){const b=new Map(a.execution.pageIds.map((g,y)=>[String(g),y]));p.sort((g,y)=>(b.get(String(g.id))??Number.MAX_SAFE_INTEGER)-(b.get(String(y.id))??Number.MAX_SAFE_INTEGER))}const m=this.descendantBindings(e,u,l,t);if(i)for(const b of p)i.keys.set(b,b[i.field]);if(await this.enhanceQueryRows(p,e,m),i&&Array.isArray(e.selectItems)&&e.selectItems.length&&!["id","version",...e.selectItems,...this.groupBy(e)].includes(i.field)){const b=this.schema(e.entity);if(![...(e.relations??[]).map(y=>y.name),...(e.relationAggregates??[]).map(y=>y.relationName)].some(y=>b.relations?.[y]?.localKey===i.field))for(const y of p)delete y[i.field]}return s||await this.registerContinuousPage(e,c.execution,p),r.success({attributes:{"teaql.result.cardinality":p.length}}),p}catch(s){throw r.failure(s),s}};return r.run?r.run(o):o()}async prepareIdSetPage(e,t){const i=e.localIdSetPaginationOptions?.(),r=e.localIdSetPaginationRuntime?.();if(!i||!r)return r?.observe("ID_SET_DISABLED"),{query:e};const o=this.queryLimit(e);if(!o||e.localContinuousPageOptions?.()||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return r.observe("ID_SET_FALLBACK_UNSUPPORTED_SHAPE"),{query:e};if((e.orderItems||[]).some(m=>m.expr!=null))return r.observe("ID_SET_FALLBACK_NON_DETERMINISTIC_ORDER"),{query:e};this.orders(e).some(m=>m.field==="id")||(e=e.clone().order(Y.asc("id")));const s=e.clone();s.offsetValue=0,s.limitValue=0,s.selectItems=[],s.relations=[],s.commentText=void 0,s.purposeText=void 0,s.clearIdSetPaginationRuntime(),s.clearContinuousPageRuntime();const a=`${i.namespace}|${r.scope}|${JSON.stringify(s)}`;let c=2166136261;for(let m=0;m>>0).toString(16)}`;let l,d=!1;try{l=r.get(u)}catch{return r.observe("ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l)d=!0,r.observe("ID_SET_HIT",l.ids.length);else{let m;try{m=await r.build(u,async()=>{const b=r.get(u);if(b)return b;const g=e.clone();g.selectItems=["id"],g.relations=[],g.relationAggregates=[],g.facets=[],g.offsetValue=0,g.limitValue=i.maxIds+1,g.clearIdSetPaginationRuntime(),g.clearContinuousPageRuntime(),g[this.internalQueryToken]=!0;const y=new L(e).deriveHelper(g,`collect ${e.entity} IDs for pagination`),O=await this.compileQuery(e,!1),w=await this.queryTreeBindings(e,O.sql,O.values,t),E=await this.executeDerivedQuery(y.query,w,y.intent);if(E.length>i.maxIds)return;let k;try{k=BigUint64Array.from(E.map(T=>BigInt(T.id)))}catch{throw new Error("ID_SET_UNSUPPORTED_ID")}const j={ids:k,expiresAt:Date.now()+i.ttlSeconds*1e3};return r.put(u,j),j})}catch(b){return r.observe(b instanceof Error&&b.message==="ID_SET_UNSUPPORTED_ID"?"ID_SET_FALLBACK_UNSUPPORTED_SHAPE":"ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l=m.value,!l)return r.observe("ID_SET_FALLBACK_LIMIT_EXCEEDED",i.maxIds+1),{query:e};d=!m.built,r.observe(d?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length)}const h=Number(e.offsetValue||e._offset||0),f=Array.from(l.ids.slice(h,h+o)),p=e.clone();return p.offsetValue=0,p.limitValue=Math.max(f.length,1),p.filterCondition=p.filterCondition?{$and:[p.filterCondition,{id:{$in:f}}]}:{id:{$in:f}},p.clearIdSetPaginationRuntime(),r.observe(d?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length),{query:p,execution:{pageIds:f,totalCount:l.ids.length}}}async executeFacetMembership(e,t,i=[]){const r=await this.executeFacetAggregates(e,t,[{function:"Count",field:"id",alias:"__teaql_facet_count"}]);return new Map([...r].map(([o,s])=>[o,Number(s.__teaql_facet_count??0)]))}async executeFacetAggregates(e,t,i){const r=new L(e);e=r.query;const o=r.withQuery(e.clone()).query;je(e,o),o.facets=[],o.relations=[],o.relationAggregates=[],o.orderItems=[],o.offsetValue=0,o.limitValue=0,o.selectItems=[],o.groupByItems=[t],o.groupByAliases=void 0,o.aggregateItems=i.map(a=>({...a})),o[this.internalQueryToken]=!0;const s=await this.executeQuery(o);return new Map(s.flatMap(a=>{const c=a[t];if(c==null)return[];const u={};for(const l of i)u[l.alias]=a[l.alias];return[[String(c),u]]}))}async executeCount(e,t,i){const r=e instanceof L?e:new L(e);if(e=r.query,typeof e?.forExactCount!="function")throw new Error("TeaQL exact count requires the formal runtime SelectQuery");const o=t??"__teaql_total",s=r.deriveOperation(e.forExactCount(o),i??{kind:"named-count",...t!==void 0?{alias:t}:{}}),a=await this.executeQuery(s.query),c=a[0]?.[o];if(a.length!==1||typeof c!="number"||!Number.isSafeInteger(c)||c<0)throw new Error(`TeaQL provider did not return exact count alias ${o}`);return c}async prepareContinuousPage(e){const t=e.localContinuousPageOptions?.(),i=e.localContinuousPageRuntime?.();if(!t||!i)return i?.observe("DISABLED"),{query:e};const r=this.orders(e),o=this.queryLimit(e);if(!o||r.length!==1||r[0].field!=="id"||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return i.observe("OFFSET_FALLBACK:UNSUPPORTED_QUERY_SHAPE"),{query:e};const s=Object.assign(Object.create(Object.getPrototypeOf(e)),e);s.orderItems=[...e.orderItems||[]],s.relations=[...e.relations||[]],Object.defineProperty(s,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:t}),Object.defineProperty(s,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:i});const a=Number(e.offsetValue||e._offset||0),c={...JSON.parse(JSON.stringify(s)),offsetValue:0,_offset:0,commentText:void 0,purposeText:void 0},u=`${t.namespace}|${i.owner}|${JSON.stringify(c)}`;let l=2166136261;for(let m=0;m>>0).toString(16)}`,h={queryKey:d,offset:a,limit:o,direction:String(r[0].direction).toLowerCase(),ttlSeconds:t.ttlSeconds,runtime:i,optimized:!1};if(a===0)return i.observe("OFFSET_FALLBACK:FIRST_PAGE"),{query:s,execution:h};let f;try{f=await me(this.operationTelemetry(),{family:"cache",name:"continuous_page.get",attributes:{"teaql.cache.operation":"get"}},()=>i.get(d,a))}catch{return i.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE"),{query:s,execution:h}}if(!f)return i.observe("OFFSET_FALLBACK:CACHE_MISS"),{query:s,execution:h};const p={id:{[h.direction==="desc"?"$lt":"$gt"]:f.boundary}};return s.filterCondition=s.filterCondition?{$and:[s.filterCondition,p]}:p,s.offsetValue=0,s._offset!==void 0&&(s._offset=0),h.optimized=!0,h.cursorId=f.cursorId,i.observe("CURSOR_SEEK",f.cursorId),{query:s,execution:h}}async registerContinuousPage(e,t,i){if(!(!t||i.length!==t.limit||!i.length||i[i.length-1].id===void 0)){try{await me(this.operationTelemetry(),{family:"cache",name:"continuous_page.put",attributes:{"teaql.cache.operation":"put"}},()=>t.runtime.put(t.queryKey,t.offset+i.length,{cursorId:`cpg_${Date.now().toString(16)}_${Math.random().toString(16).slice(2)}`,boundary:i[i.length-1].id,expiresAt:Date.now()+t.ttlSeconds*1e3}))}catch{t.runtime.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE");return}t.optimized&&t.runtime.observe("CURSOR_SEEK",t.cursorId)}}executeForStream(e,t=1e3){try{const i=e instanceof L?new L(e.query,e.intent):new L(e);return this.executeCapturedStream(i.query,t)}catch(i){return(async function*(){throw i})()}}async*executeCapturedStream(e,t){if(await this.telemetryStartup,!Number.isInteger(t)||t<=0)throw new Error("stream chunk size must be a positive integer");if(Array.isArray(e.facets)&&e.facets.length>0)throw new Error("QRY-F01_STREAM_UNSUPPORTED: execute facets with executeForList");const{sql:i,values:r,aggregateNames:o,groupAliases:s}=await this.compileQuery(e),a=await this.queryTreeBindings(e,i,r),c=H(this.operationTelemetry(),{family:"query",name:`${String(e.entity)}.stream`,attributes:{"teaql.entity.type":String(e.entity)}});let u;const l=async()=>{u=H(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.stream`,attributes:{"teaql.provider.execution":"statement","teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}})};await(c.run?c.run(l):l());const d=u.correlation?.(),h=this.driver.stream(i,r)[Symbol.asyncIterator](),f=Date.now();let p="cancelled",m=0,b=[];const g=this.descendantBindings(e,i,r,a);try{for(;;){const y=await(u.run?u.run(()=>h.next()):h.next());if(y.done)break;b.push(this.decodeRow(e.entity,y.value,o,s)),b.length===t&&(await this.enhanceQueryRows(b,e,g),m+=b.length,yield b,b=[])}b.length&&(await this.enhanceQueryRows(b,e,g),m+=b.length,yield b),p="success"}catch(y){throw p="failure",u.failure(y),c.failure(y),y}finally{try{await h.return?.()}catch(y){if(p!=="failure")throw p="failure",u.failure(y),c.failure(y),y}finally{if(p==="failure")try{this.recordSQL("select",i,r,f,m,void 0,this.queryLogIntent(e),p,a,d)}catch{}else this.recordSQL("select",i,r,f,m,void 0,this.queryLogIntent(e),p,a,d),u.success({attributes:{"teaql.result.cardinality":m}}),c.success({attributes:{"teaql.result.cardinality":m}})}}}async enhanceQueryRows(e,t,i){if(!e.length)return;const r=[...(t.relations??[]).map(a=>a.name),...(t.relationAggregates??[]).map(a=>a.relationName)];if(!r.length)return;const o=this.schema(t.entity),s=new Map;for(const a of r){const c=o.relations?.[a];if(!c)throw new Error(`Missing relation ${t.entity}.${a}`);s.has(c.localKey)||s.set(c.localKey,e.map(u=>u[c.localKey]))}await this.enhanceRelationAggregates(e,t,s,i),await this.enhanceRelations(e,t,s,i)}async enhanceRelations(e,t,i,r){if(!e.length||!Array.isArray(t.relations)||!t.relations.length)return;const o=this.schema(t.entity),s=new L(t).intent;for(const a of t.relations){const c=o.relations?.[a.name];if(!c)throw new Error(`Missing relation ${t.entity}.${a.name}`);const u=i.get(c.localKey),l=u.filter(w=>w!=null),d=a.query?this.queryLimit(a.query):void 0,h=a.query?.localTopNProbeParentThreshold?.(),f=c.many&&d!==void 0,p=Array.isArray(a.query?.selectItems)?a.query.selectItems:[],m=p.length>0&&!p.includes(c.foreignKey),b=this.driver.topNRelationPlanPolicy==="alwaysProbe",g=f&&(h===void 0?b:h>0&&l.length<=h),y=g?"bounded_probes":"window",O=H(this.operationTelemetry(),{family:"relation_load",name:`${t.entity}.${String(a.name)}`,attributes:{"teaql.entity.type":String(t.entity),"teaql.relation.name":String(a.name),"teaql.relation.parent_count":l.length,"teaql.relation.per_parent_limit":d??0,"teaql.relation.configured_probe_threshold":h??"provider-default","teaql.relation.selected_plan":y,"teaql.relation.probe_count":g?l.length:0}});try{if(!l.length&&!(c.many&&a.query?.facets?.length)){for(const T of e)T[a.name]=c.many?[]:null;O.success({attributes:{"teaql.result.cardinality":0}});continue}const w={...a.query||{},entity:c.targetEntity,selectItems:m?[...p,c.foreignKey]:p,_filters:[...this.filters(a.query||{})],relations:[...a.query?.relations||[]],orderItems:[...a.query?.orderItems||[]],__teaqlPartitionBy:f&&!g?c.foreignKey:void 0};if(f){const T=this.groupBy(w),R=T.length||this.aggregates(w).length?T:["id"];for(const v of R)w.orderItems.some(S=>S.field===v)||w.orderItems.push(Y.asc(v))}typeof w.clearContinuousPageRuntime=="function"&&w.clearContinuousPageRuntime(),w[this.internalQueryToken]=!0;const E=[],k={field:c.foreignKey,keys:new WeakMap};if(g)for(const T of l){const R={...w,_filters:[...w._filters,{[c.foreignKey]:{$eq:T}}],__teaqlPartitionBy:void 0};E.push(...await this.executeDerivedQuery(new L(t).derive(R,a.name,a.operation).query,r,s,k))}else w._filters.push({[c.foreignKey]:{$in:l}}),E.push(...await this.executeDerivedQuery(new L(t).derive(w,a.name,a.operation).query,r,s,k));for(const T of E)delete T.__teaql_partition_rank;const j=new Map;for(const T of E){if(!k.keys.has(T))throw new Error("Relation assembly lost its captured row identity");const R=k.keys.get(T),v=j.get(R)||[];v.push(T),j.set(R,v)}if(m)for(const T of E)delete T[c.foreignKey];for(const[T,R]of e.entries()){const v=j.get(u[T])||[];if(c.many&&a.query?.facets?.length){const S=a.query.clone();S.entity=c.targetEntity;const _=u[T],z={[c.foreignKey]:_==null?{$in:[]}:{$eq:_}};S.filterCondition=S.filterCondition?{$and:[S.filterCondition,z]}:z,je(t,S);const ae=new L(t).derive(S,a.name,a.operation).query;R[a.name]=new ee(v,{facets:await Xi(this,Ji=>Ji,ae,S.facets)})}else{const S=u[T];R[a.name]=c.many?v:v[0]??(S==null?null:{[c.foreignKey]:S})}}O.success({attributes:{"teaql.result.cardinality":E.length}})}catch(w){throw O.failure(w),w}}}async enhanceRelationAggregates(e,t,i,r){const o=t.relationAggregates;if(!e.length||!Array.isArray(o)||!o.length)return;const s=this.schema(t.entity),a=new L(t).intent;for(const c of o){const u=s.relations?.[c.relationName];if(!u)throw new Error(`Missing relation ${t.entity}.${c.relationName}`);const l=i.get(u.localKey),d=l.filter(b=>b!=null);if(!d.length){for(const b of e)b[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{};continue}const h=c.query.clone();h.entity=u.targetEntity,h.selectItems=[],h.properties=[],h.orderItems=[],h.limitValue=0,h.offsetValue=0,h.relations=[],h.relationAggregates=[],h.aggregateItems.length||h.aggregate("Count","id",c.alias),h.groupByItems.includes(u.foreignKey)||h.groupBy(u.foreignKey);const f={[u.foreignKey]:{$in:d}};h.filterCondition=h.filterCondition?{$and:[h.filterCondition,f]}:f,h[this.internalQueryToken]=!0;const p=await this.executeDerivedQuery(new L(t).deriveAggregate(h,c.relationName,c.operation??{kind:"relation-count",relation:c.relationName,alias:c.alias}).query,r,a),m=new Map;for(const b of p)m.set(b[u.foreignKey],b);for(const[b,g]of e.entries()){const y=m.get(l[b]);y?c.singleResult?g[c.alias]=y[h.aggregateItems[0].alias]??null:g[c.alias]=Object.fromEntries(Object.entries(y).filter(([O])=>O!==u.foreignKey)):g[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{}}}}emptyAggregateValue(e){const t=e.aggregateItems[0];return!t||String(t.function).toLowerCase()==="count"?0:null}queryLimit(e){if(e._limit!==void 0)return Number(e._limit);if(e.limitValue!==void 0&&Number(e.limitValue)>0)return Number(e.limitValue)}async close(){try{await this.driver.close()}finally{await this.telemetryStartup,await this.standardTelemetryHandle?.release(),this.standardTelemetryHandle=void 0}}}function xr(n){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new Error(`Unsafe SQL identifier: ${n}`);return n}function qr(n){const t={count:"COUNT",sum:"SUM",avg:"AVG",min:"MIN",max:"MAX"}[String(n).toLowerCase()];if(!t)throw new Error(`Unsupported aggregate: ${n}`);return t}class Mr{constructor(e){this.worker=e,this.nextRequestId=1,this.pending=new Map,this.closed=!1,this.onMessage=t=>{const i=t.data;if(!i||i.type!=="teaql-browser-sqlite-response")return;const r=this.pending.get(i.requestId);if(r)if(this.pending.delete(i.requestId),i.error){const o=new Error(i.error.message);o.name=i.error.name,i.error.code&&(o.code=i.error.code),r.reject(o)}else r.resolve(i.result)},this.onError=t=>{const i=new Error(t.message||"Browser SQLite worker failed");i.name="BrowserSQLiteWorkerError";for(const r of this.pending.values())r.reject(i);this.pending.clear()},e.addEventListener("message",this.onMessage),e.addEventListener("error",this.onError)}request(e,t){if(this.closed)return Promise.reject(new Error("Browser SQLite worker is closed"));const i=this.nextRequestId++;return new Promise((r,o)=>{this.pending.set(i,{resolve:s=>r(s),reject:o}),this.worker.postMessage({type:"teaql-browser-sqlite-request",requestId:i,operation:e,payload:t})})}async close(e){if(!this.closed)try{await this.request("close")}finally{this.closed=!0,this.worker.removeEventListener("message",this.onMessage),this.worker.removeEventListener("error",this.onError),e&&this.worker.terminate?.();const t=new Error("Browser SQLite worker is closed");for(const i of this.pending.values())i.reject(t);this.pending.clear()}}}class Dr{constructor(e){this.transport=e}query(e,t=[]){return this.transport.request("query",{sql:e,values:t})}}class Rt{constructor(e,t){this.transport=e,this.options=t,this.databaseKind="sqlite",this.accessTail=Promise.resolve()}static async open(e,t={}){const i={storage:t.storage??"memory",databaseName:zr(t.databaseName??"teaql-browser.sqlite3"),terminateWorkerOnClose:t.terminateWorkerOnClose??!0},r=new Mr(e);return await r.request("open",i),new Rt(r,i)}identifier(e){return`"${xr(e)}"`}placeholder(e){return"?"}contains(e,t){return`CAST(${e} AS TEXT) LIKE '%' || ${t} || '%'`}aggregateFunction(e){return qr(e)}decimalComparison(e,t,i){return`teaql_decimal_cmp(${e}, ${i}) ${t} 0`}decimalOrderExpression(e){return`teaql_decimal_order_key(${e})`}decimalAggregateFunction(e){const i={sum:"teaql_decimal_sum",min:"teaql_decimal_min",max:"teaql_decimal_max"}[e.toLowerCase()];if(!i)throw new Error(`EXACT_DECIMAL_UNSUPPORTED: ${e} requires an explicit exact rounding policy`);return i}longComparison(e,t,i){return`CAST(${e} AS INTEGER) ${t} CAST(${i} AS INTEGER)`}longOrderExpression(e){return`CAST(${e} AS INTEGER)`}encode(e,t){return e==null?e:t?.logicalType==="decimal"&&t.decode==="decimal"?ue(e):t?.logicalType==="long"?be(e):t?.logicalType==="time"?Ce(e):t?.logicalType==="json"&&typeof e!="string"?JSON.stringify(e):t?.logicalType==="boolean"?e?1:0:e instanceof Date?e.toISOString():e}async exclusive(e){const t=this.accessTail;let i;this.accessTail=new Promise(r=>{i=r}),await t;try{return await e()}finally{i()}}query(e,t=[]){return this.exclusive(()=>this.transport.request("query",{sql:e,values:t}))}async*stream(e,t=[]){const i=await this.query(e,t);for(const r of i.rows)yield r}transaction(e){return this.exclusive(async()=>{const t=new Dr(this.transport);await t.query("BEGIN IMMEDIATE");try{const i=await e(t);return await t.query("COMMIT"),i}catch(i){try{await t.query("ROLLBACK")}catch{}throw i}})}async ensureSchema(e){for(const t of Object.values(e)){const i=this.identifier(t.table);await this.query(`CREATE TABLE IF NOT EXISTS ${i} ("id" INTEGER PRIMARY KEY, "version" INTEGER NOT NULL)`);const r=await this.query(`PRAGMA table_info(${i})`),o=new Set(r.rows.map(s=>String(s.name)));for(const[s,a]of Object.entries(t.columns)){if(a.logicalType==="decimal"&&a.decode==="decimal"||a.logicalType==="long"){const c=r.rows.find(u=>String(u.name)===a.columnName);if(c&&String(c.type).toUpperCase()!=="TEXT")throw new Error(`EXACT_${a.logicalType.toUpperCase()}_SCHEMA_MISMATCH: ${t.table}.${a.columnName} requires TEXT; migrate the existing column explicitly`)}s==="id"||s==="version"||o.has(a.columnName)||await this.query(`ALTER TABLE ${i} ADD COLUMN ${this.identifier(a.columnName)} ${Fr(a.logicalType,a.decode)}${a.nullable===!1?" NOT NULL":""}`)}}for(const t of Ar(e))await this.query(`CREATE INDEX IF NOT EXISTS ${this.identifier(t.name)} ON ${this.identifier(t.table)} (${this.identifier(t.foreignColumn)}, ${this.identifier(t.idColumn)} DESC)`);await this.query("CREATE TABLE IF NOT EXISTS teaql_id_space (type_name TEXT PRIMARY KEY, current_level INTEGER NOT NULL)")}async nextId(e,t){for(let i=1;i<=100;i+=1){const r=await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t]);if(!r.rowCount){try{if((await e.query("INSERT INTO teaql_id_space(type_name, current_level) VALUES (?, 1)",[t])).rowCount===1)return"1"}catch(c){if(!(await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t])).rowCount)throw c}continue}const o=Number(r.rows[0].id),s=o+1,a=await e.query("UPDATE teaql_id_space SET current_level = ? WHERE type_name = ? AND current_level = ?",[s,t,o]);if(a.rowCount===1)return String(s);if(a.rowCount!==0)throw new Error(`ID space update for ${t} changed ${a.rowCount} rows`)}throw new Error(`Unable to allocate ID for ${t} after 100 optimistic-lock attempts`)}ensureIdFloor(e,t,i){return Rr(e,r=>this.placeholder(r),t,i)}reset(){return this.exclusive(()=>this.transport.request("reset",this.options))}close(){return this.exclusive(()=>this.transport.close(this.options.terminateWorkerOnClose))}}class Yi extends Nr{constructor(e,t){super(e,t),this.browserDriver=e}static async open(e,t,i={}){return new Yi(await Rt.open(e,i),t)}get storage(){return this.browserDriver.options.storage}async reset(e){await this.browserDriver.reset(),this.invalidateSchemaState(),await e.ensureSchema()}}function Fr(n,e){return{boolean:"INTEGER",double:"REAL",decimal:e==="decimal"?"TEXT":"NUMERIC",long:"TEXT",time:"TEXT",date:"TEXT",datetime:"TEXT",json:"TEXT",integer:"INTEGER",text:"TEXT"}[n]}function zr(n){const e=n.trim();if(!e||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new TypeError("Browser SQLite databaseName must be a simple file name");return e}function Vr(n){if(typeof n!="string")return!1;try{return ue(n),!0}catch{return!1}}function Yr(n,e,t,i){const r=o=>{if(o.includes("."))throw new Error("Dynamic search requires a trusted relation binding");const s=t[n.entity]?.queryFields;if(!s||!Object.prototype.hasOwnProperty.call(s,o))throw new Error("Missing generated scalar search binding");return s[o]};return Ur(n,e,t,{filter:(o,s)=>{const[a,c]=Object.entries(s)[0];if(c===null&&a!=="$eq"&&a!=="$ne")throw new Error("Null supports only equality predicates");return{[r(o)]:s}},order:(o,s)=>s==="asc"?Y.asc(r(o)):Y.desc(r(o))},i)}function Ur(n,e,t,i,r=o=>console.warn({...o,fieldPath:""})){const o=Qr(e,n.entity,t,()=>{}),s=Object.entries(o.search.filter??{}).map(([d,h])=>i.filter(d,h)),a=(o.search.orderBy??[]).map(d=>i.order(d.field,d.direction));if(s.some(d=>!Re(d)))throw new Error("Invalid trusted search filter binding");if(a.some(d=>!(d instanceof Y)))throw new Error("Invalid trusted search order binding");const c=n.clone(),u=n._filters??[],l=[...u,...n.filterCondition?[n.filterCondition]:[]];return(s.length||u.length)&&c.filter({$and:[...l,...s]}),c.orderItems.push(...a),o.warnings.forEach(d=>r({...d})),{query:c,warnings:o.warnings}}const Ke=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),Re=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Br=new Set(["__proto__","prototype","constructor"]),Kr=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$notIn","$contains"]);function Qr(n,e,t,i=o=>console.warn({...o,fieldPath:""}),r=100){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid search limit");if(!Ke(t,e))throw new Error("Unknown search entity");let o;try{o=typeof n=="string"?JSON.parse(n):n}catch{throw new Error("Dynamic search requires valid JSON")}if(!Re(o)||Object.keys(o).some(f=>!["filter","orderBy"].includes(f)))throw new Error("Unsupported dynamic search input or control");if(o.filter!==void 0&&!Re(o.filter))throw new Error("Invalid search filter");if(o.orderBy!==void 0&&!Array.isArray(o.orderBy))throw new Error("Invalid search ordering");const s=Object.entries(o.filter??{}),a=o.orderBy??[];if(s.length+a.length>r)throw new Error("Dynamic search exceeds clause limit");const c=[],u={filter:Object.create(null),orderBy:[]};function l(f){const p=f.split(".");if(p.length>16||p.some(g=>!g||g.startsWith("$")||Br.has(g)))throw new Error("Invalid dynamic search field path");let m=t[e];for(const g of p.slice(0,-1)){if(!Ke(m.relations,g))return;const y=m.relations[g];if(!Ke(t,y))throw new Error("Invalid trusted search relation metadata");m=t[y]}const b=p[p.length-1];return Ke(m.fields,b)?m.fields[b]:void 0}function d(f,p){c.push({code:"DYNAMIC_SEARCH_UNKNOWN_FIELD",entity:e,clause:p,fieldPath:f})}function h(f,p){if(f===null)return;if(!(p==="date"?typeof f=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(f)&&!f.startsWith("0000-")&&Number.isFinite(Date.parse(f+"T00:00:00Z"))&&new Date(f+"T00:00:00Z").toISOString().slice(0,10)===f:p==="decimal"?Vr(f):p==="integer"||p==="timestamp"?typeof f=="number"&&Number.isSafeInteger(f):p==="number"?typeof f=="number"&&Number.isFinite(f):typeof f===p))throw new Error("Invalid value for known search field")}for(const[f,p]of s){const m=Re(p)?Object.entries(p):[["$eq",p]];if(m.length!==1||!Kr.has(m[0][0]))throw new Error("Unsupported or malformed dynamic search operator");const[b,g]=m[0];if((b==="$in"||b==="$notIn")&&(!Array.isArray(g)||g.length>1e3))throw new Error("Invalid or oversized search value list");const y=l(f);if(y===void 0){d(f,"FILTER");continue}if(y==="unsupported")throw new Error("Known search field has no supported scalar binding");if(b==="$contains"&&y!=="string")throw new Error("String operator requires a string field");if(Array.isArray(g)){if(b!=="$in"&&b!=="$notIn")throw new Error("Unexpected search value list");g.forEach(O=>h(O,y))}else h(g,y);u.filter[f]={[b]:Array.isArray(g)?[...g]:g}}for(const f of a){if(!Re(f)||Object.keys(f).some(m=>!["field","direction"].includes(m))||typeof f.field!="string"||!["asc","desc"].includes(f.direction))throw new Error("Invalid dynamic search ordering");const p=l(f.field);if(p===void 0){d(f.field,"ORDER_BY");continue}if(p==="unsupported")throw new Error("Known search field has no supported scalar binding");u.orderBy.push({field:f.field,direction:f.direction})}return c.forEach(f=>i({...f})),{search:u,warnings:c}}export{Yi as B,G as C,Wr as D,wn as E,$ as L,Ie as M,Y as O,it as Q,It as R,jr as S,rt as U,ee as a,Xr as b,Hr as c,F as d,Xi as e,Gn as f,M as g,ue as h,ui as i,Yr as j,jt as k,Ur as m,ct as n}; diff --git a/assets/entity-creation-Bqaw1C4U.js b/assets/entity-creation-Bqaw1C4U.js new file mode 100644 index 0000000000000000000000000000000000000000..f20b27b341b92f0c398ab72e3e59f140df8640ef --- /dev/null +++ b/assets/entity-creation-Bqaw1C4U.js @@ -0,0 +1 @@ +import{U as l,k as f,L as p}from"./dynamic-search-BwvXmN4R.js";const d=new WeakMap,u=new WeakSet,i=new WeakMap,y=(o,t)=>JSON.stringify([o,t]);class a extends Error{constructor(){super("ENTITY_CREATION_CONTEXT_REQUIRED: create through the Context-bound Q factory or load a persisted version before mutation"),this.code="ENTITY_CREATION_CONTEXT_REQUIRED",this.name="EntityCreationError"}}class T{static async create(t,r,s){if(!(t instanceof l))throw new a;const n=await t.generateInternalId(r),e=s(n);return d.set(e,Object.freeze({entity:r,id:n})),e}static bootstrap(t,r,s,n){if(!(t instanceof l))throw new a;const e=f(s);if(!i.get(t)?.has(y(r,e)))throw new a;const c=n(e);return d.set(c,Object.freeze({entity:r,id:e})),c}static hydrated(t){return u.add(t),t}static requireMutation(t,r,s,n,e,c){if(!c)return;let w;try{w=f(s)}catch{throw new a}if(f(r.id)!==w)throw new a;const h=p.forEntity(t);if(n==="Create"){const E=d.get(t);if(!E||E.entity!==r.entity||E.id!==w||h?.origin!=="creationBaseline"||!e.isNew(r))throw new a}else if(!u.has(t)&&!d.has(t)||h?.origin!=="hydrated"||h.persistedVersion===void 0)throw new a}}async function I(o,t,r){const s=i.get(o),n=new Set;for(const e of[t.defaultDomainRoot,...t.constants??[]])e&&n.add(y(e.entity,f(e.id)));i.set(o,n);try{await r()}finally{s?i.set(o,s):i.delete(o)}}export{T as EntityCreation,a as EntityCreationError,I as runGeneratedBootstrap}; diff --git a/assets/main-Csdici-L.js b/assets/main-Csdici-L.js new file mode 100644 index 0000000000000000000000000000000000000000..166de027a039c2f996560a2065240388d9462ee3 --- /dev/null +++ b/assets/main-Csdici-L.js @@ -0,0 +1,104 @@ +import{S as x,m as De,a as qe,e as xe,O as R,B as Qe,b as Be,R as Re,U as $e,D as ke,c as Fe,M as ze}from"./dynamic-search-BwvXmN4R.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),h=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),We=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],V={Platform:{table:"platform_data",columns:{id:C("id"),name:h("name"),code:h("code"),region:h("region"),currency:h("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:h("name"),email:h("email"),city:h("city"),tier:h("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:h("order_number"),orderDate:We("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:h("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:h("name"),code:h("code"),color:h("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:h("product_name"),sku:h("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:h("provider"),status:h("status"),amount:I("amount"),currency:h("currency"),transactionId:h("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:h("carrier"),status:h("status"),trackingNumber:h("tracking_number"),shipToCity:h("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:200,lineAmount:400}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:80,lineAmount:80}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:168,lineAmount:168}},{entity:"OrderItem",id:"2012",payload:{orderId:"1008",productName:"Keyboard Protective Case",sku:"KB-CASE-68",quantity:1,unitPrice:30,lineAmount:30}},{entity:"OrderItem",id:"2013",payload:{orderId:"1008",productName:"Foldable Travel Stand",sku:"KB-STAND-FOLD",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2014",payload:{orderId:"1008",productName:"Braided USB-C Cable",sku:"CABLE-USBC",quantity:1,unitPrice:20,lineAmount:20}},{entity:"OrderItem",id:"2015",payload:{orderId:"1008",productName:"Accent Keycap Set",sku:"KEYCAP-ACCENT",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2016",payload:{orderId:"1006",productName:"Balanced Audio Cable",sku:"AUDIO-XLR",quantity:1,unitPrice:40,lineAmount:40}},{entity:"OrderItem",id:"2017",payload:{orderId:"1006",productName:"Speaker Isolation Pads",sku:"SPK-PADS",quantity:1,unitPrice:60,lineAmount:60}},{entity:"OrderItem",id:"2018",payload:{orderId:"1006",productName:"USB DAC Adapter",sku:"AUDIO-DAC-USB",quantity:1,unitPrice:60,lineAmount:60}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],N=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(` +`,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const i=f[String(a)];return i===void 0?a:Number(i)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class P{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${N(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${N(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(` +`)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(m=>!(String(m.function).toLowerCase()==="count"&&m.alias===this.pageTotalAlias)));const i=await n.executeQuery(e.prepareQuery(a)),c=new qe(i,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,m=>e.prepareQuery(m),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends P{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ge extends P{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ye extends P{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends P{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${N(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${N(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends P{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends P{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends P{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=De(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?R.asc(s):R.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${N(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${N(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${N(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ge}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ye}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const F=document.querySelector("#status"),$=document.querySelector("#persist"),G=document.querySelector("#reset"),k=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),X=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),B=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),ee=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},developmentProcess:{en:"00 / DEVELOPMENT PROCESS",zh:"00 / 开发过程"},developmentProcessTitle:{en:"From one domain model to executable evidence.",zh:"从一份领域模型,到可以执行和审查的证据。"},developmentProcessIntro:{en:"TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.",zh:"TeaQL 让业务模型保持精简、可读,从模型生成确定性的领域 API,并把请求意图一直带到 Runtime 实际执行的 SQL。"},modelSource:{en:"MODEL SOURCE",zh:"模型源文件"},viewOrderModel:{en:"View order-model.xml",zh:"查看 order-model.xml"},scopedGuidance:{en:"SCOPED GUIDANCE",zh:"按需指导"},viewModelAssist:{en:"View model-aware Assist",zh:"查看模型感知 Assist"},processModelTitle:{en:"Model the domain",zh:"建立领域模型"},processModelBody:{en:"Define entities, fields, relationships, constant objects, and constraints in one model file.",zh:"在一个模型文件中定义对象、字段、关系、常数对象和约束。"},processGenerateTitle:{en:"Generate the working surface",zh:"生成领域开发接口"},processGenerateBody:{en:"Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.",zh:"从模型生成强类型 Q 与 E API、Schema、可审计变更和字段级 Assist。"},processQueryTitle:{en:"Build one bounded Q request",zh:"构建一个有界的 Q 请求"},processQueryBody:{en:"Application code selects only what the page needs and attaches a readable comment and purpose.",zh:"应用代码只选择页面需要的内容,并附上可读的 comment 和 purpose。"},processEvidenceTitle:{en:"Run and retain evidence",zh:"运行并保留证据"},processEvidenceBody:{en:"The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.",zh:"Runtime 执行策略和 SQLite/WASM,并保留从 purpose、嵌套 comment 到耗时和实际 SQL 的 TraceChain。"},contextEfficiency:{en:"CONTEXT EFFICIENCY",zh:"上下文效率"},contextEfficiencyTitle:{en:"Spend context on the business change.",zh:"把上下文窗口留给真正的业务变更。"},contextEfficiencyBody:{en:"Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.",zh:"Agent 不需要加载 Runtime 内部实现和所有生成文件,而是从精简模型出发,只打开当前对象、动作或字段所需的 Assist。强类型领域操作把数据库和 Provider 细节压缩成更小的工作界面,减少重复占用上下文,同时保持行为确定、可审查。"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let d=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[d]??t}function O(t){return d==="en"?nt[t]??t:t}let E,z=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",T,fe=0,te;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";$.checked=Ae==="opfs";async function Y(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function re(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset) + .limit(pageSize) + .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:re(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() + .selectPlatformWith(Q.platforms().selectName()) + .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .orderByOrderDateDescending() + .orderByIdDescending() + .limit(8) + .comment('what: list recent commerce orders') + .purpose('why: provide the default order overview') + .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() + .withOrderNumberIs('TQL-2026-1003') + .selectPlatformWith(Q.platforms()) + .selectCustomerWith(Q.customers()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectItemListWith(Q.orderItems().orderByIdAscending()) + .selectPaymentListWith(Q.payments().orderByIdAscending()) + .selectShipmentListWith(Q.shipments().orderByIdAscending()) + .limit(1) + .comment('what: load one complete order graph') + .purpose('why: inspect items, payment and fulfillment together') + .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() + .selectPlatformWith(Q.platforms().selectName()) + .countOrderListAs('orderCount') + .orderByNameAscending() + .comment('what: list customers with related order counts') + .purpose('why: compare customer activity at a glance') + .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() + .groupByCurrency().groupByStatus() + .countAs('orderCount') + .sumTotalAmountAs('grossAmount') + .averageTotalAmountAs('averageOrderValue') + .comment('what: aggregate orders by currency and status') + .purpose('why: show the current order funnel') + .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() + .groupByProductName() + .sumQuantityAs('units') + .sumLineAmountAs('revenue') + .comment('what: aggregate sold units and line revenue') + .purpose('why: identify the strongest products in the demo data') + .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() + .groupByCurrency().groupByProvider().groupByStatus() + .countAs('paymentCount').sumAmountAs('paymentAmount') + .orderByCurrencyAscending().orderByProviderAscending() + .comment('what: reconcile payment totals by provider') + .purpose('why: compare captured, pending and refunded money') + .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、范围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() + .withStatusIsPendingPayment() + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectCustomerWith(Q.customers().selectName()) + .selectPaymentListWith(Q.payments()) + .comment('what: find orders awaiting payment') + .purpose('why: support payment follow-up') + .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() + .withPlatformIdIs('1') + .withTotalAmountGreaterThanOrEqualTo(500) + .selectCustomerWith(Q.customers().selectName().selectCity()) + .orderByTotalAmountDescending() + .comment('what: find high-value domestic orders') + .purpose('why: prioritize valuable fulfillment work') + .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() + .withStatusIn('READY', 'IN_TRANSIT') + .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) + .orderByStatusAscending().orderByIdAscending() + .comment('what: find shipments that are not delivered') + .purpose('why: monitor active fulfillment') + .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { + "filter": { + "currency": "CNY", + "totalAmount": { "$gte": "250" }, + "status": { "$in": ["PAID", "SHIPPED"] } + }, + "orderBy": [{ "field": "totalAmount", "direction": "desc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>Y(t,{filter:{currency:"CNY",totalAmount:{$gte:"250"},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { + "filter": { "orderDate": { "$gte": "2026-09-15" } }, + "orderBy": [{ "field": "orderDate", "direction": "asc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>Y(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { + "filter": { + "status": "DELIVERED", + "internalNote": { "$contains": "not queryable" } + } +}; +const request = Q.customerOrders().filterByJson(input); +const data = await request + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx); +const warnings = request.warnings();`,run:t=>Y(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...V},{storage:t,databaseName:"teaql-order-playground-v4.sqlite3"}),n=new Be().enableSelect();r.install(new Re(V,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v2"}),o=new $e().insertResource("dataService",r).withMutationPolicyRegistry(new ke(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Fe(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new ze("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:Object.fromEntries(Object.entries(o.payload).map(([a,i])=>{const c=V[o.entity]?.columns[a];if(!c)throw new Error(`Unknown fixture field ${o.entity}.${a}`);return[c.modelName??a,i]}))}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){k.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const i=document.createElement("a");i.href=`#${a.id}`,i.dataset.queryId=a.id,i.textContent=O(a.title),i.addEventListener("click",c=>{c.preventDefault(),z=a.id,history.replaceState(null,"",`#${a.id}`),Z(),E&&v(a,E).catch(L)}),o.append(i)}e.append(r,o),k.append(e)}Z()}function Z(){k.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===z;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function v(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),w.classList.toggle("dashboard-result",t.view==="dashboard"),ee.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),B.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",X.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),T={data:s,query:t,active:e},b=t.view==="dashboard"||J(s)?"table":"tree",W();const o=Math.max(1,Math.round(performance.now()-r));fe=o,te=n;const a=e.evidence.snapshot();be(a,n),Ne(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=te){ue.replaceChildren(),et.textContent=d==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const i=document.createElement("td");i.textContent=`${T?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const p=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${p}`,s.append(a,i,c,m),ue.append(s)})}function J(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function W(){if(!T)return;const{data:t,query:e,active:r}=T,n=e.view==="dashboard"||J(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),H.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),H.setAttribute("aria-pressed",String(b==="tree")),ee.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){B.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&J(t)){B.textContent=d==="en"?"Result table":"结果表格",ut(t);return}B.textContent=d==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const i=document.createElement("p");i.className="result-table-empty",i.textContent=d==="en"?"The query returned no records.":"查询没有返回记录。",e.append(i),w.replaceChildren(e);return}const r=[...new Set(t.flatMap(i=>Object.keys(i)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const i of r){const c=document.createElement("th");c.scope="col",c.textContent=i,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const i of t){const c=document.createElement("tr");for(const m of r){const p=document.createElement("td");p.textContent=lt(i[m]),c.append(p)}a.append(c)}n.append(s,a),e.append(n),w.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return d==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=re(e);if(r)return we(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?d==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=d==="en"?"Order Management Center":"订单管理中心";const i=document.createElement("p");i.textContent=d==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,i);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const p=document.createElement("button");p.type="submit",p.className="order-search-submit",p.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),p.title=d==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),p.append(l),c.append(m,p),c.addEventListener("submit",y=>{y.preventDefault(),A.search=m.value.trim(),A.page=0,v(r,e).catch(L)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(d==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,v(r,e).catch(L)}));for(const y of t.statusFacets)S.append(me(y.name,y.orderCount,y.code.toLowerCase(),y.color,t.search.toUpperCase()===y.code,()=>{A.search=y.code,A.page=0,v(r,e).catch(L)},`${d==="en"?"Total":"总额"} ${pt(y.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const Te=d==="en"?["Order number","Order date","Status","Line Items"]:["订单号","订单日期","状态","订单明细"];for(const y of Te){const q=document.createElement("span");q.textContent=y,M.append(q)}if(g.append(M),!t.orders.length){const y=document.createElement("div");y.className="order-empty",y.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(y)}for(const y of t.orders)g.append(yt(y));const _=document.createElement("div");_.className="order-center-footer";const se=document.createElement("p"),oe=t.filteredOrders?t.page*t.pageSize+1:0,ae=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);se.textContent=d==="en"?`Showing ${oe}–${ae} of ${t.filteredOrders} orders`:`显示 ${oe}–${ae},共 ${t.filteredOrders} 条订单`;const D=document.createElement("div");D.className="pagination";const ie=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));D.append(j("‹",t.page-1,t.page===0,e,r));for(let y=0;y=ie-1,e,r)),_.append(se,D),n.append(s,S,g,_),w.replaceChildren(n)}function me(t,e,r,n,s,o,a){const i=document.createElement("button");i.type="button",i.className=`metric-card metric-${r}`,n&&i.style.setProperty("--metric-color",n),i.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),i.append(c,m),a){const p=document.createElement("small");p.textContent=a,i.append(p)}return i.addEventListener("click",o),i}function pt(t){return new Intl.NumberFormat(d==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=re(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=we(i)||String(r.name??i);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const p=Number(t.itemCount??n.length);if(p>n.length){const l=document.createElement("small");l.className="line-item-count",l.textContent=d==="en"?`${p} items`:`共 ${p} 项`,l.title=d==="en"?`Showing ${n.length} of ${p} line items`:`显示 ${n.length} 项,共 ${p} 项订单明细`,m.append(l)}return e.append(m),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,v(s,n).catch(L)}),o}function we(t){return(d==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){w.replaceChildren(Le(t,"result",0))}function Le(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),i=document.createElement("details");i.className="tree-branch",i.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const p=document.createElement("span");p.className="tree-preview",p.textContent=ht(t,a.length),c.append(m,p),i.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of a)l.append(Le(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(l),i}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return d==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):d==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Ne(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=d==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;X.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;F.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=d==="en"?"en":"zh-CN",document.title=d==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=d==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===d;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",d==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",d==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",d==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",d==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",d==="en"?"Runtime settings":"运行时设置"),k.setAttribute("aria-label",d==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",d==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",d==="en"?"Result tree actions":"结果树操作"),dt(),T){const{data:e,query:r,active:n}=T;ye.textContent=O(r.title),he.textContent=O(r.description),W(),be(n.evidence.snapshot(),te),Ne(e,r,fe),Oe($.checked?"opfs":"memory")}else F.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function ne(){return le.find(t=>t.id===z)??le[0]}async function Pe(t){F.textContent=d==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await v(ne(),r),Oe(t)}$.addEventListener("change",()=>{const t=$.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Pe(t).catch(L)});G.addEventListener("click",async()=>{if(E){G.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await v(ne(),E)}catch(t){L(t)}finally{G.disabled=!1}}});ee.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",W())});H.addEventListener("click",()=>{b="tree",W()});tt.addEventListener("click",()=>{w.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{d=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",d),ve()})});function L(t){const e=t instanceof Error?t:new Error(String(t));F.textContent=`${e.name}: ${e.message}`,X.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}ve();z=ne().id;Z();Pe(Ae).catch(L); diff --git a/assets/orders-DBfzfR_e.js b/assets/orders-DBfzfR_e.js new file mode 100644 index 0000000000000000000000000000000000000000..45ca2800723e6fb607fbbeae6773510c11607b98 --- /dev/null +++ b/assets/orders-DBfzfR_e.js @@ -0,0 +1,2 @@ +import{d as p,S as bt,f as Y,E as k,a as L,g as Z,L as d,M as N,C as g,n as tt,i as X,h as mt,j as et,e as M,Q as rt,U as H,R as Nt,B as Et,D as $t,c as Tt,b as Dt}from"./dynamic-search-BwvXmN4R.js";import{EntityCreationError as it,EntityCreation as E}from"./entity-creation-Bqaw1C4U.js";/* empty css */class D{constructor(t,e,r,i,s){this.rootExpression=t,this.profile=e,this.location=r,this.steps=i,this.missing=s}static root(t,e="camelCase"){return new D(t,e,p.root(),[])}member(t,e){return this.append(`${e}()`,this.location.property(t),!0)}index(t,e=!1){return this.append(e?"first()":`get(${t})`,this.location.index(t),!0)}operation(t){return this.append(t,this.location,!1)}append(t,e,r){return new D(this.rootExpression,this.profile,e,[...this.steps,{call:t,location:e,traverses:r}],this.missing)}markMissing(){return new D(this.rootExpression,this.profile,this.location,this.steps,this.missing??this.steps.length-1)}withFailureFrom(t){return new D(this.rootExpression,this.profile,this.location,this.steps,t.missing)}render(t=!1){return this.rootExpression+this.steps.map((e,r)=>`.${e.call}${t&&r===this.missing?"":""}`).join("")}diagnostic(t){const e=this.missing===void 0?this.location:this.steps[this.missing].location,r=e.segments[e.segments.length-1];return{code:"NOT_LOADED",location:e.segments,instancePath:e.instancePath(this.profile),breakPoint:r?.kind==="property"?r.name:t,attemptedLocation:this.location.segments,attemptedInstancePath:this.location.instancePath(this.profile),breakPointIndex:Math.max(0,e.segments.length-1),originalExpression:this.render(),expressionWithBrokenPoint:this.render(!0),suggestedFix:{action:"preload",location:e.segments}}}}class v extends Error{constructor(t,e){const r=t.diagnostic(e),i=r.location.reduce((s,o)=>o.kind==="index"?s.index(o.index):s.property(o.name),p.root());super(`TeaQLNotLoadedError: access_path=${i.nativePath()} break_point=${r.breakPoint} — select the missing field or relation expression=${r.expressionWithBrokenPoint}`),this.path=t,this.breakPoint=e,this.name="TeaQLNotLoadedError",this.details=r}withPath(t){return new v(t.withFailureFrom(this.path),this.breakPoint)}terminal(t){return new v(this.path.operation(t),this.breakPoint)}toWire(){return this.details}}class O extends bt{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,r="id",i="id",s=!0,o){return super.relationQuery(t,e,r,i,s,o)}}const nt=Symbol("managed entity construction");class T{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("Customer",["id","platform","name","version"],{id:"immutable_field",version:"immutable_field"});id;platform;name;version;constructor(t,e,r=!1){if(e!==nt)throw new it;if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--T.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.customerOrderList,Object.assign(this,s),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof C?t.platform:C.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const o=t.customerOrderList;this._customerOrderList=new L(o.map(n=>n instanceof b?n:b.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("customerOrderList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Customer",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._customerOrderList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new T(t,nt));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("customerOrderList")&&(t.customerOrderList=this._customerOrderList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return T.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"Customer",e,r=>new T({id:r},nt,!0))}static teaqlCreate(t){return E.create(t,"Customer",e=>new T({id:e},nt,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._customerOrderList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._customerOrderList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("customer_order_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(T.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._customerOrderList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(T.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},customer_order_list:t.sourceMembers(this._customerOrderList)}));for(const r of this._customerOrderList){r.teaqlAttachRoot(this._root);const i=r.customer;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("customer")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updateCustomer(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),T.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"Customer",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._customerOrderList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("customer_order_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(T.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"Customer",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"Customer",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const w=a.customer;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("customer")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updateCustomer(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("customer_order_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"Customer",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const _=y.customer;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("customer")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updateCustomer(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("customer_order_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._customerOrderList.entries()){q.teaqlAttachRoot(this._root);const y=q.customer;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("customer")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updateCustomer(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("customer_order_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,platform:this.platform,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}const at=Symbol("managed entity construction");class Q{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("OrderItem",["id","customer_order","product_name","quantity","unit_price","version"],{id:"immutable_field",version:"immutable_field"});id;customerOrder;productName;quantity;unitPrice;version;constructor(t,e,r=!1){if(e!==at)throw new it;{const s=X(t?.quantity,"OrderItem","quantity");if(s)throw s}if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--Q.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];Object.assign(this,s),t.customerOrder&&typeof t.customerOrder=="object"&&(this.customerOrder=t.customerOrder instanceof b?t.customerOrder:b.fromRecord(t.customerOrder),this.markLoaded("customerOrder"))}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"OrderItem",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const r=E.hydrated(new Q(t,at));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){{const e=X(this.quantity,"OrderItem","quantity");if(e)throw e}return Object.fromEntries(Object.entries(this))}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return Q.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"OrderItem",e,r=>new Q({id:r},at,!0))}static teaqlCreate(t){return E.create(t,"OrderItem",e=>new Q({id:e},at,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());return E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),r}teaqlValidateLoadedIdentities(t=new Set){t.has(this)||(t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version))}teaqlDiscardRestoredGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(Q.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)))}teaqlNormalizeGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(Q.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{customer_order:"CustomerOrder"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()}})))}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),Q.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"OrderItem",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}return r}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(Q.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const l=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(c=>!this.isLoaded(c.member));if(l)throw new g([{ruleId:"invalid_type",entityType:"OrderItem",location:p.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"OrderItem",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f),f.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"OrderItem",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return l.scopeFor(this.teaqlEntityKey()),this;const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();return l.scopeFor(m),e.afterGraphRollback(()=>{for(const S of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,S)||delete this[S];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m),l.scopeFor(m),e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,customer_order:this.customerOrder,product_name:this.productName,quantity:this.quantity,unit_price:this.unitPrice,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateProductName(t){return this.productName=t,this.markLoaded("productName"),this._root.set(this.teaqlEntityKey(),"product_name",t),this}updateQuantity(t){return this.quantity=t,this.markLoaded("quantity"),this._root.set(this.teaqlEntityKey(),"quantity",t),this}updateUnitPrice(t){return t!=null&&(t=mt(t)),this.unitPrice=t,this.markLoaded("unitPrice"),this._root.set(this.teaqlEntityKey(),"unit_price",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomerOrder(t){return this.customerOrder=t?.id??t,this.markLoaded("customerOrder"),this._root.set(this.teaqlEntityKey(),"customer_order",this.customerOrder),this}}const ut=Symbol("managed entity construction");class b{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("CustomerOrder",["id","customer","status","order_number","order_date","total_amount","version"],{id:"immutable_field",version:"immutable_field"});id;customer;status;orderNumber;orderDate;totalAmount;version;constructor(t,e,r=!1){if(e!==ut)throw new it;if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--b.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderItemList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.orderItemList,Object.assign(this,s),t.customer&&typeof t.customer=="object"&&(this.customer=t.customer instanceof T?t.customer:T.fromRecord(t.customer),this.markLoaded("customer")),t.status&&typeof t.status=="object"&&(this.status=t.status instanceof P?t.status:P.fromRecord(t.status),this.markLoaded("status")),Array.isArray(t.orderItemList)){const o=t.orderItemList;this._orderItemList=new L(o.map(n=>n instanceof Q?n:Q.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("orderItemList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"CustomerOrder",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._orderItemList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new b(t,ut));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("orderItemList")&&(t.orderItemList=this._orderItemList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return b.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"CustomerOrder",e,r=>new b({id:r},ut,!0))}static teaqlCreate(t){return E.create(t,"CustomerOrder",e=>new b({id:e},ut,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._orderItemList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._orderItemList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("order_item_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(b.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._orderItemList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(b.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{customer:"Customer",status:"OrderStatus"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},order_item_list:t.sourceMembers(this._orderItemList)}));for(const r of this._orderItemList){r.teaqlAttachRoot(this._root);const i=r.customerOrder;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("customerOrder")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updateCustomerOrder(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),b.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"CustomerOrder",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._orderItemList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("order_item_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(b.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"CustomerOrder",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"CustomerOrder",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._orderItemList.entries()){a.teaqlAttachRoot(this._root);const w=a.customerOrder;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("customerOrder")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updateCustomerOrder(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("order_item_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"CustomerOrder",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._orderItemList.entries()){y.teaqlAttachRoot(this._root);const _=y.customerOrder;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("customerOrder")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updateCustomerOrder(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("order_item_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._orderItemList.entries()){q.teaqlAttachRoot(this._root);const y=q.customerOrder;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("customerOrder")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updateCustomerOrder(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("order_item_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,customer:this.customer,status:this.status,order_number:this.orderNumber,order_date:this.orderDate,total_amount:this.totalAmount,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateOrderNumber(t){return this.orderNumber=t,this.markLoaded("orderNumber"),this._root.set(this.teaqlEntityKey(),"order_number",t),this}updateOrderDate(t){return this.orderDate=t,this.markLoaded("orderDate"),this._root.set(this.teaqlEntityKey(),"order_date",t),this}updateTotalAmount(t){return t!=null&&(t=mt(t)),this.totalAmount=t,this.markLoaded("totalAmount"),this._root.set(this.teaqlEntityKey(),"total_amount",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomer(t){return this.customer=t?.id??t,this.markLoaded("customer"),this._root.set(this.teaqlEntityKey(),"customer",this.customer),this}updateStatus(t){return this.status=t?.id??t,this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToNew(){return this.status="1001",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToPaid(){return this.status="1002",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToCancelled(){return this.status="1003",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}orderItemList(){return this._orderItemList}}const dt=Symbol("managed entity construction");class P{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("OrderStatus",["platform","id","name","code","color","display_order","version"],{id:"immutable_field",version:"immutable_field"});platform;id;name;code;color;displayOrder;version;constructor(t,e,r=!1){if(e!==dt)throw new it;{const s=X(t?.displayOrder,"OrderStatus","display_order");if(s)throw s}if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--P.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.customerOrderList,Object.assign(this,s),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof C?t.platform:C.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const o=t.customerOrderList;this._customerOrderList=new L(o.map(n=>n instanceof b?n:b.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("customerOrderList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"OrderStatus",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._customerOrderList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new P(t,dt));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){{const e=X(this.displayOrder,"OrderStatus","display_order");if(e)throw e}const t=Object.fromEntries(Object.entries(this));return this.isLoaded("customerOrderList")&&(t.customerOrderList=this._customerOrderList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return P.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"OrderStatus",e,r=>new P({id:r},dt,!0))}static teaqlCreate(t){return E.create(t,"OrderStatus",e=>new P({id:e},dt,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._customerOrderList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._customerOrderList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("customer_order_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(P.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._customerOrderList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(P.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},customer_order_list:t.sourceMembers(this._customerOrderList)}));for(const r of this._customerOrderList){r.teaqlAttachRoot(this._root);const i=r.status;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("status")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updateStatus(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),P.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"OrderStatus",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._customerOrderList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("customer_order_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(P.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"OrderStatus",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"OrderStatus",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const w=a.status;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("status")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updateStatus(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("customer_order_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"OrderStatus",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const _=y.status;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("status")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updateStatus(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("customer_order_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._customerOrderList.entries()){q.teaqlAttachRoot(this._root);const y=q.status;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("status")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updateStatus(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("customer_order_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{platform:this.platform,id:this.id,name:this.name,code:this.code,color:this.color,display_order:this.displayOrder,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateCode(t){return this.code=t,this.markLoaded("code"),this._root.set(this.teaqlEntityKey(),"code",t),this}updateColor(t){return this.color=t,this.markLoaded("color"),this._root.set(this.teaqlEntityKey(),"color",t),this}updateDisplayOrder(t){return this.displayOrder=t,this.markLoaded("displayOrder"),this._root.set(this.teaqlEntityKey(),"display_order",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}const ht=Symbol("managed entity construction");class C{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("Platform",["id","name","version"],{id:"immutable_field",version:"immutable_field"});id;name;version;constructor(t,e,r=!1){if(e!==ht)throw new it;if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--C.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderStatusList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.orderStatusList,delete s.customerList,Object.assign(this,s),Array.isArray(t.orderStatusList)){const o=t.orderStatusList;this._orderStatusList=new L(o.map(n=>n instanceof P?n:P.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("orderStatusList")}if(Array.isArray(t.customerList)){const o=t.customerList;this._customerList=new L(o.map(n=>n instanceof T?n:T.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("customerList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._orderStatusList)r.teaqlAttachRoot(t,e);for(const r of this._customerList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new C(t,ht));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("orderStatusList")&&(t.orderStatusList=this._orderStatusList),this.isLoaded("customerList")&&(t.customerList=this._customerList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return C.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"Platform",e,r=>new C({id:r},ht,!0))}static teaqlCreate(t){return E.create(t,"Platform",e=>new C({id:e},ht,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._orderStatusList)r=i.teaqlValidateMutationOrigins(t)||r;for(const i of this._customerList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._orderStatusList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("order_status_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}for(const[e,r]of this._customerList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("customer_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(C.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._orderStatusList)r.teaqlDiscardRestoredGraph(t,e);for(const r of this._customerList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(C.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},order_status_list:t.sourceMembers(this._orderStatusList),customer_list:t.sourceMembers(this._customerList)}));for(const r of this._orderStatusList){r.teaqlAttachRoot(this._root);const i=r.platform;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("platform")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updatePlatform(this),r.teaqlNormalizeGraph(t,e)}for(const r of this._customerList){r.teaqlAttachRoot(this._root);const i=r.platform;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("platform")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updatePlatform(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),C.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"Platform",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._orderStatusList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("order_status_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}for(const[s,o]of this._customerList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("customer_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(C.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"Platform",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"Platform",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._orderStatusList.entries()){a.teaqlAttachRoot(this._root);const w=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("order_status_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}for(const[c,a]of this._customerList.entries()){a.teaqlAttachRoot(this._root);const w=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("customer_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"Platform",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._orderStatusList.entries()){y.teaqlAttachRoot(this._root);const _=y.platform;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("order_status_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}for(const[q,y]of this._customerList.entries()){y.teaqlAttachRoot(this._root);const _=y.platform;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("customer_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._orderStatusList.entries()){q.teaqlAttachRoot(this._root);const y=q.platform;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("order_status_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}for(const[I,q]of this._customerList.entries()){q.teaqlAttachRoot(this._root);const y=q.platform;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("customer_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}orderStatusList(){return this._orderStatusList}customerList(){return this._customerList}}const st=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({orderStatusList:"OrderStatus",customerList:"Customer"})}),OrderStatus:Object.freeze({fields:Object.freeze({platform:"integer",id:"integer",name:"string",code:"string",color:"string",display_order:"integer",displayOrder:"integer",version:"integer"}),queryFields:Object.freeze({platform:"platform",id:"id",name:"name",code:"code",color:"color",display_order:"displayOrder",displayOrder:"displayOrder",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),Customer:Object.freeze({fields:Object.freeze({id:"integer",platform:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",platform:"platform",name:"name",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),CustomerOrder:Object.freeze({fields:Object.freeze({id:"integer",customer:"integer",status:"integer",order_number:"string",orderNumber:"string",order_date:"date",orderDate:"date",total_amount:"decimal",totalAmount:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer:"customer",status:"status",order_number:"orderNumber",orderNumber:"orderNumber",order_date:"orderDate",orderDate:"orderDate",total_amount:"totalAmount",totalAmount:"totalAmount",version:"version"}),relations:Object.freeze({customer:"Customer",status:"OrderStatus",orderItemList:"OrderItem"})}),OrderItem:Object.freeze({fields:Object.freeze({id:"integer",customer_order:"integer",customerOrder:"integer",product_name:"string",productName:"string",quantity:"integer",unit_price:"decimal",unitPrice:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer_order:"customerOrder",customerOrder:"customerOrder",product_name:"productName",productName:"productName",quantity:"quantity",unit_price:"unitPrice",unitPrice:"unitPrice",version:"version"}),relations:Object.freeze({customer_order:"CustomerOrder",customerOrder:"CustomerOrder"})})});class qt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Platform"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new kt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectOrderStatusListWith(t){return this.query.relationQuery("orderStatusList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectOrderStatusListWith",relation:"orderStatusList"}),this}selectCustomerListWith(t){return this.query.relationQuery("customerList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectCustomerListWith",relation:"customerList"}),this}haveOrderStatuses(){return this.withOrderStatusListMatching({entityName:"OrderStatus",toQuery:()=>new O("OrderStatus")})}haveNoOrderStatuses(){return this.withoutOrderStatusListMatching({entityName:"OrderStatus",toQuery:()=>new O("OrderStatus")})}withOrderStatusListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutOrderStatusListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}haveCustomers(){return this.withCustomerListMatching({entityName:"Customer",toQuery:()=>new O("Customer")})}haveNoCustomers(){return this.withoutCustomerListMatching({entityName:"Customer",toQuery:()=>new O("Customer")})}withCustomerListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutCustomerListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countOrderStatuses(){return this.countOrderStatusesAs("countOrderStatuses")}countOrderStatusesAs(t){const e=new O("OrderStatus").filter({version:{$gte:1}});return this.countOrderStatusesWith(t,{entityName:"OrderStatus",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderStatusesAs",relation:"orderStatusList",alias:t},this}countOrderStatusesWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"relation-count",method:"countOrderStatusesWith",relation:"orderStatusList",alias:t}),this}minDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.minDisplayOrderOfOrderStatusesAs("minOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}minDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"minDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}maxDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.maxDisplayOrderOfOrderStatusesAs("maxOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}maxDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"maxDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sumDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.sumDisplayOrderOfOrderStatusesAs("sumOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}sumDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sumDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}avgDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.avgDisplayOrderOfOrderStatusesAs("avgOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}avgDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"avgDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}standardDeviationDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.standardDeviationDisplayOrderOfOrderStatusesAs("standardDeviationOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}standardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"standardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs("squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sampleVarianceDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.sampleVarianceDisplayOrderOfOrderStatusesAs("sampleVarianceOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}sampleVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sampleVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}samplePopulationVarianceDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs("samplePopulationVarianceOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}samplePopulationVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}countCustomers(){return this.countCustomersAs("countCustomers")}countCustomersAs(t){const e=new O("Customer").filter({version:{$gte:1}});return this.countCustomersWith(t,{entityName:"Customer",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomersAs",relation:"customerList",alias:t},this}countCustomersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerList",t,r,!0,{kind:"relation-count",method:"countCustomersWith",relation:"customerList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof C?n:C.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof C?a:C.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof C?n:C.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class kt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return C.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class wt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("OrderStatus"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"OrderStatus"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Rt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["platform","id","name","code","color","displayOrder","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectCode(){return this.query.select(["code"]),this}selectColor(){return this.query.select(["color"]),this}selectDisplayOrder(){return this.query.select(["displayOrder"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","status",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"status"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"status"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new O("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{entityName:"CustomerOrder",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withCodeContaining(t){return this.filters.push({code:{$contains:t}}),this}withCodeIs(t){return this.filters.push({code:{$eq:t}}),this}withCodeIsNot(t){return this.filters.push({code:{$ne:t}}),this}withCodeIn(...t){return this.filters.push({code:{$in:t}}),this}withCodeNotIn(...t){return this.filters.push({code:{$notIn:t}}),this}withCodeGreaterThan(t){return this.filters.push({code:{$gt:t}}),this}withCodeGreaterThanOrEqualTo(t){return this.filters.push({code:{$gte:t}}),this}withCodeLessThan(t){return this.filters.push({code:{$lt:t}}),this}withCodeLessThanOrEqualTo(t){return this.filters.push({code:{$lte:t}}),this}withCodeBetween(t,e){return this.filters.push({code:{$between:[t,e]}}),this}withCodeIsKnown(){return this.filters.push({code:{$isNull:!1}}),this}withCodeIsUnknown(){return this.filters.push({code:{$isNull:!0}}),this}withCodeNotContaining(t){return this.filters.push({code:{$notContains:t}}),this}withCodeStartingWith(t){return this.filters.push({code:{$startsWith:t}}),this}withCodeNotStartingWith(t){return this.filters.push({code:{$notStartsWith:t}}),this}withCodeEndingWith(t){return this.filters.push({code:{$endsWith:t}}),this}withCodeNotEndingWith(t){return this.filters.push({code:{$notEndsWith:t}}),this}withCodeSoundingLike(t){return this.filters.push({code:{$soundLike:t}}),this}withColorContaining(t){return this.filters.push({color:{$contains:t}}),this}withColorIs(t){return this.filters.push({color:{$eq:t}}),this}withColorIsNot(t){return this.filters.push({color:{$ne:t}}),this}withColorIn(...t){return this.filters.push({color:{$in:t}}),this}withColorNotIn(...t){return this.filters.push({color:{$notIn:t}}),this}withColorGreaterThan(t){return this.filters.push({color:{$gt:t}}),this}withColorGreaterThanOrEqualTo(t){return this.filters.push({color:{$gte:t}}),this}withColorLessThan(t){return this.filters.push({color:{$lt:t}}),this}withColorLessThanOrEqualTo(t){return this.filters.push({color:{$lte:t}}),this}withColorBetween(t,e){return this.filters.push({color:{$between:[t,e]}}),this}withColorIsKnown(){return this.filters.push({color:{$isNull:!1}}),this}withColorIsUnknown(){return this.filters.push({color:{$isNull:!0}}),this}withColorNotContaining(t){return this.filters.push({color:{$notContains:t}}),this}withColorStartingWith(t){return this.filters.push({color:{$startsWith:t}}),this}withColorNotStartingWith(t){return this.filters.push({color:{$notStartsWith:t}}),this}withColorEndingWith(t){return this.filters.push({color:{$endsWith:t}}),this}withColorNotEndingWith(t){return this.filters.push({color:{$notEndsWith:t}}),this}withColorSoundingLike(t){return this.filters.push({color:{$soundLike:t}}),this}withDisplayOrderIs(t){return this.filters.push({displayOrder:{$eq:t}}),this}withDisplayOrderIsNot(t){return this.filters.push({displayOrder:{$ne:t}}),this}withDisplayOrderIn(...t){return this.filters.push({displayOrder:{$in:t}}),this}withDisplayOrderNotIn(...t){return this.filters.push({displayOrder:{$notIn:t}}),this}withDisplayOrderGreaterThan(t){return this.filters.push({displayOrder:{$gt:t}}),this}withDisplayOrderGreaterThanOrEqualTo(t){return this.filters.push({displayOrder:{$gte:t}}),this}withDisplayOrderLessThan(t){return this.filters.push({displayOrder:{$lt:t}}),this}withDisplayOrderLessThanOrEqualTo(t){return this.filters.push({displayOrder:{$lte:t}}),this}withDisplayOrderBetween(t,e){return this.filters.push({displayOrder:{$between:[t,e]}}),this}withDisplayOrderIsKnown(){return this.filters.push({displayOrder:{$isNull:!1}}),this}withDisplayOrderIsUnknown(){return this.filters.push({displayOrder:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByCodeAscending(){return this.query.orderBy("code","asc"),this}orderByCodeDescending(){return this.query.orderBy("code","desc"),this}orderByColorAscending(){return this.query.orderBy("color","asc"),this}orderByColorDescending(){return this.query.orderBy("color","desc"),this}orderByDisplayOrderAscending(){return this.query.orderBy("displayOrder","asc"),this}orderByDisplayOrderDescending(){return this.query.orderBy("displayOrder","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minDisplayOrder(){return this.minDisplayOrderAs("minOfDisplayOrder")}minDisplayOrderAs(t){return this.query.aggregate("min","displayOrder",t),this}maxDisplayOrder(){return this.maxDisplayOrderAs("maxOfDisplayOrder")}maxDisplayOrderAs(t){return this.query.aggregate("max","displayOrder",t),this}sumDisplayOrder(){return this.sumDisplayOrderAs("sumOfDisplayOrder")}sumDisplayOrderAs(t){return this.query.aggregate("sum","displayOrder",t),this}avgDisplayOrder(){return this.avgDisplayOrderAs("avgOfDisplayOrder")}avgDisplayOrderAs(t){return this.query.aggregate("avg","displayOrder",t),this}standardDeviationDisplayOrder(){return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder")}standardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev","displayOrder",t),this}squareRootOfPopulationStandardDeviationDisplayOrder(){return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder")}squareRootOfPopulationStandardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev_pop","displayOrder",t),this}sampleVarianceDisplayOrder(){return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder")}sampleVarianceDisplayOrderAs(t){return this.query.aggregate("var_samp","displayOrder",t),this}samplePopulationVarianceDisplayOrder(){return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder")}samplePopulationVarianceDisplayOrderAs(t){return this.query.aggregate("var_pop","displayOrder",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByCode(){return this.query.groupBy("code"),this}groupByCodeAs(t){return this.query.groupBy("code",t),this}groupByColor(){return this.query.groupBy("color"),this}groupByColorAs(t){return this.query.groupBy("color",t),this}groupByDisplayOrder(){return this.query.groupBy("displayOrder"),this}groupByDisplayOrderAs(t){return this.query.groupBy("displayOrder",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof P?n:P.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof P?a:P.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof P?n:P.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Rt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return P.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class vt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("Customer"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Customer"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Qt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","platform","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","customer",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customer"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customer"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new O("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{entityName:"CustomerOrder",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof T?n:T.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof T?a:T.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof T?n:T.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Qt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return T.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class _t{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("CustomerOrder"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"CustomerOrder"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Bt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customer","status","orderNumber","orderDate","totalAmount","version"]),this}selectId(){return this.query.select(["id"]),this}selectOrderNumber(){return this.query.select(["orderNumber"]),this}selectOrderDate(){return this.query.select(["orderDate"]),this}selectTotalAmount(){return this.query.select(["totalAmount"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerWith(t){return this.query.select(["customer"]),this.query.relationQuery("customer",t.toQuery(),"customer","id",!1,{kind:"relation-select",method:"selectCustomerWith",relation:"customer"}),this}selectStatusWith(t){return this.query.select(["status"]),this.query.relationQuery("status",t.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this}withCustomerMatching(t){return this.filters.push({customer:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerMatching(t){return this.filters.push({customer:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withStatusMatching(t){return this.filters.push({status:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutStatusMatching(t){return this.filters.push({status:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectOrderItemListWith(t){return this.query.relationQuery("orderItemList",t.toQuery(),"id","customerOrder",!0,{kind:"relation-select",method:"selectOrderItemListWith",relation:"orderItemList"}),this}haveOrderItems(){return this.withOrderItemListMatching({entityName:"OrderItem",toQuery:()=>new O("OrderItem")})}haveNoOrderItems(){return this.withoutOrderItemListMatching({entityName:"OrderItem",toQuery:()=>new O("OrderItem")})}withOrderItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}withoutOrderItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}countOrderItems(){return this.countOrderItemsAs("countOrderItems")}countOrderItemsAs(t){const e=new O("OrderItem").filter({version:{$gte:1}});return this.countOrderItemsWith(t,{entityName:"OrderItem",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderItemsAs",relation:"orderItemList",alias:t},this}countOrderItemsWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"relation-count",method:"countOrderItemsWith",relation:"orderItemList",alias:t}),this}minQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.minQuantityOfOrderItemsAs("minOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}minQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.maxQuantityOfOrderItemsAs("maxOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}maxQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sumQuantityOfOrderItemsAs("sumOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sumQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.avgQuantityOfOrderItemsAs("avgOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}avgQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.standardDeviationQuantityOfOrderItemsAs("standardDeviationOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}standardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceQuantityOfOrderItemsAs("sampleVarianceOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sampleVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceQuantityOfOrderItemsAs("samplePopulationVarianceOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}samplePopulationVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}minUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.minUnitPriceOfOrderItemsAs("minOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}minUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.maxUnitPriceOfOrderItemsAs("maxOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}maxUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sumUnitPriceOfOrderItemsAs("sumOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sumUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.avgUnitPriceOfOrderItemsAs("avgOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}avgUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.standardDeviationUnitPriceOfOrderItemsAs("standardDeviationOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}standardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceUnitPriceOfOrderItemsAs("sampleVarianceOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sampleVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceUnitPriceOfOrderItemsAs("samplePopulationVarianceOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}samplePopulationVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomer(t){return this.filters.push({customer:{$eq:t}}),this}filterByCustomerIn(...t){return this.filters.push({customer:{$in:t}}),this}withCustomerIsKnown(){return this.filters.push({customer:{$isNull:!1}}),this}withCustomerIsUnknown(){return this.filters.push({customer:{$isNull:!0}}),this}filterByStatus(t){return this.filters.push({status:{$eq:t}}),this}filterByStatusIn(...t){return this.filters.push({status:{$in:t}}),this}withStatusIsKnown(){return this.filters.push({status:{$isNull:!1}}),this}withStatusIsUnknown(){return this.filters.push({status:{$isNull:!0}}),this}withStatusIsNew(){return this.filters.push({status:{$eq:"1001"}}),this}withStatusIsPaid(){return this.filters.push({status:{$eq:"1002"}}),this}withStatusIsCancelled(){return this.filters.push({status:{$eq:"1003"}}),this}withOrderNumberContaining(t){return this.filters.push({orderNumber:{$contains:t}}),this}withOrderNumberIs(t){return this.filters.push({orderNumber:{$eq:t}}),this}withOrderNumberIsNot(t){return this.filters.push({orderNumber:{$ne:t}}),this}withOrderNumberIn(...t){return this.filters.push({orderNumber:{$in:t}}),this}withOrderNumberNotIn(...t){return this.filters.push({orderNumber:{$notIn:t}}),this}withOrderNumberGreaterThan(t){return this.filters.push({orderNumber:{$gt:t}}),this}withOrderNumberGreaterThanOrEqualTo(t){return this.filters.push({orderNumber:{$gte:t}}),this}withOrderNumberLessThan(t){return this.filters.push({orderNumber:{$lt:t}}),this}withOrderNumberLessThanOrEqualTo(t){return this.filters.push({orderNumber:{$lte:t}}),this}withOrderNumberBetween(t,e){return this.filters.push({orderNumber:{$between:[t,e]}}),this}withOrderNumberIsKnown(){return this.filters.push({orderNumber:{$isNull:!1}}),this}withOrderNumberIsUnknown(){return this.filters.push({orderNumber:{$isNull:!0}}),this}withOrderNumberNotContaining(t){return this.filters.push({orderNumber:{$notContains:t}}),this}withOrderNumberStartingWith(t){return this.filters.push({orderNumber:{$startsWith:t}}),this}withOrderNumberNotStartingWith(t){return this.filters.push({orderNumber:{$notStartsWith:t}}),this}withOrderNumberEndingWith(t){return this.filters.push({orderNumber:{$endsWith:t}}),this}withOrderNumberNotEndingWith(t){return this.filters.push({orderNumber:{$notEndsWith:t}}),this}withOrderNumberSoundingLike(t){return this.filters.push({orderNumber:{$soundLike:t}}),this}withOrderDateIs(t){return this.filters.push({orderDate:{$eq:t}}),this}withOrderDateIsNot(t){return this.filters.push({orderDate:{$ne:t}}),this}withOrderDateIn(...t){return this.filters.push({orderDate:{$in:t}}),this}withOrderDateNotIn(...t){return this.filters.push({orderDate:{$notIn:t}}),this}withOrderDateGreaterThan(t){return this.filters.push({orderDate:{$gt:t}}),this}withOrderDateGreaterThanOrEqualTo(t){return this.filters.push({orderDate:{$gte:t}}),this}withOrderDateLessThan(t){return this.filters.push({orderDate:{$lt:t}}),this}withOrderDateLessThanOrEqualTo(t){return this.filters.push({orderDate:{$lte:t}}),this}withOrderDateBetween(t,e){return this.filters.push({orderDate:{$between:[t,e]}}),this}withOrderDateIsKnown(){return this.filters.push({orderDate:{$isNull:!1}}),this}withOrderDateIsUnknown(){return this.filters.push({orderDate:{$isNull:!0}}),this}withTotalAmountIs(t){return this.filters.push({totalAmount:{$eq:t}}),this}withTotalAmountIsNot(t){return this.filters.push({totalAmount:{$ne:t}}),this}withTotalAmountIn(...t){return this.filters.push({totalAmount:{$in:t}}),this}withTotalAmountNotIn(...t){return this.filters.push({totalAmount:{$notIn:t}}),this}withTotalAmountGreaterThan(t){return this.filters.push({totalAmount:{$gt:t}}),this}withTotalAmountGreaterThanOrEqualTo(t){return this.filters.push({totalAmount:{$gte:t}}),this}withTotalAmountLessThan(t){return this.filters.push({totalAmount:{$lt:t}}),this}withTotalAmountLessThanOrEqualTo(t){return this.filters.push({totalAmount:{$lte:t}}),this}withTotalAmountBetween(t,e){return this.filters.push({totalAmount:{$between:[t,e]}}),this}withTotalAmountIsKnown(){return this.filters.push({totalAmount:{$isNull:!1}}),this}withTotalAmountIsUnknown(){return this.filters.push({totalAmount:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByOrderNumberAscending(){return this.query.orderBy("orderNumber","asc"),this}orderByOrderNumberDescending(){return this.query.orderBy("orderNumber","desc"),this}orderByOrderDateAscending(){return this.query.orderBy("orderDate","asc"),this}orderByOrderDateDescending(){return this.query.orderBy("orderDate","desc"),this}orderByTotalAmountAscending(){return this.query.orderBy("totalAmount","asc"),this}orderByTotalAmountDescending(){return this.query.orderBy("totalAmount","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minTotalAmount(){return this.minTotalAmountAs("minOfTotalAmount")}minTotalAmountAs(t){return this.query.aggregate("min","totalAmount",t),this}maxTotalAmount(){return this.maxTotalAmountAs("maxOfTotalAmount")}maxTotalAmountAs(t){return this.query.aggregate("max","totalAmount",t),this}sumTotalAmount(){return this.sumTotalAmountAs("sumOfTotalAmount")}sumTotalAmountAs(t){return this.query.aggregate("sum","totalAmount",t),this}avgTotalAmount(){return this.avgTotalAmountAs("avgOfTotalAmount")}avgTotalAmountAs(t){return this.query.aggregate("avg","totalAmount",t),this}standardDeviationTotalAmount(){return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount")}standardDeviationTotalAmountAs(t){return this.query.aggregate("stddev","totalAmount",t),this}squareRootOfPopulationStandardDeviationTotalAmount(){return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount")}squareRootOfPopulationStandardDeviationTotalAmountAs(t){return this.query.aggregate("stddev_pop","totalAmount",t),this}sampleVarianceTotalAmount(){return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount")}sampleVarianceTotalAmountAs(t){return this.query.aggregate("var_samp","totalAmount",t),this}samplePopulationVarianceTotalAmount(){return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount")}samplePopulationVarianceTotalAmountAs(t){return this.query.aggregate("var_pop","totalAmount",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByCustomer(){return this.query.groupBy("customer"),this}groupByCustomerAs(t){return this.query.groupBy("customer",t),this}groupByStatus(){return this.query.groupBy("status"),this}groupByStatusAs(t){return this.query.groupBy("status",t),this}groupByOrderNumber(){return this.query.groupBy("orderNumber"),this}groupByOrderNumberAs(t){return this.query.groupBy("orderNumber",t),this}groupByOrderDate(){return this.query.groupBy("orderDate"),this}groupByOrderDateAs(t){return this.query.groupBy("orderDate",t),this}groupByTotalAmount(){return this.query.groupBy("totalAmount"),this}groupByTotalAmountAs(t){return this.query.groupBy("totalAmount",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByCustomerAs(t,e,r=!0){return this.query.facetBy(t,"customer",e,r,{kind:"facet",method:"facetByCustomerAs",relation:"customer",alias:t}),this}facetByStatusAs(t,e,r=!0){return this.query.facetBy(t,"status",e,r,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof b?n:b.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof b?a:b.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof b?n:b.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Bt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return b.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class It{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("OrderItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"OrderItem"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Ft(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customerOrder","productName","quantity","unitPrice","version"]),this}selectId(){return this.query.select(["id"]),this}selectProductName(){return this.query.select(["productName"]),this}selectQuantity(){return this.query.select(["quantity"]),this}selectUnitPrice(){return this.query.select(["unitPrice"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerOrderWith(t){return this.query.select(["customerOrder"]),this.query.relationQuery("customerOrder",t.toQuery(),"customerOrder","id",!1,{kind:"relation-select",method:"selectCustomerOrderWith",relation:"customerOrder"}),this}withCustomerOrderMatching(t){return this.filters.push({customerOrder:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerOrderMatching(t){return this.filters.push({customerOrder:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomerOrder(t){return this.filters.push({customerOrder:{$eq:t}}),this}filterByCustomerOrderIn(...t){return this.filters.push({customerOrder:{$in:t}}),this}withCustomerOrderIsKnown(){return this.filters.push({customerOrder:{$isNull:!1}}),this}withCustomerOrderIsUnknown(){return this.filters.push({customerOrder:{$isNull:!0}}),this}withProductNameContaining(t){return this.filters.push({productName:{$contains:t}}),this}withProductNameIs(t){return this.filters.push({productName:{$eq:t}}),this}withProductNameIsNot(t){return this.filters.push({productName:{$ne:t}}),this}withProductNameIn(...t){return this.filters.push({productName:{$in:t}}),this}withProductNameNotIn(...t){return this.filters.push({productName:{$notIn:t}}),this}withProductNameGreaterThan(t){return this.filters.push({productName:{$gt:t}}),this}withProductNameGreaterThanOrEqualTo(t){return this.filters.push({productName:{$gte:t}}),this}withProductNameLessThan(t){return this.filters.push({productName:{$lt:t}}),this}withProductNameLessThanOrEqualTo(t){return this.filters.push({productName:{$lte:t}}),this}withProductNameBetween(t,e){return this.filters.push({productName:{$between:[t,e]}}),this}withProductNameIsKnown(){return this.filters.push({productName:{$isNull:!1}}),this}withProductNameIsUnknown(){return this.filters.push({productName:{$isNull:!0}}),this}withProductNameNotContaining(t){return this.filters.push({productName:{$notContains:t}}),this}withProductNameStartingWith(t){return this.filters.push({productName:{$startsWith:t}}),this}withProductNameNotStartingWith(t){return this.filters.push({productName:{$notStartsWith:t}}),this}withProductNameEndingWith(t){return this.filters.push({productName:{$endsWith:t}}),this}withProductNameNotEndingWith(t){return this.filters.push({productName:{$notEndsWith:t}}),this}withProductNameSoundingLike(t){return this.filters.push({productName:{$soundLike:t}}),this}withQuantityIs(t){return this.filters.push({quantity:{$eq:t}}),this}withQuantityIsNot(t){return this.filters.push({quantity:{$ne:t}}),this}withQuantityIn(...t){return this.filters.push({quantity:{$in:t}}),this}withQuantityNotIn(...t){return this.filters.push({quantity:{$notIn:t}}),this}withQuantityGreaterThan(t){return this.filters.push({quantity:{$gt:t}}),this}withQuantityGreaterThanOrEqualTo(t){return this.filters.push({quantity:{$gte:t}}),this}withQuantityLessThan(t){return this.filters.push({quantity:{$lt:t}}),this}withQuantityLessThanOrEqualTo(t){return this.filters.push({quantity:{$lte:t}}),this}withQuantityBetween(t,e){return this.filters.push({quantity:{$between:[t,e]}}),this}withQuantityIsKnown(){return this.filters.push({quantity:{$isNull:!1}}),this}withQuantityIsUnknown(){return this.filters.push({quantity:{$isNull:!0}}),this}withUnitPriceIs(t){return this.filters.push({unitPrice:{$eq:t}}),this}withUnitPriceIsNot(t){return this.filters.push({unitPrice:{$ne:t}}),this}withUnitPriceIn(...t){return this.filters.push({unitPrice:{$in:t}}),this}withUnitPriceNotIn(...t){return this.filters.push({unitPrice:{$notIn:t}}),this}withUnitPriceGreaterThan(t){return this.filters.push({unitPrice:{$gt:t}}),this}withUnitPriceGreaterThanOrEqualTo(t){return this.filters.push({unitPrice:{$gte:t}}),this}withUnitPriceLessThan(t){return this.filters.push({unitPrice:{$lt:t}}),this}withUnitPriceLessThanOrEqualTo(t){return this.filters.push({unitPrice:{$lte:t}}),this}withUnitPriceBetween(t,e){return this.filters.push({unitPrice:{$between:[t,e]}}),this}withUnitPriceIsKnown(){return this.filters.push({unitPrice:{$isNull:!1}}),this}withUnitPriceIsUnknown(){return this.filters.push({unitPrice:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByProductNameAscending(){return this.query.orderBy("productName","asc"),this}orderByProductNameDescending(){return this.query.orderBy("productName","desc"),this}orderByQuantityAscending(){return this.query.orderBy("quantity","asc"),this}orderByQuantityDescending(){return this.query.orderBy("quantity","desc"),this}orderByUnitPriceAscending(){return this.query.orderBy("unitPrice","asc"),this}orderByUnitPriceDescending(){return this.query.orderBy("unitPrice","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minQuantity(){return this.minQuantityAs("minOfQuantity")}minQuantityAs(t){return this.query.aggregate("min","quantity",t),this}maxQuantity(){return this.maxQuantityAs("maxOfQuantity")}maxQuantityAs(t){return this.query.aggregate("max","quantity",t),this}sumQuantity(){return this.sumQuantityAs("sumOfQuantity")}sumQuantityAs(t){return this.query.aggregate("sum","quantity",t),this}avgQuantity(){return this.avgQuantityAs("avgOfQuantity")}avgQuantityAs(t){return this.query.aggregate("avg","quantity",t),this}standardDeviationQuantity(){return this.standardDeviationQuantityAs("standardDeviationOfQuantity")}standardDeviationQuantityAs(t){return this.query.aggregate("stddev","quantity",t),this}squareRootOfPopulationStandardDeviationQuantity(){return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity")}squareRootOfPopulationStandardDeviationQuantityAs(t){return this.query.aggregate("stddev_pop","quantity",t),this}sampleVarianceQuantity(){return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity")}sampleVarianceQuantityAs(t){return this.query.aggregate("var_samp","quantity",t),this}samplePopulationVarianceQuantity(){return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity")}samplePopulationVarianceQuantityAs(t){return this.query.aggregate("var_pop","quantity",t),this}minUnitPrice(){return this.minUnitPriceAs("minOfUnitPrice")}minUnitPriceAs(t){return this.query.aggregate("min","unitPrice",t),this}maxUnitPrice(){return this.maxUnitPriceAs("maxOfUnitPrice")}maxUnitPriceAs(t){return this.query.aggregate("max","unitPrice",t),this}sumUnitPrice(){return this.sumUnitPriceAs("sumOfUnitPrice")}sumUnitPriceAs(t){return this.query.aggregate("sum","unitPrice",t),this}avgUnitPrice(){return this.avgUnitPriceAs("avgOfUnitPrice")}avgUnitPriceAs(t){return this.query.aggregate("avg","unitPrice",t),this}standardDeviationUnitPrice(){return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice")}standardDeviationUnitPriceAs(t){return this.query.aggregate("stddev","unitPrice",t),this}squareRootOfPopulationStandardDeviationUnitPrice(){return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice")}squareRootOfPopulationStandardDeviationUnitPriceAs(t){return this.query.aggregate("stddev_pop","unitPrice",t),this}sampleVarianceUnitPrice(){return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice")}sampleVarianceUnitPriceAs(t){return this.query.aggregate("var_samp","unitPrice",t),this}samplePopulationVarianceUnitPrice(){return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice")}samplePopulationVarianceUnitPriceAs(t){return this.query.aggregate("var_pop","unitPrice",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByCustomerOrder(){return this.query.groupBy("customerOrder"),this}groupByCustomerOrderAs(t){return this.query.groupBy("customerOrder",t),this}groupByProductName(){return this.query.groupBy("productName"),this}groupByProductNameAs(t){return this.query.groupBy("productName",t),this}groupByQuantity(){return this.query.groupBy("quantity"),this}groupByQuantityAs(t){return this.query.groupBy("quantity",t),this}groupByUnitPrice(){return this.query.groupBy("unitPrice"),this}groupByUnitPriceAs(t){return this.query.groupBy("unitPrice",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByCustomerOrderAs(t,e,r=!0){return this.query.facetBy(t,"customerOrder",e,r,{kind:"facet",method:"facetByCustomerOrderAs",relation:"customerOrder",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof Q?n:Q.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof Q?a:Q.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof Q?n:Q.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Ft{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return Q.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class F{static platforms(){return new qt(!1)}static platformsWithMinimalFields(){return new qt(!0)}static orderStatuses(){return new wt(!1)}static orderStatusesWithMinimalFields(){return new wt(!0)}static customers(){return new vt(!1)}static customersWithMinimalFields(){return new vt(!0)}static customerOrders(){return new _t(!1)}static customerOrdersWithMinimalFields(){return new _t(!0)}static orderItems(){return new It(!1)}static orderItemsWithMinimalFields(){return new It(!0)}}class u{constructor(t,e=!0,r,i){this.value=t,this.present=e,this.notLoaded=r,this.invalidValue=i}value;present;notLoaded;invalidValue;static missing(){return new u(void 0,!1)}static notLoaded(t){return new u(void 0,!1,t)}static invalid(t){return new u(void 0,!1,void 0,t)}eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");if(this.invalidValue)throw this.invalidValue;return this.present?this.value:void 0}isPresent(){if(this.notLoaded)throw this.notLoaded.terminal("isPresent()");if(this.invalidValue)throw this.invalidValue;return this.present}orElse(t){if(this.notLoaded)throw this.notLoaded.terminal("orElse()");if(this.invalidValue)throw this.invalidValue;const e=this.value;return this.present&&e!=null?e:t}}class K{constructor(t,e="Platform(null)",r=D.root("E.platform()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}name(){const t=this.path.member("name","name");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("name")?new u(this.value.name):u.notLoaded(new v(t.markMissing(),"name")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}orderStatusList(){const t=this.path.member("order_status_list","orderStatusList");return this.notLoaded?new j([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderStatusList")?new j(this.value.orderStatusList(),this.root,t):new j([],this.root,t,!1,new v(t.markMissing(),"order_status_list")):j.missing(this.root,t)}customerList(){const t=this.path.member("customer_list","customerList");return this.notLoaded?new z([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("customerList")?new z(this.value.customerList(),this.root,t):new z([],this.root,t,!1,new v(t.markMissing(),"customer_list")):z.missing(this.root,t)}}class U{constructor(t,e="OrderStatus(null)",r=D.root("E.orderStatus()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}name(){const t=this.path.member("name","name");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("name")?new u(this.value.name):u.notLoaded(new v(t.markMissing(),"name")):u.missing()}code(){const t=this.path.member("code","code");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("code")?new u(this.value.code):u.notLoaded(new v(t.markMissing(),"code")):u.missing()}color(){const t=this.path.member("color","color");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("color")?new u(this.value.color):u.notLoaded(new v(t.markMissing(),"color")):u.missing()}displayOrder(){const t=this.path.member("display_order","displayOrder");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("displayOrder"))return u.notLoaded(new v(t.markMissing(),"display_order"));const e=X(this.value.displayOrder,"OrderStatus","display_order");return e?u.invalid(e):new u(this.value.displayOrder)}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}platformId(){const t=this.path.member("platform","platformId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("platform"))return u.notLoaded(new v(t.markMissing(),"platform"));const e=this.value.platform;return new u(e instanceof C?e.id:e)}platform(){const t=this.path.member("platform","platform");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const e=this.value.platform;if(e!=null&&!(e instanceof C))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const r=e instanceof C?e:void 0;return new K(r,this.root,t)}customerOrderList(){const t=this.path.member("customer_order_list","customerOrderList");return this.notLoaded?new x([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("customerOrderList")?new x(this.value.customerOrderList(),this.root,t):new x([],this.root,t,!1,new v(t.markMissing(),"customer_order_list")):x.missing(this.root,t)}}class W{constructor(t,e="Customer(null)",r=D.root("E.customer()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}name(){const t=this.path.member("name","name");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("name")?new u(this.value.name):u.notLoaded(new v(t.markMissing(),"name")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}platformId(){const t=this.path.member("platform","platformId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("platform"))return u.notLoaded(new v(t.markMissing(),"platform"));const e=this.value.platform;return new u(e instanceof C?e.id:e)}platform(){const t=this.path.member("platform","platform");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const e=this.value.platform;if(e!=null&&!(e instanceof C))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const r=e instanceof C?e:void 0;return new K(r,this.root,t)}customerOrderList(){const t=this.path.member("customer_order_list","customerOrderList");return this.notLoaded?new x([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("customerOrderList")?new x(this.value.customerOrderList(),this.root,t):new x([],this.root,t,!1,new v(t.markMissing(),"customer_order_list")):x.missing(this.root,t)}}class G{constructor(t,e="CustomerOrder(null)",r=D.root("E.customerOrder()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}orderNumber(){const t=this.path.member("order_number","orderNumber");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderNumber")?new u(this.value.orderNumber):u.notLoaded(new v(t.markMissing(),"order_number")):u.missing()}orderDate(){const t=this.path.member("order_date","orderDate");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderDate")?new u(this.value.orderDate):u.notLoaded(new v(t.markMissing(),"order_date")):u.missing()}totalAmount(){const t=this.path.member("total_amount","totalAmount");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("totalAmount")?new u(this.value.totalAmount):u.notLoaded(new v(t.markMissing(),"total_amount")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}customerId(){const t=this.path.member("customer","customerId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("customer"))return u.notLoaded(new v(t.markMissing(),"customer"));const e=this.value.customer;return new u(e instanceof T?e.id:e)}statusId(){const t=this.path.member("status","statusId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("status"))return u.notLoaded(new v(t.markMissing(),"status"));const e=this.value.status;return new u(e instanceof P?e.id:e)}customer(){const t=this.path.member("customer","customer");if(this.notLoaded)return new W(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new W(void 0,this.root,t);if(!this.value.isLoaded("customer"))return new W(void 0,this.root,t,new v(t.markMissing(),"customer"));const e=this.value.customer;if(e!=null&&!(e instanceof T))return new W(void 0,this.root,t,new v(t.markMissing(),"customer"));const r=e instanceof T?e:void 0;return new W(r,this.root,t)}status(){const t=this.path.member("status","status");if(this.notLoaded)return new U(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new U(void 0,this.root,t);if(!this.value.isLoaded("status"))return new U(void 0,this.root,t,new v(t.markMissing(),"status"));const e=this.value.status;if(e!=null&&!(e instanceof P))return new U(void 0,this.root,t,new v(t.markMissing(),"status"));const r=e instanceof P?e:void 0;return new U(r,this.root,t)}orderItemList(){const t=this.path.member("order_item_list","orderItemList");return this.notLoaded?new J([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderItemList")?new J(this.value.orderItemList(),this.root,t):new J([],this.root,t,!1,new v(t.markMissing(),"order_item_list")):J.missing(this.root,t)}}class lt{constructor(t,e="OrderItem(null)",r=D.root("E.orderItem()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}productName(){const t=this.path.member("product_name","productName");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("productName")?new u(this.value.productName):u.notLoaded(new v(t.markMissing(),"product_name")):u.missing()}quantity(){const t=this.path.member("quantity","quantity");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("quantity"))return u.notLoaded(new v(t.markMissing(),"quantity"));const e=X(this.value.quantity,"OrderItem","quantity");return e?u.invalid(e):new u(this.value.quantity)}unitPrice(){const t=this.path.member("unit_price","unitPrice");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("unitPrice")?new u(this.value.unitPrice):u.notLoaded(new v(t.markMissing(),"unit_price")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}customerOrderId(){const t=this.path.member("customer_order","customerOrderId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("customerOrder"))return u.notLoaded(new v(t.markMissing(),"customer_order"));const e=this.value.customerOrder;return new u(e instanceof b?e.id:e)}customerOrder(){const t=this.path.member("customer_order","customerOrder");if(this.notLoaded)return new G(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new G(void 0,this.root,t);if(!this.value.isLoaded("customerOrder"))return new G(void 0,this.root,t,new v(t.markMissing(),"customer_order"));const e=this.value.customerOrder;if(e!=null&&!(e instanceof b))return new G(void 0,this.root,t,new v(t.markMissing(),"customer_order"));const r=e instanceof b?e:void 0;return new G(r,this.root,t)}}class j{constructor(t,e="OrderStatus(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new j([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new U(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new U(void 0,this.root,r):new U(this.items[t],this.root,r)}}class z{constructor(t,e="Customer(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new z([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new W(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new W(void 0,this.root,r):new W(this.items[t],this.root,r)}}class x{constructor(t,e="CustomerOrder(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new x([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new G(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new G(void 0,this.root,r):new G(this.items[t],this.root,r)}}class J{constructor(t,e="OrderItem(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new J([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new lt(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new lt(void 0,this.root,r):new lt(this.items[t],this.root,r)}}class ft{static platform(t){return new K(t,"Platform",D.root("E.platform()","camelCase"))}static orderStatus(t){return new U(t,"OrderStatus",D.root("E.orderStatus()","camelCase"))}static customer(t){return new W(t,"Customer",D.root("E.customer()","camelCase"))}static customerOrder(t){return new G(t,"CustomerOrder",D.root("E.customerOrder()","camelCase"))}static orderItem(t){return new lt(t,"OrderItem",D.root("E.orderItem()","camelCase"))}}const Lt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{orderStatusList:{targetEntity:"OrderStatus",localKey:"id",foreignKey:"platform",many:!0},customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platform",many:!0}}},OrderStatus:{table:"order_status_data",auditMaskFields:[],columns:{platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},code:{columnName:"code",modelName:"code",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},color:{columnName:"color",modelName:"color",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},displayOrder:{columnName:"display_order",modelName:"display_order",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1,integer32:!0},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},Customer:{table:"customer_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customer",many:!0}}},CustomerOrder:{table:"customer_order_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customer:{columnName:"customer",modelName:"customer",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},status:{columnName:"status",modelName:"status",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},orderNumber:{columnName:"order_number",modelName:"order_number",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},orderDate:{columnName:"order_date",modelName:"order_date",logPolicy:"plain",logicalType:"date",decode:"date",nullable:!1},totalAmount:{columnName:"total_amount",modelName:"total_amount",logPolicy:"plain",logicalType:"decimal",decode:"decimal",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customer:{targetEntity:"Customer",localKey:"customer",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},orderItemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"customerOrder",many:!0}}},OrderItem:{table:"order_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customerOrder:{columnName:"customer_order",modelName:"customer_order",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},productName:{columnName:"product_name",modelName:"product_name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},quantity:{columnName:"quantity",modelName:"quantity",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1,integer32:!0},unitPrice:{columnName:"unit_price",modelName:"unit_price",logPolicy:"plain",logicalType:"decimal",decode:"decimal",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customerOrder:{targetEntity:"CustomerOrder",localKey:"customerOrder",foreignKey:"id",many:!1}}}};async function Vt(h){let t=(await F.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];t||(t=C.teaqlBootstrapNew(h,"1"),t.updateName("Commerce Test Platform"),await t.auditAs("create generated Domain Root Platform").save(h)),h.withActiveRoot({entity:"Platform",id:t.id});let e=(await F.orderStatuses().withIdIs("1001").comment("what: locate generated constant OrderStatus(1001)").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];if(!e)e=P.teaqlBootstrapNew(h,"1001"),e.updatePlatform(t),e.updateName("New"),e.updateCode("NEW"),e.updateColor("#94A3B8"),e.updateDisplayOrder(1),await e.auditAs("create model constant OrderStatus(1001)").save(h);else{let s=!1;String(e.platform?.id??e.platform)!==String(t.id)&&(e.updatePlatform(t),s=!0),e.name!=="New"&&(e.updateName("New"),s=!0),e.code!=="NEW"&&(e.updateCode("NEW"),s=!0),e.color!=="#94A3B8"&&(e.updateColor("#94A3B8"),s=!0),e.displayOrder!==1&&(e.updateDisplayOrder(1),s=!0),s&&await e.auditAs("reconcile model constant OrderStatus(1001)").save(h)}let r=(await F.orderStatuses().withIdIs("1002").comment("what: locate generated constant OrderStatus(1002)").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];if(!r)r=P.teaqlBootstrapNew(h,"1002"),r.updatePlatform(t),r.updateName("Paid"),r.updateCode("PAID"),r.updateColor("#22C55E"),r.updateDisplayOrder(2),await r.auditAs("create model constant OrderStatus(1002)").save(h);else{let s=!1;String(r.platform?.id??r.platform)!==String(t.id)&&(r.updatePlatform(t),s=!0),r.name!=="Paid"&&(r.updateName("Paid"),s=!0),r.code!=="PAID"&&(r.updateCode("PAID"),s=!0),r.color!=="#22C55E"&&(r.updateColor("#22C55E"),s=!0),r.displayOrder!==2&&(r.updateDisplayOrder(2),s=!0),s&&await r.auditAs("reconcile model constant OrderStatus(1002)").save(h)}let i=(await F.orderStatuses().withIdIs("1003").comment("what: locate generated constant OrderStatus(1003)").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];if(!i)i=P.teaqlBootstrapNew(h,"1003"),i.updatePlatform(t),i.updateName("Cancelled"),i.updateCode("CANCELLED"),i.updateColor("#EF4444"),i.updateDisplayOrder(3),await i.auditAs("create model constant OrderStatus(1003)").save(h);else{let s=!1;String(i.platform?.id??i.platform)!==String(t.id)&&(i.updatePlatform(t),s=!0),i.name!=="Cancelled"&&(i.updateName("Cancelled"),s=!0),i.code!=="CANCELLED"&&(i.updateCode("CANCELLED"),s=!0),i.color!=="#EF4444"&&(i.updateColor("#EF4444"),s=!0),i.displayOrder!==3&&(i.updateDisplayOrder(3),s=!0),s&&await i.auditAs("reconcile model constant OrderStatus(1003)").save(h)}}const Kt=new Nt(Lt,{Platform:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:p.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:p.property("name"),inputValue:t.payload.name,systemValue:100})}},OrderStatus:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:p.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:p.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:p.property("name"),inputValue:t.payload.name,systemValue:100}),(t.action==="Create"&&t.payload.code===void 0||t.payload.code===null)&&e.push({ruleId:"required",location:p.property("code")}),t.payload.code!=null&&[...String(t.payload.code)].length>100&&e.push({ruleId:"max_length",location:p.property("code"),inputValue:t.payload.code,systemValue:100}),(t.action==="Create"&&t.payload.color===void 0||t.payload.color===null)&&e.push({ruleId:"required",location:p.property("color")}),t.payload.color!=null&&[...String(t.payload.color)].length>100&&e.push({ruleId:"max_length",location:p.property("color"),inputValue:t.payload.color,systemValue:100}),(t.action==="Create"&&t.payload.display_order===void 0||t.payload.display_order===null)&&e.push({ruleId:"required",location:p.property("display_order")})}},Customer:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:p.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:p.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:p.property("name"),inputValue:t.payload.name,systemValue:100})}},CustomerOrder:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.customer===void 0||t.payload.customer===null)&&e.push({ruleId:"required",location:p.property("customer")}),(t.action==="Create"&&t.payload.status===void 0||t.payload.status===null)&&e.push({ruleId:"required",location:p.property("status")}),(t.action==="Create"&&t.payload.order_number===void 0||t.payload.order_number===null)&&e.push({ruleId:"required",location:p.property("order_number")}),t.payload.order_number!=null&&[...String(t.payload.order_number)].length>100&&e.push({ruleId:"max_length",location:p.property("order_number"),inputValue:t.payload.order_number,systemValue:100}),(t.action==="Create"&&t.payload.order_date===void 0||t.payload.order_date===null)&&e.push({ruleId:"required",location:p.property("order_date")}),(t.action==="Create"&&t.payload.total_amount===void 0||t.payload.total_amount===null)&&e.push({ruleId:"required",location:p.property("total_amount")})}},OrderItem:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.customer_order===void 0||t.payload.customer_order===null)&&e.push({ruleId:"required",location:p.property("customer_order")}),(t.action==="Create"&&t.payload.product_name===void 0||t.payload.product_name===null)&&e.push({ruleId:"required",location:p.property("product_name")}),t.payload.product_name!=null&&[...String(t.payload.product_name)].length>100&&e.push({ruleId:"max_length",location:p.property("product_name"),inputValue:t.payload.product_name,systemValue:100}),(t.action==="Create"&&t.payload.quantity===void 0||t.payload.quantity===null)&&e.push({ruleId:"required",location:p.property("quantity")}),(t.action==="Create"&&t.payload.unit_price===void 0||t.payload.unit_price===null)&&e.push({ruleId:"required",location:p.property("unit_price")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Commerce Test Platform"}},constants:[{entity:"OrderStatus",id:"1001",values:{platform:"1",name:"New",code:"NEW",color:"#94A3B8",displayOrder:1}},{entity:"OrderStatus",id:"1002",values:{platform:"1",name:"Paid",code:"PAID",color:"#22C55E",displayOrder:2}},{entity:"OrderStatus",id:"1003",values:{platform:"1",name:"Cancelled",code:"CANCELLED",color:"#EF4444",displayOrder:3}}],ensure:Vt}),Ot=document.querySelector("#status"),xt=document.querySelector("#result"),Mt=document.querySelector("#trace"),Ut=document.querySelector("#sql"),Wt=document.querySelector("#evidence-rows"),yt=document.querySelector("#persist"),At=document.querySelector("#logging"),gt=document.querySelector("#reset"),ct=document.querySelector("#query"),Pt=document.querySelector("#search"),Gt={filter:{orderNumber:{$contains:"KEEP"}}};let V;yt.checked=localStorage.getItem("teaql-browser-order-storage")==="opfs";async function jt(h){const t=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),e=await Et.open(t,{...Lt},{storage:h,databaseName:"teaql-browser-orders.sqlite3"});e.install(Kt),e.setDiagnosticSQLLogSink(void 0).setMutationLoggingEnabled(!1);const r=Object.freeze({policyId:"browser-order-seed",version:"1",fingerprint:"sha256:browser-order-seed-v1"}),i=new H().insertResource("dataService",e).withMutationPolicyRegistry(new $t(()=>({identity:r,review:(s,o)=>o.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Tt(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(i),await i.ensureSchema(),await i.ensureSchema(),{client:e,context:i,evidence:new Dt,diagnostics:[]}}async function Ct({context:h}){if((await F.customerOrdersWithMinimalFields().limit(1).comment("detect existing order demo").purpose("keep mutation seeding idempotent").executeForList(h)).length)return;const e=(await F.platforms().limit(2).comment("load bootstrap platform").purpose("prepare order demo").executeForList(h))[0],r=await F.customers().comment("initialize demo customer").purpose("prepare order demo").newEntity(h);r.updateName("North Star Retail").updatePlatform(e.id),await r.auditAs("seed browser order customer").save(h);for(let i=1;i<=4;i++){const s=await F.customerOrders().comment("initialize demo order").purpose("prepare order demo").newEntity(h);s.updateCustomer(r.id).updateOrderNumber(i<4?`KEEP-00${i}`:"DROP-004").updateOrderDate(`2026-10-0${i}`).updateTotalAmount(mt(String(i<4?i*100:900))),i===1?s.updateStatusToNew():s.updateStatusToPaid(),await s.auditAs("seed browser order").save(h);for(let o=1;o<=5;o++){const n=await F.orderItems().comment("initialize demo item").purpose("prepare item previews").newEntity(h);n.updateCustomerOrder(s.id).updateProductName(`Box ${o}`).updateQuantity(o).updateUnitPrice(mt("20")),await n.auditAs("seed browser order item").save(h)}}}async function pt(h){const t=JSON.parse(Pt.value),e=F.customerOrdersWithMinimalFields().filterByJson(t);h.evidence.enableAll(),h.diagnostics.length=0,h.client.setRuntimeTelemetrySink(h.evidence).setQueryLoggingEnabled(At.checked).setDiagnosticSQLLogSink({write:n=>h.diagnostics.push(n)});const r=await e.countAs("totalOrders").facetByStatusAs("statusCounts",F.orderStatusesWithMinimalFields().selectName().selectColor().countAs("orderCount").sumTotalAmountOfCustomerOrdersAs("orderTotalAmount",F.customerOrdersWithMinimalFields()).orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(F.orderStatusesWithMinimalFields().selectName().selectColor().comment("load status")).selectOrderItemListWith(F.orderItemsWithMinimalFields().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countOrderItemsAs("itemCount").orderByOrderDateDescending().orderByIdDescending().offset(1).limit(1).comment("load order list").purpose("render order list page").executeForList(h.context),i={data:r.data.map(n=>{const f=ft.customerOrder(n),l=f.orderItemList().size().eval();if(l==null)throw new Error("Selected item list unexpectedly has a null size");return{id:n.id,version:n.version,orderNumber:f.orderNumber().eval(),orderDate:f.orderDate().eval(),status:{name:f.status().name().eval(),color:f.status().color().eval()},items:Array.from({length:l},(c,a)=>({productName:f.orderItemList().get(a).productName().eval(),quantity:f.orderItemList().get(a).quantity().eval()})),itemCount:n.itemCount}}),metadata:{totalCount:r.totalCount,pageOffset:1,pageSize:1,aggregations:r.data.aggregations,searchWarnings:e.dynamicSearchWarnings},facets:{statusCounts:r.data.facets.statusCounts.map(n=>({id:n.id,name:ft.orderStatus(P.fromRecord(n)).name().eval(),color:ft.orderStatus(P.fromRecord(n)).color().eval(),orderCount:n.orderCount,orderTotalAmount:n.orderTotalAmount}))}};xt.textContent=JSON.stringify(i,null,2);const s=h.evidence.snapshot(),o=s.map(n=>{const f=n.traceChain??[],l=f.filter(w=>w.kind==="purpose"),c=l.length===1?`${l[0].detail}: ${f.filter(w=>w.kind==="comment").map(w=>w.detail).join(" → ")}`:"TraceChain unavailable",a=document.createElement("tr");for(const w of[`${n.elapsedMicros} µs`,n.tracePath.find(m=>m.kind==="request")?.name??"—",c,n.debugSQL]){const m=document.createElement("td");m.textContent=w,a.append(m)}return{row:a,businessTrace:c}});Wt.replaceChildren(...o.map(n=>n.row)),Mt.textContent=o.map(n=>n.businessTrace).join(` +`),Ut.textContent=JSON.stringify(s,null,2),Ot.textContent=`${h.client.storage.toUpperCase()} · ${r.totalCount} matches · ${s.length} SQL statements · ${h.diagnostics.length} diagnostics · policy installed · ready`}async function St(h){Ot.textContent=`Opening ${h.toUpperCase()} SQLite/WASM…`;const t=V;V=void 0,await t?.client.close();const e=await jt(h);V=e,await Ct(e),await pt(e)}function ot(h){Ot.textContent=h instanceof Error?`${h.name}: ${h.message}`:String(h)}ct.addEventListener("click",async()=>{if(V){ct.disabled=!0;try{await pt(V)}catch(h){ot(h)}finally{ct.disabled=!1}}});document.querySelector("#preset").addEventListener("click",()=>{Pt.value=JSON.stringify(Gt,null,2),ct.click()});At.addEventListener("change",()=>{V&&pt(V).catch(ot)});yt.addEventListener("change",()=>{const h=yt.checked?"opfs":"memory";localStorage.setItem("teaql-browser-order-storage",h),St(h).catch(ot)});gt.addEventListener("click",async()=>{if(V){gt.disabled=!0;try{await V.client.reset(V.context),await Ct(V),await pt(V)}catch(h){ot(h)}finally{gt.disabled=!1}}});St(yt.checked?"opfs":"memory").catch(ot); diff --git a/assets/sqlite.worker-BcUEWFpc.js b/assets/sqlite.worker-BcUEWFpc.js new file mode 100644 index 0000000000000000000000000000000000000000..dd1dc281680f44d338f6a68014ec7cd9338f5120 --- /dev/null +++ b/assets/sqlite.worker-BcUEWFpc.js @@ -0,0 +1,3 @@ +(function(){"use strict";globalThis.sqlite3Worker1Promiser=function qe(ie=qe.defaultConfig){if(arguments.length===1&&typeof arguments[0]=="function"){const de=ie;ie=Object.assign(Object.create(null),qe.defaultConfig),ie.onready=de}else ie=Object.assign(Object.create(null),qe.defaultConfig,ie);const f=Object.create(null),he=function(){},ye=ie.onerror||he,ge=ie.debug||he,Se=ie.generateMessageId?void 0:Object.create(null),Be=ie.generateMessageId||function(de){return de.type+"#"+(Se[de.type]=(Se[de.type]||0)+1)},Qe=(...de)=>{throw new Error(de.join(" "))};ie.worker||(ie.worker=qe.defaultConfig.worker),typeof ie.worker=="function"&&(ie.worker=ie.worker());let De,We;return ie.worker.onmessage=function(de){de=de.data,ge("worker1.onmessage",de);let Le=f[de.messageId];if(!Le){if(de&&de.type==="sqlite3-api"&&de.result==="worker1-ready"){ie.onready&&ie.onready(We);return}if(Le=f[de.type],Le&&Le.onrow){Le.onrow(de);return}ie.onunhandled?ie.onunhandled(arguments[0]):ye("sqlite3Worker1Promiser() unhandled worker message:",de);return}switch(delete f[de.messageId],de.type){case"error":Le.reject(de);return;case"open":De||(De=de.dbId);break;case"close":de.dbId===De&&(De=void 0);break}try{Le.resolve(de)}catch(Ie){Le.reject(Ie)}},We=function(){let de;arguments.length===1?de=arguments[0]:arguments.length===2?(de=Object.create(null),de.type=arguments[0],de.args=arguments[1],de.dbId=de.args.dbId):Qe("Invalid arguments for sqlite3Worker1Promiser()-created factory."),!de.dbId&&de.type!=="open"&&(de.dbId=De),de.messageId=Be(de),de.departureTime=performance.now();const Le=Object.create(null);Le.message=de;let Ie;de.type==="exec"&&de.args&&(typeof de.args.callback=="function"?(Ie=de.messageId+":row",Le.onrow=de.args.callback,de.args.callback=Ie,f[Ie]=Le):typeof de.args.callback=="string"&&Qe("exec callback may not be a string when using the Promise interface."));let Ee=new Promise(function(Ce,je){Le.resolve=Ce,Le.reject=je,f[de.messageId]=Le,ge("Posting",de.type,"message to Worker dbId="+(De||"default")+":",de),ie.worker.postMessage(de)});return Ie&&(Ee=Ee.finally(()=>delete f[Ie])),Ee}},globalThis.sqlite3Worker1Promiser.defaultConfig={worker:function(){return new Worker(new URL("/assets/sqlite3-worker1-Ydf970DV.js",self.location.href),{type:"module"})},onerror:(...qe)=>console.error("sqlite3Worker1Promiser():",...qe)},globalThis.sqlite3Worker1Promiser.v2=(function qe(ie=qe.defaultConfig){let f;typeof ie=="function"?(f=ie,ie={}):typeof ie?.onready=="function"&&(f=ie.onready,delete ie.onready);const he=Object.create(null);ie=Object.assign(ie||Object.create(null),{onready:async function(ge){try{f&&await f(ge),he.resolve(ge)}catch(Se){he.reject(Se)}}});const ye=new Promise(function(ge,Se){he.resolve=ge,he.reject=Se});try{this.original(ie)}catch(ge){he.reject(ge)}return ye}).bind({original:sqlite3Worker1Promiser}),globalThis.sqlite3Worker1Promiser.v2.defaultConfig=globalThis.sqlite3Worker1Promiser.defaultConfig,sqlite3Worker1Promiser.v2,delete globalThis.sqlite3Worker1Promiser;async function At(qe={}){var ie,f=qe,he=!!globalThis.window,ye=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process?.type;var ge="./this.program",Se=self.location.href,Be="";function Qe(e){return f.locateFile?f.locateFile(e,Be):Be+e}var De,We;if(he||ye){try{Be=new URL(".",Se).href}catch{}ye&&(We=e=>{var n=new XMLHttpRequest;return n.open("GET",e,!1),n.responseType="arraybuffer",n.send(null),new Uint8Array(n.response)}),De=async e=>{var n=await fetch(e,{credentials:"same-origin"});if(n.ok)return n.arrayBuffer();throw new Error(n.status+" : "+n.url)}}var de=console.log.bind(console),Le=console.error.bind(console),Ie,Ee=!1,Ce,je,et=!1;function Ct(){var e=nt.buffer;Je=new Int8Array(e),ht=new Int16Array(e),it=new Uint8Array(e),Oe=new Int32Array(e),Fe=new Uint32Array(e),Ve=new BigInt64Array(e),new BigUint64Array(e)}function _n(){if(f.wasmMemory)nt=f.wasmMemory;else{var e=f.INITIAL_MEMORY||8388608;nt=new WebAssembly.Memory({initial:e/65536,maximum:32768})}Ct()}function fn(){if(f.preRun)for(typeof f.preRun=="function"&&(f.preRun=[f.preRun]);f.preRun.length;)wn(f.preRun.shift());Nt(Dt)}function dn(){et=!0,!f.noFSInit&&!a.initialized&&a.init(),dt.__wasm_call_ctors(),a.ignorePermissions=!1}function pn(){if(f.postRun)for(typeof f.postRun=="function"&&(f.postRun=[f.postRun]);f.postRun.length;)Sn(f.postRun.shift());Nt(Rt)}function tt(e){f.onAbort?.(e),e=`Aborted(${e})`,Le(e),Ee=!0,e+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(e);throw je?.(n),n}var kt;function hn(){return f.locateFile?Qe("sqlite3.wasm"):new URL("/assets/sqlite3-BVKGSWc-.wasm",self.location.href).href}function mn(e){if(e==kt&&Ie)return new Uint8Array(Ie);if(We)return We(e);throw"both async and sync fetching of the wasm failed"}async function gn(e){if(!Ie)try{var n=await De(e);return new Uint8Array(n)}catch{}return mn(e)}async function bn(e,n){try{var l=await gn(e);return await WebAssembly.instantiate(l,n)}catch(i){Le(`failed to asynchronously prepare wasm: ${i}`),tt(i)}}async function yn(e,n,l){if(!e)try{var i=fetch(n,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(i,l)}catch(t){Le(`wasm streaming compile failed: ${t}`),Le("falling back to ArrayBuffer instantiation")}return bn(n,l)}function qn(){return{env:Yt,wasi_snapshot_preview1:Yt}}async function vn(){function e(i,t){return dt=i.exports,Ar(dt),dt}function n(i){return e(i.instance)}var l=qn();return f.instantiateWasm?new Promise((i,t)=>{f.instantiateWasm(l,(r,s)=>{i(e(r))})}):(kt??=hn(),n(await yn(Ie,kt,l)))}var ht,Oe,Ve,Je,Fe,it,Nt=e=>{for(;e.length>0;)e.shift()(f)},Rt=[],Sn=e=>Rt.push(e),Dt=[],wn=e=>Dt.push(e),nt,xe={isAbs:e=>e.charAt(0)==="/",splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,n)=>{for(var l=0,i=e.length-1;i>=0;i--){var t=e[i];t==="."?e.splice(i,1):t===".."?(e.splice(i,1),l++):l&&(e.splice(i,1),l--)}if(n)for(;l;l--)e.unshift("..");return e},normalize:e=>{var n=xe.isAbs(e),l=e.slice(-1)==="/";return e=xe.normalizeArray(e.split("/").filter(i=>!!i),!n).join("/"),!e&&!n&&(e="."),e&&l&&(e+="/"),(n?"/":"")+e},dirname:e=>{var n=xe.splitPath(e),l=n[0],i=n[1];return!l&&!i?".":(i&&(i=i.slice(0,-1)),l+i)},basename:e=>e&&e.match(/([^\/]+|\/)\/*$/)[1],join:(...e)=>xe.normalize(e.join("/")),join2:(e,n)=>xe.normalize(e+"/"+n)},En=()=>e=>(crypto.getRandomValues(e),0),jt=e=>(jt=En())(e),_t={resolve:(...e)=>{for(var n="",l=!1,i=e.length-1;i>=-1&&!l;i--){var t=i>=0?e[i]:a.cwd();if(typeof t!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";n=t+"/"+n,l=xe.isAbs(t)}return n=xe.normalizeArray(n.split("/").filter(r=>!!r),!l).join("/"),(l?"/":"")+n||"."},relative:(e,n)=>{e=_t.resolve(e).slice(1),n=_t.resolve(n).slice(1);function l(b){for(var M=0;M=0&&b[I]==="";I--);return M>I?[]:b.slice(M,I-M+1)}for(var i=l(e.split("/")),t=l(n.split("/")),r=Math.min(i.length,t.length),s=r,_=0;_{for(var t=n+l;e[n]&&!(n>=t);)++n;return n},mt=(e,n=0,l,i)=>{var t=zt(e,n,l);return Mt.decode(e.buffer?e.subarray(n,t):new Uint8Array(e.slice(n,t)))},Tt=[],vt=e=>{for(var n=0,l=0;l=55296&&i<=57343?(n+=4,++l):n+=3}return n},Bt=(e,n,l,i)=>{if(!(i>0))return 0;for(var t=l,r=l+i-1,s=0;s=r)break;n[l++]=_}else if(_<=2047){if(l+1>=r)break;n[l++]=192|_>>6,n[l++]=128|_&63}else if(_<=65535){if(l+2>=r)break;n[l++]=224|_>>12,n[l++]=128|_>>6&63,n[l++]=128|_&63}else{if(l+3>=r)break;n[l++]=240|_>>18,n[l++]=128|_>>12&63,n[l++]=128|_>>6&63,n[l++]=128|_&63,s++}}return n[l]=0,l-t},Ot=(e,n,l)=>{var i=vt(e)+1,t=new Array(i),r=Bt(e,t,0,t.length);return t.length=r,t},An=()=>{if(!Tt.length){var e=null;if(globalThis.window?.prompt&&(e=window.prompt("Input: "),e!==null&&(e+=` +`)),!e)return null;Tt=Ot(e)}return Tt.shift()},st={ttys:[],init(){},shutdown(){},register(e,n){st.ttys[e]={input:[],output:[],ops:n},a.registerDevice(e,st.stream_ops)},stream_ops:{open(e){var n=st.ttys[e.node.rdev];if(!n)throw new a.ErrnoError(43);e.tty=n,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,n,l,i,t){if(!e.tty||!e.tty.ops.get_char)throw new a.ErrnoError(60);for(var r=0,s=0;s0&&(de(mt(e.output)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,n,l){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,n){n===null||n===10?(Le(mt(e.output)),e.output=[]):n!=0&&e.output.push(n)},fsync(e){e.output?.length>0&&(Le(mt(e.output)),e.output=[])}}},In=(e,n)=>it.fill(0,e,e+n),Wt=(e,n)=>Math.ceil(e/n)*n,Qt=e=>{e=Wt(e,65536);var n=Xt(65536,e);return n&&In(n,e),n},me={ops_table:null,mount(e){return me.createNode(null,"/",16895,0)},createNode(e,n,l,i){if(a.isBlkdev(l)||a.isFIFO(l))throw new a.ErrnoError(63);me.ops_table||={dir:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr,lookup:me.node_ops.lookup,mknod:me.node_ops.mknod,rename:me.node_ops.rename,unlink:me.node_ops.unlink,rmdir:me.node_ops.rmdir,readdir:me.node_ops.readdir,symlink:me.node_ops.symlink},stream:{llseek:me.stream_ops.llseek}},file:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr},stream:{llseek:me.stream_ops.llseek,read:me.stream_ops.read,write:me.stream_ops.write,mmap:me.stream_ops.mmap,msync:me.stream_ops.msync}},link:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr,readlink:me.node_ops.readlink},stream:{}},chrdev:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr},stream:a.chrdev_stream_ops}};var t=a.createNode(e,n,l,i);return a.isDir(t.mode)?(t.node_ops=me.ops_table.dir.node,t.stream_ops=me.ops_table.dir.stream,t.contents={}):a.isFile(t.mode)?(t.node_ops=me.ops_table.file.node,t.stream_ops=me.ops_table.file.stream,t.usedBytes=0,t.contents=me.emptyFileContents??=new Uint8Array(0)):a.isLink(t.mode)?(t.node_ops=me.ops_table.link.node,t.stream_ops=me.ops_table.link.stream):a.isChrdev(t.mode)&&(t.node_ops=me.ops_table.chrdev.node,t.stream_ops=me.ops_table.chrdev.stream),t.atime=t.mtime=t.ctime=Date.now(),e&&(e.contents[n]=t,e.atime=e.mtime=e.ctime=t.atime),t},getFileDataAsTypedArray(e){return e.contents.subarray(0,e.usedBytes)},expandFileStorage(e,n){var l=e.contents.length;if(!(l>=n)){n=Math.max(n,l*(l<1024*1024?2:1.125)>>>0),l&&(n=Math.max(n,256));var i=me.getFileDataAsTypedArray(e);e.contents=new Uint8Array(n),e.contents.set(i)}},resizeFileStorage(e,n){if(e.usedBytes!=n){var l=e.contents;e.contents=new Uint8Array(n),e.contents.set(l.subarray(0,Math.min(n,e.usedBytes))),e.usedBytes=n}},node_ops:{getattr(e){var n={};return n.dev=a.isChrdev(e.mode)?e.id:1,n.ino=e.id,n.mode=e.mode,n.nlink=1,n.uid=0,n.gid=0,n.rdev=e.rdev,a.isDir(e.mode)?n.size=4096:a.isFile(e.mode)?n.size=e.usedBytes:a.isLink(e.mode)?n.size=e.link.length:n.size=0,n.atime=new Date(e.atime),n.mtime=new Date(e.mtime),n.ctime=new Date(e.ctime),n.blksize=4096,n.blocks=Math.ceil(n.size/n.blksize),n},setattr(e,n){for(const l of["mode","atime","mtime","ctime"])n[l]!=null&&(e[l]=n[l]);n.size!==void 0&&me.resizeFileStorage(e,n.size)},lookup(e,n){throw me.doesNotExistError||(me.doesNotExistError=new a.ErrnoError(44),me.doesNotExistError.stack=""),me.doesNotExistError},mknod(e,n,l,i){return me.createNode(e,n,l,i)},rename(e,n,l){var i;try{i=a.lookupNode(n,l)}catch{}if(i){if(a.isDir(e.mode))for(var t in i.contents)throw new a.ErrnoError(55);a.hashRemoveNode(i)}delete e.parent.contents[e.name],n.contents[l]=e,e.name=l,n.ctime=n.mtime=e.parent.ctime=e.parent.mtime=Date.now()},unlink(e,n){delete e.contents[n],e.ctime=e.mtime=Date.now()},rmdir(e,n){for(var l in a.lookupNode(e,n).contents)throw new a.ErrnoError(55);delete e.contents[n],e.ctime=e.mtime=Date.now()},readdir(e){return[".","..",...Object.keys(e.contents)]},symlink(e,n,l){var i=me.createNode(e,n,41471,0);return i.link=l,i},readlink(e){if(!a.isLink(e.mode))throw new a.ErrnoError(28);return e.link}},stream_ops:{read(e,n,l,i,t){var r=e.node.contents;if(t>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-t,i);return n.set(r.subarray(t,t+s),l),s},write(e,n,l,i,t,r){if(n.buffer===Je.buffer&&(r=!1),!i)return 0;var s=e.node;return s.mtime=s.ctime=Date.now(),r?(s.contents=n.subarray(l,l+i),s.usedBytes=i):s.usedBytes===0&&t===0?(s.contents=n.slice(l,l+i),s.usedBytes=i):(me.expandFileStorage(s,t+i),s.contents.set(n.subarray(l,l+i),t),s.usedBytes=Math.max(s.usedBytes,t+i)),i},llseek(e,n,l){var i=n;if(l===1?i+=e.position:l===2&&a.isFile(e.node.mode)&&(i+=e.node.usedBytes),i<0)throw new a.ErrnoError(28);return i},mmap(e,n,l,i,t){if(!a.isFile(e.node.mode))throw new a.ErrnoError(43);var r,s,_=e.node.contents;if(!(t&2)&&_.buffer===Je.buffer)s=!1,r=_.byteOffset;else{if(s=!0,r=Qt(n),!r)throw new a.ErrnoError(48);_&&((l>0||l+n<_.length)&&(_.subarray?_=_.subarray(l,l+n):_=Array.prototype.slice.call(_,l,l+n)),Je.set(_,r))}return{ptr:r,allocated:s}},msync(e,n,l,i,t){return me.stream_ops.write(e,n,0,i,l,!1),0}}},kn=e=>{if(typeof e!="string")return e;var n={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(typeof n>"u")throw new Error(`Unknown file open mode: ${e}`);return n},Ut=e=>(typeof e=="string"&&(e=Ot(e)),e.subarray||(e=new Uint8Array(e)),e),xt=(e,n)=>{var l=0;return e&&(l|=365),n&&(l|=146),l},Tn=async e=>{var n=await De(e);return new Uint8Array(n)},On=(...e)=>a.createDataFile(...e),ot=0,gt=null,xn=e=>{if(ot--,f.monitorRunDependencies?.(ot),ot==0&>){var n=gt;gt=null,n()}},Pn=e=>{ot++,f.monitorRunDependencies?.(ot)},Vt=[],Fn=async(e,n)=>{typeof Browser<"u"&&Browser.init();for(var l of Vt)if(l.canHandle(n))return l.handle(e,n);return e},Ht=async(e,n,l,i,t,r,s,_)=>{var c=n?_t.resolve(xe.join2(e,n)):e;Pn();try{var b=l;typeof l=="string"&&(b=await Tn(l)),b=await Fn(b,c),_?.(),r||On(e,n,b,i,t,s)}finally{xn()}},Ln=(e,n,l,i,t,r,s,_,c,b)=>{Ht(e,n,l,i,t,_,c,b).then(r).catch(s)},a={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(e){this.errno=e}},FSStream:class{shared={};get object(){return this.node}set object(e){this.node=e}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(e,n,l,i){e||(e=this),this.parent=e,this.mount=e.mount,this.id=a.nextInode++,this.name=n,this.mode=l,this.rdev=i,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return a.isDir(this.mode)}get isDevice(){return a.isChrdev(this.mode)}},lookupPath(e,n={}){if(!e)throw new a.ErrnoError(44);n.follow_mount??=!0,xe.isAbs(e)||(e=a.cwd()+"/"+e);e:for(var l=0;l<40;l++){for(var i=e.split("/").filter(b=>!!b),t=a.root,r="/",s=0;s>>0)%a.nameTable.length},hashAddNode(e){var n=a.hashName(e.parent.id,e.name);e.name_next=a.nameTable[n],a.nameTable[n]=e},hashRemoveNode(e){var n=a.hashName(e.parent.id,e.name);if(a.nameTable[n]===e)a.nameTable[n]=e.name_next;else for(var l=a.nameTable[n];l;){if(l.name_next===e){l.name_next=e.name_next;break}l=l.name_next}},lookupNode(e,n){var l=a.mayLookup(e);if(l)throw new a.ErrnoError(l);for(var i=a.hashName(e.id,n),t=a.nameTable[i];t;t=t.name_next){var r=t.name;if(t.parent.id===e.id&&r===n)return t}return a.lookup(e,n)},createNode(e,n,l,i){var t=new a.FSNode(e,n,l,i);return a.hashAddNode(t),t},destroyNode(e){a.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)===32768},isDir(e){return(e&61440)===16384},isLink(e){return(e&61440)===40960},isChrdev(e){return(e&61440)===8192},isBlkdev(e){return(e&61440)===24576},isFIFO(e){return(e&61440)===4096},isSocket(e){return(e&49152)===49152},flagsToPermissionString(e){var n=["r","w","rw"][e&3];return e&512&&(n+="w"),n},nodePermissions(e,n){return a.ignorePermissions?0:n.includes("r")&&!(e.mode&292)||n.includes("w")&&!(e.mode&146)||n.includes("x")&&!(e.mode&73)?2:0},mayLookup(e){if(!a.isDir(e.mode))return 54;var n=a.nodePermissions(e,"x");return n||(e.node_ops.lookup?0:2)},mayCreate(e,n){if(!a.isDir(e.mode))return 54;try{return a.lookupNode(e,n),20}catch{}return a.nodePermissions(e,"wx")},mayDelete(e,n,l){var i;try{i=a.lookupNode(e,n)}catch(r){return r.errno}var t=a.nodePermissions(e,"wx");if(t)return t;if(l){if(!a.isDir(i.mode))return 54;if(a.isRoot(i)||a.getPath(i)===a.cwd())return 10}else if(a.isDir(i.mode))return 31;return 0},mayOpen(e,n){if(!e)return 44;if(a.isLink(e.mode))return 32;var l=a.flagsToPermissionString(n);return a.isDir(e.mode)&&(l!=="r"||n&576)?31:a.nodePermissions(e,l)},checkOpExists(e,n){if(!e)throw new a.ErrnoError(n);return e},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=a.MAX_OPEN_FDS;e++)if(!a.streams[e])return e;throw new a.ErrnoError(33)},getStreamChecked(e){var n=a.getStream(e);if(!n)throw new a.ErrnoError(8);return n},getStream:e=>a.streams[e],createStream(e,n=-1){return e=Object.assign(new a.FSStream,e),n==-1&&(n=a.nextfd()),e.fd=n,a.streams[n]=e,e},closeStream(e){a.streams[e]=null},dupStream(e,n=-1){var l=a.createStream(e,n);return l.stream_ops?.dup?.(l),l},doSetAttr(e,n,l){var i=e?.stream_ops.setattr,t=i?e:n;i??=n.node_ops.setattr,a.checkOpExists(i,63),i(t,l)},chrdev_stream_ops:{open(e){e.stream_ops=a.getDevice(e.node.rdev).stream_ops,e.stream_ops.open?.(e)},llseek(){throw new a.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,n)=>e<<8|n,registerDevice(e,n){a.devices[e]={stream_ops:n}},getDevice:e=>a.devices[e],getMounts(e){for(var n=[],l=[e];l.length;){var i=l.pop();n.push(i),l.push(...i.mounts)}return n},syncfs(e,n){typeof e=="function"&&(n=e,e=!1),a.syncFSRequests++,a.syncFSRequests>1&&Le(`warning: ${a.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var l=a.getMounts(a.root.mount),i=0;function t(_){return a.syncFSRequests--,n(_)}function r(_){if(_)return r.errored?void 0:(r.errored=!0,t(_));++i>=l.length&&t(null)}for(var s of l)s.type.syncfs?s.type.syncfs(s,e,r):r(null)},mount(e,n,l){var i=l==="/",t=!l,r;if(i&&a.root)throw new a.ErrnoError(10);if(!i&&!t){var s=a.lookupPath(l,{follow_mount:!1});if(l=s.path,r=s.node,a.isMountpoint(r))throw new a.ErrnoError(10);if(!a.isDir(r.mode))throw new a.ErrnoError(54)}var _={type:e,opts:n,mountpoint:l,mounts:[]},c=e.mount(_);return c.mount=_,_.root=c,i?a.root=c:r&&(r.mounted=_,r.mount&&r.mount.mounts.push(_)),c},unmount(e){var n=a.lookupPath(e,{follow_mount:!1});if(!a.isMountpoint(n.node))throw new a.ErrnoError(28);var l=n.node,i=l.mounted,t=a.getMounts(i);for(var[r,s]of Object.entries(a.nameTable))for(;s;){var _=s.name_next;t.includes(s.mount)&&a.destroyNode(s),s=_}l.mounted=null;var c=l.mount.mounts.indexOf(i);l.mount.mounts.splice(c,1)},lookup(e,n){return e.node_ops.lookup(e,n)},mknod(e,n,l){var i=a.lookupPath(e,{parent:!0}).node,t=xe.basename(e);if(!t)throw new a.ErrnoError(28);if(t==="."||t==="..")throw new a.ErrnoError(20);var r=a.mayCreate(i,t);if(r)throw new a.ErrnoError(r);if(!i.node_ops.mknod)throw new a.ErrnoError(63);return i.node_ops.mknod(i,t,n,l)},statfs(e){return a.statfsNode(a.lookupPath(e,{follow:!0}).node)},statfsStream(e){return a.statfsNode(e.node)},statfsNode(e){var n={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:a.nextInode,ffree:a.nextInode-1,fsid:42,flags:2,namelen:255};return e.node_ops.statfs&&Object.assign(n,e.node_ops.statfs(e.mount.opts.root)),n},create(e,n=438){return n&=4095,n|=32768,a.mknod(e,n,0)},mkdir(e,n=511){return n&=1023,n|=16384,a.mknod(e,n,0)},mkdirTree(e,n){var l=e.split("/"),i="";for(var t of l)if(t){(i||xe.isAbs(e))&&(i+="/"),i+=t;try{a.mkdir(i,n)}catch(r){if(r.errno!=20)throw r}}},mkdev(e,n,l){return typeof l>"u"&&(l=n,n=438),n|=8192,a.mknod(e,n,l)},symlink(e,n){if(!_t.resolve(e))throw new a.ErrnoError(44);var l=a.lookupPath(n,{parent:!0}).node;if(!l)throw new a.ErrnoError(44);var i=xe.basename(n),t=a.mayCreate(l,i);if(t)throw new a.ErrnoError(t);if(!l.node_ops.symlink)throw new a.ErrnoError(63);return l.node_ops.symlink(l,i,e)},rename(e,n){var l=xe.dirname(e),i=xe.dirname(n),t=xe.basename(e),r=xe.basename(n),s=a.lookupPath(e,{parent:!0}),_=s.node,c;if(s=a.lookupPath(n,{parent:!0}),c=s.node,!_||!c)throw new a.ErrnoError(44);if(_.mount!==c.mount)throw new a.ErrnoError(75);var b=a.lookupNode(_,t),M=_t.relative(e,i);if(M.charAt(0)!==".")throw new a.ErrnoError(28);if(M=_t.relative(n,l),M.charAt(0)!==".")throw new a.ErrnoError(55);var I;try{I=a.lookupNode(c,r)}catch{}if(b!==I){var S=a.isDir(b.mode),w=a.mayDelete(_,t,S);if(w)throw new a.ErrnoError(w);if(w=I?a.mayDelete(c,r,S):a.mayCreate(c,r),w)throw new a.ErrnoError(w);if(!_.node_ops.rename)throw new a.ErrnoError(63);if(a.isMountpoint(b)||I&&a.isMountpoint(I))throw new a.ErrnoError(10);if(c!==_&&(w=a.nodePermissions(_,"w"),w))throw new a.ErrnoError(w);a.hashRemoveNode(b);try{_.node_ops.rename(b,c,r),b.parent=c}catch(x){throw x}finally{a.hashAddNode(b)}}},rmdir(e){var n=a.lookupPath(e,{parent:!0}).node,l=xe.basename(e),i=a.lookupNode(n,l),t=a.mayDelete(n,l,!0);if(t)throw new a.ErrnoError(t);if(!n.node_ops.rmdir)throw new a.ErrnoError(63);if(a.isMountpoint(i))throw new a.ErrnoError(10);n.node_ops.rmdir(n,l),a.destroyNode(i)},readdir(e){var n=a.lookupPath(e,{follow:!0}).node;return a.checkOpExists(n.node_ops.readdir,54)(n)},unlink(e){var n=a.lookupPath(e,{parent:!0}).node;if(!n)throw new a.ErrnoError(44);var l=xe.basename(e),i=a.lookupNode(n,l),t=a.mayDelete(n,l,!1);if(t)throw new a.ErrnoError(t);if(!n.node_ops.unlink)throw new a.ErrnoError(63);if(a.isMountpoint(i))throw new a.ErrnoError(10);n.node_ops.unlink(n,l),a.destroyNode(i)},readlink(e){var n=a.lookupPath(e).node;if(!n)throw new a.ErrnoError(44);if(!n.node_ops.readlink)throw new a.ErrnoError(28);return n.node_ops.readlink(n)},stat(e,n){var l=a.lookupPath(e,{follow:!n}).node;return a.checkOpExists(l.node_ops.getattr,63)(l)},fstat(e){var n=a.getStreamChecked(e),l=n.node,i=n.stream_ops.getattr,t=i?n:l;return i??=l.node_ops.getattr,a.checkOpExists(i,63),i(t)},lstat(e){return a.stat(e,!0)},doChmod(e,n,l,i){a.doSetAttr(e,n,{mode:l&4095|n.mode&-4096,ctime:Date.now(),dontFollow:i})},chmod(e,n,l){var i;typeof e=="string"?i=a.lookupPath(e,{follow:!l}).node:i=e,a.doChmod(null,i,n,l)},lchmod(e,n){a.chmod(e,n,!0)},fchmod(e,n){var l=a.getStreamChecked(e);a.doChmod(l,l.node,n,!1)},doChown(e,n,l){a.doSetAttr(e,n,{timestamp:Date.now(),dontFollow:l})},chown(e,n,l,i){var t;typeof e=="string"?t=a.lookupPath(e,{follow:!i}).node:t=e,a.doChown(null,t,i)},lchown(e,n,l){a.chown(e,n,l,!0)},fchown(e,n,l){var i=a.getStreamChecked(e);a.doChown(i,i.node,!1)},doTruncate(e,n,l){if(a.isDir(n.mode))throw new a.ErrnoError(31);if(!a.isFile(n.mode))throw new a.ErrnoError(28);var i=a.nodePermissions(n,"w");if(i)throw new a.ErrnoError(i);a.doSetAttr(e,n,{size:l,timestamp:Date.now()})},truncate(e,n){if(n<0)throw new a.ErrnoError(28);var l;typeof e=="string"?l=a.lookupPath(e,{follow:!0}).node:l=e,a.doTruncate(null,l,n)},ftruncate(e,n){var l=a.getStreamChecked(e);if(n<0||(l.flags&2097155)===0)throw new a.ErrnoError(28);a.doTruncate(l,l.node,n)},utime(e,n,l){var i=a.lookupPath(e,{follow:!0}).node;a.checkOpExists(i.node_ops.setattr,63)(i,{atime:n,mtime:l})},open(e,n,l=438){if(e==="")throw new a.ErrnoError(44);n=kn(n),n&64?l=l&4095|32768:l=0;var i,t;if(typeof e=="object")i=e;else{t=e.endsWith("/");var r=a.lookupPath(e,{follow:!(n&131072),noent_okay:!0});i=r.node,e=r.path}var s=!1;if(n&64)if(i){if(n&128)throw new a.ErrnoError(20)}else{if(t)throw new a.ErrnoError(31);i=a.mknod(e,l|511,0),s=!0}if(!i)throw new a.ErrnoError(44);if(a.isChrdev(i.mode)&&(n&=-513),n&65536&&!a.isDir(i.mode))throw new a.ErrnoError(54);if(!s){var _=a.mayOpen(i,n);if(_)throw new a.ErrnoError(_)}n&512&&!s&&a.truncate(i,0),n&=-131713;var c=a.createStream({node:i,path:a.getPath(i),flags:n,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1});return c.stream_ops.open&&c.stream_ops.open(c),s&&a.chmod(i,l&511),c},close(e){if(a.isClosed(e))throw new a.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(n){throw n}finally{a.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,n,l){if(a.isClosed(e))throw new a.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new a.ErrnoError(70);if(l!=0&&l!=1&&l!=2)throw new a.ErrnoError(28);return e.position=e.stream_ops.llseek(e,n,l),e.ungotten=[],e.position},read(e,n,l,i,t){if(i<0||t<0)throw new a.ErrnoError(28);if(a.isClosed(e))throw new a.ErrnoError(8);if((e.flags&2097155)===1)throw new a.ErrnoError(8);if(a.isDir(e.node.mode))throw new a.ErrnoError(31);if(!e.stream_ops.read)throw new a.ErrnoError(28);var r=typeof t<"u";if(!r)t=e.position;else if(!e.seekable)throw new a.ErrnoError(70);var s=e.stream_ops.read(e,n,l,i,t);return r||(e.position+=s),s},write(e,n,l,i,t,r){if(i<0||t<0)throw new a.ErrnoError(28);if(a.isClosed(e))throw new a.ErrnoError(8);if((e.flags&2097155)===0)throw new a.ErrnoError(8);if(a.isDir(e.node.mode))throw new a.ErrnoError(31);if(!e.stream_ops.write)throw new a.ErrnoError(28);e.seekable&&e.flags&1024&&a.llseek(e,0,2);var s=typeof t<"u";if(!s)t=e.position;else if(!e.seekable)throw new a.ErrnoError(70);var _=e.stream_ops.write(e,n,l,i,t,r);return s||(e.position+=_),_},mmap(e,n,l,i,t){if((i&2)!==0&&(t&2)===0&&(e.flags&2097155)!==2)throw new a.ErrnoError(2);if((e.flags&2097155)===1)throw new a.ErrnoError(2);if(!e.stream_ops.mmap)throw new a.ErrnoError(43);if(!n)throw new a.ErrnoError(28);return e.stream_ops.mmap(e,n,l,i,t)},msync(e,n,l,i,t){return e.stream_ops.msync?e.stream_ops.msync(e,n,l,i,t):0},ioctl(e,n,l){if(!e.stream_ops.ioctl)throw new a.ErrnoError(59);return e.stream_ops.ioctl(e,n,l)},readFile(e,n={}){n.flags=n.flags||0,n.encoding=n.encoding||"binary",n.encoding!=="utf8"&&n.encoding!=="binary"&&tt(`Invalid encoding type "${n.encoding}"`);var l=a.open(e,n.flags),i=a.stat(e).size,t=new Uint8Array(i);return a.read(l,t,0,i,0),n.encoding==="utf8"&&(t=mt(t)),a.close(l),t},writeFile(e,n,l={}){l.flags=l.flags||577;var i=a.open(e,l.flags,l.mode);n=Ut(n),a.write(i,n,0,n.byteLength,void 0,l.canOwn),a.close(i)},cwd:()=>a.currentPath,chdir(e){var n=a.lookupPath(e,{follow:!0});if(n.node===null)throw new a.ErrnoError(44);if(!a.isDir(n.node.mode))throw new a.ErrnoError(54);var l=a.nodePermissions(n.node,"x");if(l)throw new a.ErrnoError(l);a.currentPath=n.path},createDefaultDirectories(){a.mkdir("/tmp"),a.mkdir("/home"),a.mkdir("/home/web_user")},createDefaultDevices(){a.mkdir("/dev"),a.registerDevice(a.makedev(1,3),{read:()=>0,write:(i,t,r,s,_)=>s,llseek:()=>0}),a.mkdev("/dev/null",a.makedev(1,3)),st.register(a.makedev(5,0),st.default_tty_ops),st.register(a.makedev(6,0),st.default_tty1_ops),a.mkdev("/dev/tty",a.makedev(5,0)),a.mkdev("/dev/tty1",a.makedev(6,0));var e=new Uint8Array(1024),n=0,l=()=>(n===0&&(jt(e),n=e.byteLength),e[--n]);a.createDevice("/dev","random",l),a.createDevice("/dev","urandom",l),a.mkdir("/dev/shm"),a.mkdir("/dev/shm/tmp")},createSpecialDirectories(){a.mkdir("/proc");var e=a.mkdir("/proc/self");a.mkdir("/proc/self/fd"),a.mount({mount(){var n=a.createNode(e,"fd",16895,73);return n.stream_ops={llseek:me.stream_ops.llseek},n.node_ops={lookup(l,i){var t=+i,r=a.getStreamChecked(t),s={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path},id:t+1};return s.parent=s,s},readdir(){return Array.from(a.streams.entries()).filter(([l,i])=>i).map(([l,i])=>l.toString())}},n}},{},"/proc/self/fd")},createStandardStreams(e,n,l){e?a.createDevice("/dev","stdin",e):a.symlink("/dev/tty","/dev/stdin"),n?a.createDevice("/dev","stdout",null,n):a.symlink("/dev/tty","/dev/stdout"),l?a.createDevice("/dev","stderr",null,l):a.symlink("/dev/tty1","/dev/stderr"),a.open("/dev/stdin",0),a.open("/dev/stdout",1),a.open("/dev/stderr",1)},staticInit(){a.nameTable=new Array(4096),a.mount(me,{},"/"),a.createDefaultDirectories(),a.createDefaultDevices(),a.createSpecialDirectories(),a.filesystems={MEMFS:me}},init(e,n,l){a.initialized=!0,e??=f.stdin,n??=f.stdout,l??=f.stderr,a.createStandardStreams(e,n,l)},quit(){a.initialized=!1;for(var e of a.streams)e&&a.close(e)},findObject(e,n){var l=a.analyzePath(e,n);return l.exists?l.object:null},analyzePath(e,n){try{var l=a.lookupPath(e,{follow:!n});e=l.path}catch{}var i={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var l=a.lookupPath(e,{parent:!0});i.parentExists=!0,i.parentPath=l.path,i.parentObject=l.node,i.name=xe.basename(e),l=a.lookupPath(e,{follow:!n}),i.exists=!0,i.path=l.path,i.object=l.node,i.name=l.node.name,i.isRoot=l.path==="/"}catch(t){i.error=t.errno}return i},createPath(e,n,l,i){e=typeof e=="string"?e:a.getPath(e);for(var t=n.split("/").reverse();t.length;){var r=t.pop();if(r){var s=xe.join2(e,r);try{a.mkdir(s)}catch(_){if(_.errno!=20)throw _}e=s}}return s},createFile(e,n,l,i,t){var r=xe.join2(typeof e=="string"?e:a.getPath(e),n),s=xt(i,t);return a.create(r,s)},createDataFile(e,n,l,i,t,r){var s=n;e&&(e=typeof e=="string"?e:a.getPath(e),s=n?xe.join2(e,n):e);var _=xt(i,t),c=a.create(s,_);if(l){l=Ut(l),a.chmod(c,_|146);var b=a.open(c,577);a.write(b,l,0,l.length,0,r),a.close(b),a.chmod(c,_)}},createDevice(e,n,l,i){var t=xe.join2(typeof e=="string"?e:a.getPath(e),n),r=xt(!!l,!!i);a.createDevice.major??=64;var s=a.makedev(a.createDevice.major++,0);return a.registerDevice(s,{open(_){_.seekable=!1},close(_){i?.buffer?.length&&i(10)},read(_,c,b,M,I){for(var S=0,w=0;wthis.length-1||I<0)){var S=I%this.chunkSize,w=I/this.chunkSize|0;return this.getter(w)[S]}}setDataGetter(I){this.getter=I}cacheLength(){var I=new XMLHttpRequest;I.open("HEAD",l,!1),I.send(null),I.status>=200&&I.status<300||I.status===304||tt("Couldn't load "+l+". Status: "+I.status);var S=Number(I.getResponseHeader("Content-length")),w,x=(w=I.getResponseHeader("Accept-Ranges"))&&w==="bytes",L=(w=I.getResponseHeader("Content-Encoding"))&&w==="gzip",H=1024*1024;x||(H=S);var g=(D,Q)=>{D>Q&&tt("invalid range ("+D+", "+Q+") or no bytes requested!"),Q>S-1&&tt("only "+S+" bytes available! programmer error!");var A=new XMLHttpRequest;return A.open("GET",l,!1),S!==H&&A.setRequestHeader("Range","bytes="+D+"-"+Q),A.responseType="arraybuffer",A.overrideMimeType&&A.overrideMimeType("text/plain; charset=x-user-defined"),A.send(null),A.status>=200&&A.status<300||A.status===304||tt("Couldn't load "+l+". Status: "+A.status),A.response!==void 0?new Uint8Array(A.response||[]):Ot(A.responseText||"")},h=this;h.setDataGetter(D=>{var Q=D*H,A=(D+1)*H-1;return A=Math.min(A,S-1),typeof h.chunks[D]>"u"&&(h.chunks[D]=g(Q,A)),typeof h.chunks[D]>"u"&&tt("doXHR failed!"),h.chunks[D]}),(L||!S)&&(H=S=1,S=this.getter(0).length,H=S,de("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=S,this._chunkSize=H,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(globalThis.XMLHttpRequest){ye||tt("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var s={isDevice:!1,contents:new r}}else var s={isDevice:!1,url:l};var _=a.createFile(e,n,s,i,t);s.contents?_.contents=s.contents:s.url&&(_.contents=null,_.url=s.url),Object.defineProperties(_,{usedBytes:{get:function(){return this.contents.length}}});var c={};for(const[M,I]of Object.entries(_.stream_ops))c[M]=(...S)=>(a.forceLoadFile(_),I(...S));function b(M,I,S,w,x){var L=M.node.contents;if(x>=L.length)return 0;var H=Math.min(L.length-x,w);if(L.slice)for(var g=0;g(a.forceLoadFile(_),b(M,I,S,w,x)),c.mmap=(M,I,S,w,x)=>{a.forceLoadFile(_);var L=Qt(I);if(!L)throw new a.ErrnoError(48);return b(M,Je,L,I,S),{ptr:L,allocated:!0}},_.stream_ops=c,_}},Cn=(e,n,l)=>{if(!e)return"";var i=zt(it,e,n);return Mt.decode(it.subarray(e,i))},ve={calculateAt(e,n,l){if(xe.isAbs(n))return n;var i;if(e===-100?i=a.cwd():i=ve.getStreamFromFD(e).path,n.length==0){if(!l)throw new a.ErrnoError(44);return i}return i+"/"+n},writeStat(e,n){Fe[e>>2]=n.dev,Fe[e+4>>2]=n.mode,Fe[e+8>>2]=n.nlink,Fe[e+12>>2]=n.uid,Fe[e+16>>2]=n.gid,Fe[e+20>>2]=n.rdev,Ve[e+24>>3]=BigInt(n.size),Oe[e+32>>2]=4096,Oe[e+36>>2]=n.blocks;var l=n.atime.getTime(),i=n.mtime.getTime(),t=n.ctime.getTime();return Ve[e+40>>3]=BigInt(Math.floor(l/1e3)),Fe[e+48>>2]=l%1e3*1e3*1e3,Ve[e+56>>3]=BigInt(Math.floor(i/1e3)),Fe[e+64>>2]=i%1e3*1e3*1e3,Ve[e+72>>3]=BigInt(Math.floor(t/1e3)),Fe[e+80>>2]=t%1e3*1e3*1e3,Ve[e+88>>3]=BigInt(n.ino),0},writeStatFs(e,n){Fe[e+4>>2]=n.bsize,Fe[e+60>>2]=n.bsize,Ve[e+8>>3]=BigInt(n.blocks),Ve[e+16>>3]=BigInt(n.bfree),Ve[e+24>>3]=BigInt(n.bavail),Ve[e+32>>3]=BigInt(n.files),Ve[e+40>>3]=BigInt(n.ffree),Fe[e+48>>2]=n.fsid,Fe[e+64>>2]=n.flags,Fe[e+56>>2]=n.namelen},doMsync(e,n,l,i,t){if(!a.isFile(n.node.mode))throw new a.ErrnoError(43);if(i&2)return 0;var r=it.slice(e,e+l);a.msync(n,r,t,l,i)},getStreamFromFD(e){return a.getStreamChecked(e)},varargs:void 0,getStr(e){return Cn(e)}};function Nn(e,n){try{return e=ve.getStr(e),a.chmod(e,n),0}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function Rn(e,n,l,i){try{if(n=ve.getStr(n),n=ve.calculateAt(e,n),l&-8)return-28;var t=a.lookupPath(n,{follow:!0}).node;if(!t)return-44;var r="";return l&4&&(r+="r"),l&2&&(r+="w"),l&1&&(r+="x"),r&&a.nodePermissions(t,r)?-2:0}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function Dn(e,n){try{return a.fchmod(e,n),0}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function jn(e,n,l){try{return a.fchown(e,n,l),0}catch(i){if(typeof a>"u"||i.name!=="ErrnoError")throw i;return-i.errno}}var St=()=>{var e=Oe[+ve.varargs>>2];return ve.varargs+=4,e},ft=St;function Mn(e,n,l){ve.varargs=l;try{var i=ve.getStreamFromFD(e);switch(n){case 0:var t=St();if(t<0)return-28;for(;a.streams[t];)t++;return a.dupStream(i,t).fd;case 1:case 2:return 0;case 3:return i.flags;case 4:var t=St();return i.flags|=t,0;case 12:var t=ft(),r=0;return ht[t+r>>1]=2,0;case 13:case 14:return 0}return-28}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function zn(e,n){try{return ve.writeStat(n,a.fstat(e))}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}var Bn=9007199254740992,Wn=-9007199254740992,bt=e=>eBn?NaN:Number(e);function Qn(e,n){n=bt(n);try{return isNaN(n)?-61:(a.ftruncate(e,n),0)}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}var lt=(e,n,l)=>Bt(e,it,n,l);function Un(e,n){try{if(n===0)return-28;var l=a.cwd(),i=vt(l)+1;return n"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function Vn(e,n,l){ve.varargs=l;try{var i=ve.getStreamFromFD(e);switch(n){case 21509:return i.tty?0:-59;case 21505:if(!i.tty)return-59;if(i.tty.ops.ioctl_tcgets){var t=i.tty.ops.ioctl_tcgets(i),I=ft();Oe[I>>2]=t.c_iflag||0,Oe[I+4>>2]=t.c_oflag||0,Oe[I+8>>2]=t.c_cflag||0,Oe[I+12>>2]=t.c_lflag||0;for(var r=0;r<32;r++)Je[I+r+17]=t.c_cc[r]||0;return 0}return 0;case 21510:case 21511:case 21512:return i.tty?0:-59;case 21506:case 21507:case 21508:if(!i.tty)return-59;if(i.tty.ops.ioctl_tcsets){for(var I=ft(),s=Oe[I>>2],_=Oe[I+4>>2],c=Oe[I+8>>2],b=Oe[I+12>>2],M=[],r=0;r<32;r++)M.push(Je[I+r+17]);return i.tty.ops.ioctl_tcsets(i.tty,n,{c_iflag:s,c_oflag:_,c_cflag:c,c_lflag:b,c_cc:M})}return 0;case 21519:if(!i.tty)return-59;var I=ft();return Oe[I>>2]=0,0;case 21520:return i.tty?-28:-59;case 21537:case 21531:var I=ft();return a.ioctl(i,n,I);case 21523:if(!i.tty)return-59;if(i.tty.ops.ioctl_tiocgwinsz){var S=i.tty.ops.ioctl_tiocgwinsz(i.tty),I=ft();ht[I>>1]=S[0],ht[I+2>>1]=S[1]}return 0;case 21524:return i.tty?0:-59;case 21515:return i.tty?0:-59;default:return-28}}catch(w){if(typeof a>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}function Hn(e,n){try{return e=ve.getStr(e),ve.writeStat(n,a.lstat(e))}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function Gn(e,n,l){try{return n=ve.getStr(n),n=ve.calculateAt(e,n),a.mkdir(n,l,0),0}catch(i){if(typeof a>"u"||i.name!=="ErrnoError")throw i;return-i.errno}}function $n(e,n,l,i){try{n=ve.getStr(n);var t=i&256,r=i&4096;return i=i&-6401,n=ve.calculateAt(e,n,r),ve.writeStat(l,t?a.lstat(n):a.stat(n))}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function Kn(e,n,l,i){ve.varargs=i;try{n=ve.getStr(n),n=ve.calculateAt(e,n);var t=i?St():0;return a.open(n,l,t).fd}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return-r.errno}}function Jn(e,n,l,i){try{if(n=ve.getStr(n),n=ve.calculateAt(e,n),i<=0)return-28;var t=a.readlink(n),r=Math.min(i,vt(t)),s=Je[l+r];return lt(t,l,i+1),Je[l+r]=s,r}catch(_){if(typeof a>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Xn(e){try{return e=ve.getStr(e),a.rmdir(e),0}catch(n){if(typeof a>"u"||n.name!=="ErrnoError")throw n;return-n.errno}}function Yn(e,n){try{return e=ve.getStr(e),ve.writeStat(n,a.stat(e))}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function Zn(e,n,l){try{if(n=ve.getStr(n),n=ve.calculateAt(e,n),!l)a.unlink(n);else if(l===512)a.rmdir(n);else return-28;return 0}catch(i){if(typeof a>"u"||i.name!=="ErrnoError")throw i;return-i.errno}}var Gt=e=>Fe[e>>2]+Oe[e+4>>2]*4294967296;function er(e,n,l,i){try{n=ve.getStr(n),n=ve.calculateAt(e,n,!0);var t=Date.now(),r,s;if(!l)r=t,s=t;else{var _=Gt(l),c=Oe[l+8>>2];c==1073741823?r=t:c==1073741822?r=null:r=_*1e3+c/(1e3*1e3),l+=16,_=Gt(l),c=Oe[l+8>>2],c==1073741823?s=t:c==1073741822?s=null:s=_*1e3+c/(1e3*1e3)}return(s??r)!==null&&a.utime(n,r,s),0}catch(b){if(typeof a>"u"||b.name!=="ErrnoError")throw b;return-b.errno}}var tr=e=>e%4===0&&(e%100!==0||e%400===0),nr=[0,31,60,91,121,152,182,213,244,274,305,335],rr=[0,31,59,90,120,151,181,212,243,273,304,334],ir=e=>(tr(e.getFullYear())?nr:rr)[e.getMonth()]+e.getDate()-1;function sr(e,n){e=bt(e);var l=new Date(e*1e3);Oe[n>>2]=l.getSeconds(),Oe[n+4>>2]=l.getMinutes(),Oe[n+8>>2]=l.getHours(),Oe[n+12>>2]=l.getDate(),Oe[n+16>>2]=l.getMonth(),Oe[n+20>>2]=l.getFullYear()-1900,Oe[n+24>>2]=l.getDay();var i=ir(l)|0;Oe[n+28>>2]=i,Oe[n+36>>2]=-(l.getTimezoneOffset()*60);var t=new Date(l.getFullYear(),0,1),r=new Date(l.getFullYear(),6,1).getTimezoneOffset(),s=t.getTimezoneOffset(),_=(r!=s&&l.getTimezoneOffset()==Math.min(s,r))|0;Oe[n+32>>2]=_}function or(e,n,l,i,t,r,s){t=bt(t);try{var _=ve.getStreamFromFD(i),c=a.mmap(_,e,t,n,l),b=c.ptr;return Oe[r>>2]=c.allocated,Fe[s>>2]=b,0}catch(M){if(typeof a>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}function lr(e,n,l,i,t,r){r=bt(r);try{var s=ve.getStreamFromFD(t);l&2&&ve.doMsync(e,s,n,i,r)}catch(_){if(typeof a>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}var ar=(e,n,l,i)=>{var t=new Date().getFullYear(),r=new Date(t,0,1),s=new Date(t,6,1),_=r.getTimezoneOffset(),c=s.getTimezoneOffset(),b=Math.max(_,c);Fe[e>>2]=b*60,Oe[n>>2]=+(_!=c);var M=w=>{var x=w>=0?"-":"+",L=Math.abs(w);return`UTC${x}${String(Math.floor(L/60)).padStart(2,"0")}${String(L%60).padStart(2,"0")}`},I=M(_),S=M(c);c<_?(lt(I,l,17),lt(S,i,17)):(lt(I,i,17),lt(S,l,17))},$t=()=>performance.now(),Kt=()=>Date.now(),cr=e=>e>=0&&e<=3;function ur(e,n,l){if(!cr(e))return 28;var i;e===0?i=Kt():i=$t();var t=Math.round(i*1e3*1e3);return Ve[l>>3]=BigInt(t),0}var Jt=()=>2147483648,_r=()=>Jt(),fr=e=>{var n=(e-nt.buffer.byteLength+65535)/65536|0;try{return nt.grow(n),Ct(),1}catch{}},dr=e=>{var n=it.length;e>>>=0;var l=Jt();if(e>l)return!1;for(var i=1;i<=4;i*=2){var t=n*(1+.2/i);if(t=Math.min(t,e+100663296),fr(Math.min(l,Wt(Math.max(e,t),65536))))return!0}return!1},Pt={},pr=()=>ge||"./this.program",yt=()=>{if(!yt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:pr()};for(var n in Pt)Pt[n]===void 0?delete e[n]:e[n]=Pt[n];var l=[];for(var n in e)l.push(`${n}=${e[n]}`);yt.strings=l}return yt.strings},hr=(e,n)=>{var l=0,i=0;for(var t of yt()){var r=n+l;Fe[e+i>>2]=r,l+=lt(t,r,1/0)+1,i+=4}return 0},mr=(e,n)=>{var l=yt();Fe[e>>2]=l.length;var i=0;for(var t of l)i+=vt(t)+1;return Fe[n>>2]=i,0};function gr(e){try{var n=ve.getStreamFromFD(e);return a.close(n),0}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return l.errno}}function br(e,n){try{var l=0,i=0,t=0,r=ve.getStreamFromFD(e),s=r.tty?2:a.isDir(r.mode)?3:a.isLink(r.mode)?7:4;return Je[n]=s,ht[n+2>>1]=t,Ve[n+8>>3]=BigInt(l),Ve[n+16>>3]=BigInt(i),0}catch(_){if(typeof a>"u"||_.name!=="ErrnoError")throw _;return _.errno}}var yr=(e,n,l,i)=>{for(var t=0,r=0;r>2],_=Fe[n+4>>2];n+=8;var c=a.read(e,Je,s,_,i);if(c<0)return-1;if(t+=c,c<_)break}return t};function qr(e,n,l,i){try{var t=yr(ve.getStreamFromFD(e),n,l);return Fe[i>>2]=t,0}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return r.errno}}function vr(e,n,l,i){n=bt(n);try{if(isNaN(n))return 61;var t=ve.getStreamFromFD(e);return a.llseek(t,n,l),Ve[i>>3]=BigInt(t.position),t.getdents&&n===0&&l===0&&(t.getdents=null),0}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return r.errno}}function Sr(e){try{var n=ve.getStreamFromFD(e);return n.stream_ops?.fsync?.(n)}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return l.errno}}var wr=(e,n,l,i)=>{for(var t=0,r=0;r>2],_=Fe[n+4>>2];n+=8;var c=a.write(e,Je,s,_,i);if(c<0)return-1;if(t+=c,c<_)break}return t};function Er(e,n,l,i){try{var t=wr(ve.getStreamFromFD(e),n,l);return Fe[i>>2]=t,0}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return r.errno}}if(a.createPreloadedFile=Ln,a.preloadFile=Ht,a.staticInit(),_n(),f.noExitRuntime&&f.noExitRuntime,f.preloadPlugins&&(Vt=f.preloadPlugins),f.print&&(de=f.print),f.printErr&&(Le=f.printErr),f.wasmBinary&&(Ie=f.wasmBinary),f.arguments&&f.arguments,f.thisProgram&&(ge=f.thisProgram),f.preInit)for(typeof f.preInit=="function"&&(f.preInit=[f.preInit]);f.preInit.length>0;)f.preInit.shift()();f.wasmMemory=nt;var Xt;function Ar(e){f._sqlite3_status64=e.sqlite3_status64,f._sqlite3_status=e.sqlite3_status,f._sqlite3_db_status64=e.sqlite3_db_status64,f._sqlite3_msize=e.sqlite3_msize,f._sqlite3_db_status=e.sqlite3_db_status,f._sqlite3_vfs_find=e.sqlite3_vfs_find,f._sqlite3_initialize=e.sqlite3_initialize,f._sqlite3_malloc=e.sqlite3_malloc,f._sqlite3_free=e.sqlite3_free,f._sqlite3_vfs_register=e.sqlite3_vfs_register,f._sqlite3_vfs_unregister=e.sqlite3_vfs_unregister,f._sqlite3_malloc64=e.sqlite3_malloc64,f._sqlite3_realloc=e.sqlite3_realloc,f._sqlite3_realloc64=e.sqlite3_realloc64,f._sqlite3_value_text=e.sqlite3_value_text,f._sqlite3_randomness=e.sqlite3_randomness,f._sqlite3_stricmp=e.sqlite3_stricmp,f._sqlite3_strnicmp=e.sqlite3_strnicmp,f._sqlite3_uri_parameter=e.sqlite3_uri_parameter,f._sqlite3_uri_boolean=e.sqlite3_uri_boolean,f._sqlite3_serialize=e.sqlite3_serialize,f._sqlite3_prepare_v2=e.sqlite3_prepare_v2,f._sqlite3_step=e.sqlite3_step,f._sqlite3_column_int64=e.sqlite3_column_int64,f._sqlite3_reset=e.sqlite3_reset,f._sqlite3_exec=e.sqlite3_exec,f._sqlite3_column_int=e.sqlite3_column_int,f._sqlite3_finalize=e.sqlite3_finalize,f._sqlite3_file_control=e.sqlite3_file_control,f._sqlite3_column_name=e.sqlite3_column_name,f._sqlite3_column_text=e.sqlite3_column_text,f._sqlite3_column_type=e.sqlite3_column_type,f._sqlite3_errmsg=e.sqlite3_errmsg,f._sqlite3_deserialize=e.sqlite3_deserialize,f._sqlite3_clear_bindings=e.sqlite3_clear_bindings,f._sqlite3_value_blob=e.sqlite3_value_blob,f._sqlite3_value_bytes=e.sqlite3_value_bytes,f._sqlite3_value_double=e.sqlite3_value_double,f._sqlite3_value_int=e.sqlite3_value_int,f._sqlite3_value_int64=e.sqlite3_value_int64,f._sqlite3_value_subtype=e.sqlite3_value_subtype,f._sqlite3_value_pointer=e.sqlite3_value_pointer,f._sqlite3_value_type=e.sqlite3_value_type,f._sqlite3_value_nochange=e.sqlite3_value_nochange,f._sqlite3_value_frombind=e.sqlite3_value_frombind,f._sqlite3_value_dup=e.sqlite3_value_dup,f._sqlite3_value_free=e.sqlite3_value_free,f._sqlite3_result_blob=e.sqlite3_result_blob,f._sqlite3_result_error_toobig=e.sqlite3_result_error_toobig,f._sqlite3_result_error_nomem=e.sqlite3_result_error_nomem,f._sqlite3_result_double=e.sqlite3_result_double,f._sqlite3_result_error=e.sqlite3_result_error,f._sqlite3_result_int=e.sqlite3_result_int,f._sqlite3_result_int64=e.sqlite3_result_int64,f._sqlite3_result_null=e.sqlite3_result_null,f._sqlite3_result_pointer=e.sqlite3_result_pointer,f._sqlite3_result_subtype=e.sqlite3_result_subtype,f._sqlite3_result_text=e.sqlite3_result_text,f._sqlite3_result_zeroblob=e.sqlite3_result_zeroblob,f._sqlite3_result_zeroblob64=e.sqlite3_result_zeroblob64,f._sqlite3_result_error_code=e.sqlite3_result_error_code,f._sqlite3_user_data=e.sqlite3_user_data,f._sqlite3_context_db_handle=e.sqlite3_context_db_handle,f._sqlite3_vtab_nochange=e.sqlite3_vtab_nochange,f._sqlite3_vtab_in_first=e.sqlite3_vtab_in_first,f._sqlite3_vtab_in_next=e.sqlite3_vtab_in_next,f._sqlite3_aggregate_context=e.sqlite3_aggregate_context,f._sqlite3_get_auxdata=e.sqlite3_get_auxdata,f._sqlite3_set_auxdata=e.sqlite3_set_auxdata,f._sqlite3_column_count=e.sqlite3_column_count,f._sqlite3_data_count=e.sqlite3_data_count,f._sqlite3_column_blob=e.sqlite3_column_blob,f._sqlite3_column_bytes=e.sqlite3_column_bytes,f._sqlite3_column_double=e.sqlite3_column_double,f._sqlite3_column_value=e.sqlite3_column_value,f._sqlite3_column_decltype=e.sqlite3_column_decltype,f._sqlite3_column_database_name=e.sqlite3_column_database_name,f._sqlite3_column_table_name=e.sqlite3_column_table_name,f._sqlite3_column_origin_name=e.sqlite3_column_origin_name,f._sqlite3_bind_blob=e.sqlite3_bind_blob,f._sqlite3_bind_double=e.sqlite3_bind_double,f._sqlite3_bind_int=e.sqlite3_bind_int,f._sqlite3_bind_int64=e.sqlite3_bind_int64,f._sqlite3_bind_null=e.sqlite3_bind_null,f._sqlite3_bind_pointer=e.sqlite3_bind_pointer,f._sqlite3_bind_text=e.sqlite3_bind_text,f._sqlite3_bind_zeroblob=e.sqlite3_bind_zeroblob,f._sqlite3_bind_parameter_count=e.sqlite3_bind_parameter_count,f._sqlite3_bind_parameter_name=e.sqlite3_bind_parameter_name,f._sqlite3_bind_parameter_index=e.sqlite3_bind_parameter_index,f._sqlite3_db_handle=e.sqlite3_db_handle,f._sqlite3_stmt_readonly=e.sqlite3_stmt_readonly,f._sqlite3_stmt_isexplain=e.sqlite3_stmt_isexplain,f._sqlite3_stmt_explain=e.sqlite3_stmt_explain,f._sqlite3_stmt_busy=e.sqlite3_stmt_busy,f._sqlite3_next_stmt=e.sqlite3_next_stmt,f._sqlite3_stmt_status=e.sqlite3_stmt_status,f._sqlite3_sql=e.sqlite3_sql,f._sqlite3_expanded_sql=e.sqlite3_expanded_sql,f._sqlite3_preupdate_old=e.sqlite3_preupdate_old,f._sqlite3_preupdate_count=e.sqlite3_preupdate_count,f._sqlite3_preupdate_depth=e.sqlite3_preupdate_depth,f._sqlite3_preupdate_blobwrite=e.sqlite3_preupdate_blobwrite,f._sqlite3_preupdate_new=e.sqlite3_preupdate_new,f._sqlite3_value_numeric_type=e.sqlite3_value_numeric_type,f._sqlite3_set_authorizer=e.sqlite3_set_authorizer,f._sqlite3_strglob=e.sqlite3_strglob,f._sqlite3_strlike=e.sqlite3_strlike,f._sqlite3_auto_extension=e.sqlite3_auto_extension,f._sqlite3_cancel_auto_extension=e.sqlite3_cancel_auto_extension,f._sqlite3_reset_auto_extension=e.sqlite3_reset_auto_extension,f._sqlite3_prepare_v3=e.sqlite3_prepare_v3,f._sqlite3_create_module=e.sqlite3_create_module,f._sqlite3_create_module_v2=e.sqlite3_create_module_v2,f._sqlite3_drop_modules=e.sqlite3_drop_modules,f._sqlite3_declare_vtab=e.sqlite3_declare_vtab,f._sqlite3_vtab_on_conflict=e.sqlite3_vtab_on_conflict,f._sqlite3_vtab_collation=e.sqlite3_vtab_collation,f._sqlite3_vtab_in=e.sqlite3_vtab_in,f._sqlite3_vtab_rhs_value=e.sqlite3_vtab_rhs_value,f._sqlite3_vtab_distinct=e.sqlite3_vtab_distinct,f._sqlite3_keyword_name=e.sqlite3_keyword_name,f._sqlite3_keyword_count=e.sqlite3_keyword_count,f._sqlite3_keyword_check=e.sqlite3_keyword_check,f._sqlite3_complete=e.sqlite3_complete,f._sqlite3_libversion=e.sqlite3_libversion,f._sqlite3_libversion_number=e.sqlite3_libversion_number,f._sqlite3_shutdown=e.sqlite3_shutdown,f._sqlite3_last_insert_rowid=e.sqlite3_last_insert_rowid,f._sqlite3_set_last_insert_rowid=e.sqlite3_set_last_insert_rowid,f._sqlite3_changes64=e.sqlite3_changes64,f._sqlite3_changes=e.sqlite3_changes,f._sqlite3_total_changes64=e.sqlite3_total_changes64,f._sqlite3_total_changes=e.sqlite3_total_changes,f._sqlite3_txn_state=e.sqlite3_txn_state,f._sqlite3_close_v2=e.sqlite3_close_v2,f._sqlite3_busy_handler=e.sqlite3_busy_handler,f._sqlite3_progress_handler=e.sqlite3_progress_handler,f._sqlite3_busy_timeout=e.sqlite3_busy_timeout,f._sqlite3_interrupt=e.sqlite3_interrupt,f._sqlite3_is_interrupted=e.sqlite3_is_interrupted,f._sqlite3_create_function=e.sqlite3_create_function,f._sqlite3_create_function_v2=e.sqlite3_create_function_v2,f._sqlite3_create_window_function=e.sqlite3_create_window_function,f._sqlite3_overload_function=e.sqlite3_overload_function,f._sqlite3_trace_v2=e.sqlite3_trace_v2,f._sqlite3_commit_hook=e.sqlite3_commit_hook,f._sqlite3_update_hook=e.sqlite3_update_hook,f._sqlite3_rollback_hook=e.sqlite3_rollback_hook,f._sqlite3_preupdate_hook=e.sqlite3_preupdate_hook,f._sqlite3_set_errmsg=e.sqlite3_set_errmsg,f._sqlite3_error_offset=e.sqlite3_error_offset,f._sqlite3_errcode=e.sqlite3_errcode,f._sqlite3_extended_errcode=e.sqlite3_extended_errcode,f._sqlite3_errstr=e.sqlite3_errstr,f._sqlite3_limit=e.sqlite3_limit,f._sqlite3_open=e.sqlite3_open,f._sqlite3_open_v2=e.sqlite3_open_v2,f._sqlite3_create_collation=e.sqlite3_create_collation,f._sqlite3_create_collation_v2=e.sqlite3_create_collation_v2,f._sqlite3_collation_needed=e.sqlite3_collation_needed,f._sqlite3_get_autocommit=e.sqlite3_get_autocommit,f._sqlite3_table_column_metadata=e.sqlite3_table_column_metadata,f._sqlite3_extended_result_codes=e.sqlite3_extended_result_codes,f._sqlite3_uri_key=e.sqlite3_uri_key,f._sqlite3_uri_int64=e.sqlite3_uri_int64,f._sqlite3_db_name=e.sqlite3_db_name,f._sqlite3_db_filename=e.sqlite3_db_filename,f._sqlite3_db_readonly=e.sqlite3_db_readonly,f._sqlite3_compileoption_used=e.sqlite3_compileoption_used,f._sqlite3_compileoption_get=e.sqlite3_compileoption_get,f._sqlite3session_diff=e.sqlite3session_diff,f._sqlite3session_attach=e.sqlite3session_attach,f._sqlite3session_create=e.sqlite3session_create,f._sqlite3session_delete=e.sqlite3session_delete,f._sqlite3session_table_filter=e.sqlite3session_table_filter,f._sqlite3session_changeset=e.sqlite3session_changeset,f._sqlite3session_changeset_strm=e.sqlite3session_changeset_strm,f._sqlite3session_patchset_strm=e.sqlite3session_patchset_strm,f._sqlite3session_patchset=e.sqlite3session_patchset,f._sqlite3session_enable=e.sqlite3session_enable,f._sqlite3session_indirect=e.sqlite3session_indirect,f._sqlite3session_isempty=e.sqlite3session_isempty,f._sqlite3session_memory_used=e.sqlite3session_memory_used,f._sqlite3session_object_config=e.sqlite3session_object_config,f._sqlite3session_changeset_size=e.sqlite3session_changeset_size,f._sqlite3changeset_start=e.sqlite3changeset_start,f._sqlite3changeset_start_v2=e.sqlite3changeset_start_v2,f._sqlite3changeset_start_strm=e.sqlite3changeset_start_strm,f._sqlite3changeset_start_v2_strm=e.sqlite3changeset_start_v2_strm,f._sqlite3changeset_next=e.sqlite3changeset_next,f._sqlite3changeset_op=e.sqlite3changeset_op,f._sqlite3changeset_pk=e.sqlite3changeset_pk,f._sqlite3changeset_old=e.sqlite3changeset_old,f._sqlite3changeset_new=e.sqlite3changeset_new,f._sqlite3changeset_conflict=e.sqlite3changeset_conflict,f._sqlite3changeset_fk_conflicts=e.sqlite3changeset_fk_conflicts,f._sqlite3changeset_finalize=e.sqlite3changeset_finalize,f._sqlite3changeset_invert=e.sqlite3changeset_invert,f._sqlite3changeset_invert_strm=e.sqlite3changeset_invert_strm,f._sqlite3changeset_apply_v2=e.sqlite3changeset_apply_v2,f._sqlite3changeset_apply_v3=e.sqlite3changeset_apply_v3,f._sqlite3changeset_apply=e.sqlite3changeset_apply,f._sqlite3changeset_apply_v3_strm=e.sqlite3changeset_apply_v3_strm,f._sqlite3changeset_apply_v2_strm=e.sqlite3changeset_apply_v2_strm,f._sqlite3changeset_apply_strm=e.sqlite3changeset_apply_strm,f._sqlite3changegroup_new=e.sqlite3changegroup_new,f._sqlite3changegroup_add=e.sqlite3changegroup_add,f._sqlite3changegroup_output=e.sqlite3changegroup_output,f._sqlite3changegroup_add_strm=e.sqlite3changegroup_add_strm,f._sqlite3changegroup_output_strm=e.sqlite3changegroup_output_strm,f._sqlite3changegroup_delete=e.sqlite3changegroup_delete,f._sqlite3changeset_concat=e.sqlite3changeset_concat,f._sqlite3changeset_concat_strm=e.sqlite3changeset_concat_strm,f._sqlite3session_config=e.sqlite3session_config,f._sqlite3_sourceid=e.sqlite3_sourceid,f._sqlite3__wasm_pstack_ptr=e.sqlite3__wasm_pstack_ptr,f._sqlite3__wasm_pstack_restore=e.sqlite3__wasm_pstack_restore,f._sqlite3__wasm_pstack_alloc=e.sqlite3__wasm_pstack_alloc,f._sqlite3__wasm_pstack_remaining=e.sqlite3__wasm_pstack_remaining,f._sqlite3__wasm_pstack_quota=e.sqlite3__wasm_pstack_quota,f._sqlite3__wasm_test_struct=e.sqlite3__wasm_test_struct,f._sqlite3__wasm_enum_json=e.sqlite3__wasm_enum_json,f._sqlite3__wasm_vfs_unlink=e.sqlite3__wasm_vfs_unlink,f._sqlite3__wasm_db_vfs=e.sqlite3__wasm_db_vfs,f._sqlite3__wasm_db_reset=e.sqlite3__wasm_db_reset,f._sqlite3__wasm_db_export_chunked=e.sqlite3__wasm_db_export_chunked,f._sqlite3__wasm_db_serialize=e.sqlite3__wasm_db_serialize,f._sqlite3__wasm_vfs_create_file=e.sqlite3__wasm_vfs_create_file,f._sqlite3__wasm_posix_create_file=e.sqlite3__wasm_posix_create_file,f._sqlite3__wasm_kvvfsMakeKey=e.sqlite3__wasm_kvvfsMakeKey,f._sqlite3__wasm_kvvfs_methods=e.sqlite3__wasm_kvvfs_methods,f._sqlite3__wasm_vtab_config=e.sqlite3__wasm_vtab_config,f._sqlite3__wasm_db_config_ip=e.sqlite3__wasm_db_config_ip,f._sqlite3__wasm_db_config_pii=e.sqlite3__wasm_db_config_pii,f._sqlite3__wasm_db_config_s=e.sqlite3__wasm_db_config_s,f._sqlite3__wasm_config_i=e.sqlite3__wasm_config_i,f._sqlite3__wasm_config_ii=e.sqlite3__wasm_config_ii,f._sqlite3__wasm_config_j=e.sqlite3__wasm_config_j,f._sqlite3__wasm_qfmt_token=e.sqlite3__wasm_qfmt_token,f._sqlite3__wasm_kvvfs_decode=e.sqlite3__wasm_kvvfs_decode,f._sqlite3__wasm_kvvfs_encode=e.sqlite3__wasm_kvvfs_encode,f._sqlite3__wasm_init_wasmfs=e.sqlite3__wasm_init_wasmfs,f._sqlite3__wasm_test_intptr=e.sqlite3__wasm_test_intptr,f._sqlite3__wasm_test_voidptr=e.sqlite3__wasm_test_voidptr,f._sqlite3__wasm_test_int64_max=e.sqlite3__wasm_test_int64_max,f._sqlite3__wasm_test_int64_min=e.sqlite3__wasm_test_int64_min,f._sqlite3__wasm_test_int64_times2=e.sqlite3__wasm_test_int64_times2,f._sqlite3__wasm_test_int64_minmax=e.sqlite3__wasm_test_int64_minmax,f._sqlite3__wasm_test_int64ptr=e.sqlite3__wasm_test_int64ptr,f._sqlite3__wasm_test_stack_overflow=e.sqlite3__wasm_test_stack_overflow,f._sqlite3__wasm_test_str_hello=e.sqlite3__wasm_test_str_hello,f._sqlite3__wasm_SQLTester_strglob=e.sqlite3__wasm_SQLTester_strglob,f._malloc=e.malloc,f._free=e.free,f._realloc=e.realloc,Xt=e.emscripten_builtin_memalign,e._emscripten_stack_restore,e._emscripten_stack_alloc,e.emscripten_stack_get_current,e.__indirect_function_table}var Yt={__syscall_chmod:Nn,__syscall_faccessat:Rn,__syscall_fchmod:Dn,__syscall_fchown32:jn,__syscall_fcntl64:Mn,__syscall_fstat64:zn,__syscall_ftruncate64:Qn,__syscall_getcwd:Un,__syscall_ioctl:Vn,__syscall_lstat64:Hn,__syscall_mkdirat:Gn,__syscall_newfstatat:$n,__syscall_openat:Kn,__syscall_readlinkat:Jn,__syscall_rmdir:Xn,__syscall_stat64:Yn,__syscall_unlinkat:Zn,__syscall_utimensat:er,_localtime_js:sr,_mmap_js:or,_munmap_js:lr,_tzset_js:ar,clock_time_get:ur,emscripten_date_now:Kt,emscripten_get_heap_max:_r,emscripten_get_now:$t,emscripten_resize_heap:dr,environ_get:hr,environ_sizes_get:mr,fd_close:gr,fd_fdstat_get:br,fd_read:qr,fd_seek:vr,fd_sync:Sr,fd_write:Er,memory:nt};function Ft(){if(ot>0){gt=Ft;return}if(fn(),ot>0){gt=Ft;return}function e(){f.calledRun=!0,!Ee&&(dn(),Ce?.(f),f.onRuntimeInitialized?.(),pn())}f.setStatus?(f.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>f.setStatus(""),1),e()},1)):e()}var dt=await vn();return Ft(),f.runSQLite3PostLoadInit=async function(e,n,l){delete n.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function i(t=globalThis.sqlite3ApiConfig||i.defaultConfig){if(i.sqlite3)return(i.sqlite3.config||console).warn("sqlite3ApiBootstrap() called multiple times.","Config and external initializers are ignored on calls after the first."),i.sqlite3;const r=(...d)=>Object.assign(Object.create(null),...d),s=r({exports:void 0,memory:void 0,bigIntEnabled:!!globalThis.BigInt64Array,debug:console.debug.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),log:console.log.bind(console),wasmfsOpfsDir:"/opfs",useStdAlloc:!1},t);Object.assign(s,{allocExportName:s.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:s.useStdAlloc?"free":"sqlite3_free",reallocExportName:s.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach(d=>{typeof s[d]=="function"&&(s[d]=s[d]())});const _=r(),c=r(),b=d=>_.sqlite3_js_rc_str&&_.sqlite3_js_rc_str(d)||"Unknown result code #"+d,M=d=>typeof d=="number"&&d===(d|0)&&d<=2147483647&&d>=-2147483648;class I extends Error{constructor(...y){let F;if(y.length)if(M(y[0]))if(F=y[0],y.length===1)super(b(y[0]));else{const W=b(F);typeof y[1]=="object"?super(W,y[1]):(y[0]=W+":",super(y.join(" ")))}else y.length===2&&typeof y[1]=="object"?super(...y):super(y.join(" "));this.resultCode=F||_.SQLITE_ERROR,this.name="SQLite3Error"}}I.toss=(...d)=>{throw new I(...d)};const S=I.toss;s.wasmfsOpfsDir&&!/^\/[^/]+$/.test(s.wasmfsOpfsDir)&&S("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");const w=function d(y){return d._max||(d._max=BigInt("0x7fffffffffffffff"),d._min=~d._max),y>=d._min&&y<=d._max},x=d=>d>=-2147483647n-1n&&d<=2147483647n,L=function d(y){return d._min||(d._min=Number.MIN_SAFE_INTEGER,d._max=Number.MAX_SAFE_INTEGER),y>=d._min&&y<=d._max},H=d=>d&&d.constructor&&M(d.constructor.BYTES_PER_ELEMENT)?d:!1,g=d=>d&&(d instanceof Uint8Array||d instanceof Int8Array||d instanceof ArrayBuffer),h=d=>d&&(d instanceof Uint8Array||d instanceof Int8Array||d instanceof ArrayBuffer),D=d=>g(d)||S("Value is not of a supported TypedArray type."),Q=function(d){return h(d)?c.typedArrayToString(d instanceof ArrayBuffer?new Uint8Array(d):d,0,d.length):Array.isArray(d)?d.join(""):(c.isPtr(d)&&(d=c.cstrToJs(d)),d)};class A extends Error{constructor(...y){y.length===2&&typeof y[1]=="object"?super(...y):y.length?super(y.join(" ")):super("Allocation failed."),this.resultCode=_.SQLITE_NOMEM,this.name="WasmAllocError"}}A.toss=(...d)=>{throw new A(...d)},Object.assign(_,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(d,y,F,W,P,X,ee,Z,te)=>{},sqlite3_create_function:(d,y,F,W,P,X,ee,Z)=>{},sqlite3_create_window_function:(d,y,F,W,P,X,ee,Z,te,E)=>{},sqlite3_prepare_v3:(d,y,F,W,P,X)=>{},sqlite3_prepare_v2:(d,y,F,W,P)=>{},sqlite3_exec:(d,y,F,W,P)=>{},sqlite3_randomness:(d,y)=>{}});const N={affirmBindableTypedArray:D,flexibleString:Q,bigIntFits32:x,bigIntFits64:w,bigIntFitsDouble:L,isBindableTypedArray:g,isInt32:M,isSQLableTypedArray:h,isTypedArray:H,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...d){throw new Error(d.join(" "))},toss3:S,typedArrayPart:c.typedArrayPart,nu:r,assert:function(d,y){d||N.toss("Assertion failed:",y)},affirmDbHeader:function(d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));const y="SQLite format 3";15>d.byteLength&&S("Input does not contain an SQLite3 database header.");for(let F=0;F<15;++F)y.charCodeAt(F)!==d[F]&&S("Input does not contain an SQLite3 database header.")},affirmIsDb:function(d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));const y=d.byteLength;(y<512||y%512!==0)&&S("Byte array size",y,"is invalid for an SQLite3 db."),N.affirmDbHeader(d)}};Object.assign(c,{exports:s.exports||S("Missing API config.exports (WASM module exports)."),memory:s.memory||s.exports.memory||S("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof s.exports.sqlite3_libversion()=="number"?4:8,bigIntEnabled:!!s.bigIntEnabled,functionTable:s.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),c.allocFromTypedArray=function(d){d instanceof ArrayBuffer&&(d=new Uint8Array(d)),D(d);const y=c.alloc(d.byteLength||1);return c.heapForSize(d.constructor).set(d.byteLength?d:[0],Number(y)),y};{const d=s.allocExportName,y=s.deallocExportName,F=s.reallocExportName;for(const W of[d,y,F])c.exports[W]instanceof Function||S("Missing required exports[",W,"] function.");c.alloc=function W(P){return W.impl(P)||A.toss("Failed to allocate",P," bytes.")},c.alloc.impl=c.exports[d],c.realloc=function W(P,X){const ee=W.impl(c.ptr.coerce(P),X);return X?ee||A.toss("Failed to reallocate",X," bytes."):c.ptr.null},c.realloc.impl=c.exports[F],c.dealloc=function W(P){W.impl(c.ptr.coerce(P))},c.dealloc.impl=c.exports[y]}c.compileOptionUsed=function d(y){if(arguments.length){if(Array.isArray(y)){const F=r();return y.forEach(W=>{F[W]=_.sqlite3_compileoption_used(W)}),F}else if(typeof y=="object")return Object.keys(y).forEach(F=>{y[F]=_.sqlite3_compileoption_used(F)}),y}else{if(d._result)return d._result;d._opt||(d._rx=/^([^=]+)=(.+)/,d._rxInt=/^-?\d+$/,d._opt=function(ee,Z){const te=d._rx.exec(ee);Z[0]=te?te[1]:ee,Z[1]=te?d._rxInt.test(te[2])?+te[2]:te[2]:!0});const F=r(),W=[0,0];let P=0,X;for(;X=_.sqlite3_compileoption_get(P++);)d._opt(X,W),F[W[0]]=W[1];return d._result=F}return typeof y=="string"?!!_.sqlite3_compileoption_used(y):!1},c.pstack=r({restore:c.exports.sqlite3__wasm_pstack_restore,alloc:function(d){return typeof d=="string"&&!(d=c.sizeofIR(d))&&A.toss("Invalid value for pstack.alloc(",arguments[0],")"),c.exports.sqlite3__wasm_pstack_alloc(d)||A.toss("Could not allocate",d,"bytes from the pstack.")},allocChunks:function(d,y){typeof y=="string"&&!(y=c.sizeofIR(y))&&A.toss("Invalid size value for allocChunks(",arguments[1],")");const F=c.pstack.alloc(d*y),W=[F];let P=1,X=y;for(;Pd===1?c.pstack.alloc(y?8:c.ptr.size):c.pstack.allocChunks(d,y?8:c.ptr.size),call:function(d){const y=c.pstack.pointer;try{return d(J)}finally{c.pstack.restore(y)}}}),Object.defineProperties(c.pstack,{pointer:{configurable:!1,iterable:!0,writeable:!1,get:c.exports.sqlite3__wasm_pstack_ptr},quota:{configurable:!1,iterable:!0,writeable:!1,get:c.exports.sqlite3__wasm_pstack_quota},remaining:{configurable:!1,iterable:!0,writeable:!1,get:c.exports.sqlite3__wasm_pstack_remaining}}),_.sqlite3_randomness=(...d)=>{if(d.length===1&&N.isTypedArray(d[0])&&d[0].BYTES_PER_ELEMENT===1){const y=d[0];if(y.byteLength===0)return c.exports.sqlite3_randomness(0,c.ptr.null),y;const F=c.pstack.pointer;try{let W=y.byteLength,P=0;const X=c.exports.sqlite3_randomness,ee=c.heap8u(),Z=W<512?W:512,te=c.pstack.alloc(Z);do{const E=W>Z?Z:W;X(E,te),y.set(c.typedArrayPart(ee,te,c.ptr.add(te,E)),P),W-=E,P+=E}while(W>0)}catch(W){s.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",W)}finally{c.pstack.restore(F)}return y}c.exports.sqlite3_randomness(...d)},_.sqlite3_wasmfs_opfs_dir=(function(){if(this.dir!==void 0)return this.dir;const d=s.wasmfsOpfsDir;if(!d||!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!c.exports.sqlite3__wasm_init_wasmfs)return this.dir="";try{return d&&c.xCallWrapped("sqlite3__wasm_init_wasmfs","i32",["string"],d)===0?this.dir=d:this.dir=""}catch{return this.dir=""}}).bind(r()),_.sqlite3_wasmfs_filename_is_persistent=function(d){const y=_.sqlite3_wasmfs_opfs_dir();return y&&d?d.startsWith(y+"/"):!1},_.sqlite3_js_db_uses_vfs=function(d,y,F=0){try{const W=_.sqlite3_vfs_find(y);return W?d?W===_.sqlite3_js_db_vfs(d,F)?W:!1:W===_.sqlite3_vfs_find(0)?W:!1:!1}catch{return!1}},_.sqlite3_js_vfs_list=function(){const d=[];let y=_.sqlite3_vfs_find(c.ptr.null);for(;y;){const F=new _.sqlite3_vfs(y);d.push(c.cstrToJs(F.$zName)),y=F.$pNext,F.dispose()}return d},_.sqlite3_js_db_export=function(d,y=0){d=c.xWrap.testConvertArg("sqlite3*",d),d||S("Invalid sqlite3* argument."),c.bigIntEnabled||S("BigInt support is not enabled.");const F=c.scopedAllocPush();let W;try{const P=c.scopedAlloc(8+c.ptr.size),X=c.ptr.add(P,8),ee=y?c.isPtr(y)?y:c.scopedAllocCString(""+y):c.ptr.null;let Z=c.exports.sqlite3__wasm_db_serialize(d,ee,X,P,0);Z&&S("Database serialization failed with code",J.capi.sqlite3_js_rc_str(Z)),W=c.peekPtr(X);const te=c.peek(P,"i64");return Z=te?c.heap8u().slice(Number(W),Number(W)+Number(te)):new Uint8Array,Z}finally{W&&c.exports.sqlite3_free(W),c.scopedAllocPop(F)}},_.sqlite3_js_db_vfs=(d,y=c.ptr.null)=>N.sqlite3__wasm_db_vfs(d,y),_.sqlite3_js_aggregate_context=(d,y)=>_.sqlite3_aggregate_context(d,y)||(y?A.toss("Cannot allocate",y,"bytes for sqlite3_aggregate_context()"):0),_.sqlite3_js_posix_create_file=function(d,y,F){let W;y&&c.isPtr(y)?W=y:y instanceof ArrayBuffer||y instanceof Uint8Array?(W=c.allocFromTypedArray(y),(arguments.length<3||!N.isInt32(F)||F<0)&&(F=y.byteLength)):I.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{(!N.isInt32(F)||F<0)&&I.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");const P=N.sqlite3__wasm_posix_create_file(d,W,F);P&&I.toss("Creation of file failed with sqlite3 result code",_.sqlite3_js_rc_str(P))}finally{W&&W!==y&&c.dealloc(W)}},_.sqlite3_js_vfs_create_file=function(d,y,F,W){s.warn("sqlite3_js_vfs_create_file() is deprecated and","should be avoided because it can lead to C-level crashes.","See its documentation for alternatives.");let P;F?c.isPtr(F)?P=F:(F instanceof ArrayBuffer&&(F=new Uint8Array(F)),F instanceof Uint8Array?(P=c.allocFromTypedArray(F),(arguments.length<4||!N.isInt32(W)||W<0)&&(W=F.byteLength)):I.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().")):P=0,(!N.isInt32(W)||W<0)&&(P&&P!==F&&c.dealloc(P),I.toss("Invalid 4th argument for sqlite3_js_vfs_create_file()."));try{const X=N.sqlite3__wasm_vfs_create_file(d,y,P,W);X&&I.toss("Creation of file failed with sqlite3 result code",_.sqlite3_js_rc_str(X))}finally{P&&P!==F&&c.dealloc(P)}},_.sqlite3_js_sql_to_string=d=>{if(typeof d=="string")return d;const y=Q(v);return y===v?void 0:y},_.sqlite3_db_config=(function(d,y,...F){switch(y){case _.SQLITE_DBCONFIG_ENABLE_FKEY:case _.SQLITE_DBCONFIG_ENABLE_TRIGGER:case _.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:case _.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:case _.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:case _.SQLITE_DBCONFIG_ENABLE_QPSG:case _.SQLITE_DBCONFIG_TRIGGER_EQP:case _.SQLITE_DBCONFIG_RESET_DATABASE:case _.SQLITE_DBCONFIG_DEFENSIVE:case _.SQLITE_DBCONFIG_WRITABLE_SCHEMA:case _.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:case _.SQLITE_DBCONFIG_DQS_DML:case _.SQLITE_DBCONFIG_DQS_DDL:case _.SQLITE_DBCONFIG_ENABLE_VIEW:case _.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:case _.SQLITE_DBCONFIG_TRUSTED_SCHEMA:case _.SQLITE_DBCONFIG_STMT_SCANSTATUS:case _.SQLITE_DBCONFIG_REVERSE_SCANORDER:case _.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE:case _.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE:case _.SQLITE_DBCONFIG_ENABLE_COMMENTS:case _.SQLITE_DBCONFIG_FP_DIGITS:return this.ip||(this.ip=c.xWrap("sqlite3__wasm_db_config_ip","int",["sqlite3*","int","int","*"])),this.ip(d,y,F[0],F[1]||0);case _.SQLITE_DBCONFIG_LOOKASIDE:return this.pii||(this.pii=c.xWrap("sqlite3__wasm_db_config_pii","int",["sqlite3*","int","*","int","int"])),this.pii(d,y,F[0],F[1],F[2]);case _.SQLITE_DBCONFIG_MAINDBNAME:return this.s||(this.s=c.xWrap("sqlite3__wasm_db_config_s","int",["sqlite3*","int","string:static"])),this.s(d,y,F[0]);default:return _.SQLITE_MISUSE}}).bind(r()),_.sqlite3_value_to_js=function(d,y=!0){let F;const W=_.sqlite3_value_type(d);switch(W){case _.SQLITE_INTEGER:c.bigIntEnabled?(F=_.sqlite3_value_int64(d),N.bigIntFitsDouble(F)&&(F=Number(F))):F=_.sqlite3_value_double(d);break;case _.SQLITE_FLOAT:F=_.sqlite3_value_double(d);break;case _.SQLITE_TEXT:F=_.sqlite3_value_text(d);break;case _.SQLITE_BLOB:{const P=_.sqlite3_value_bytes(d),X=_.sqlite3_value_blob(d);P&&!X&&J.WasmAllocError.toss("Cannot allocate memory for blob argument of",P,"byte(s)"),F=P?c.heap8u().slice(Number(X),Number(X)+Number(P)):null;break}case _.SQLITE_NULL:F=null;break;default:y&&S(_.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",W),F=void 0}return F},_.sqlite3_values_to_js=function(d,y,F=!0){let W;const P=[];for(W=0;Wd(y,F,"sqlite3_preupdate_new"),_.sqlite3_preupdate_old_js=(y,F)=>d(y,F,"sqlite3_preupdate_old"),_.sqlite3changeset_new_js=(y,F)=>d(y,F,"sqlite3changeset_new"),_.sqlite3changeset_old_js=(y,F)=>d(y,F,"sqlite3changeset_old")}_.sqlite3_js_retry_busy=function(d,y,F){for(let W=1;W<=d;++W)try{F&&W>1&&F(W);const P=y();if(_.SQLITE_BUSY===P){if(W===d)throw new I(P,["sqlite3_js_retry_busy() max retry attempts (",d,") reached."].join(""));continue}return P}catch(P){if(W(J.__isUnderTest||(delete J.util,delete J.StructBinder,delete J.opfs),J),W=X=>{throw s.error("an async sqlite3 initializer failed:",X),X};if(!y||!y.length)return d.isReady=F().catch(W);y=y.map(X=>X instanceof Function?async ee=>X(J):X),y.push(F);let P=Promise.resolve(J);for(;y.length;)P=P.then(y.shift());return d.isReady=P.catch(W)}).bind(i),scriptInfo:void 0};typeof l<"u"&&(J.__isUnderTest=!!l);try{i.initializers.forEach(d=>{d(J)})}catch(d){throw console.error("sqlite3 bootstrap initializer threw:",d),d}if(delete i.initializers,i.sqlite3=J,typeof e<"u"&&(e.debugModule("sqlite3ApiBootstrap() complete",J),J.scriptInfo=e),J.__isUnderTest){typeof n<"u"&&(J.config.emscripten=n);const d=J.scriptInfo?.instantiateWasm;d&&(J.wasm.module=d.module,J.wasm.instance=d.instance,J.wasm.imports=d.imports)}return delete globalThis.sqlite3ApiConfig,delete globalThis.sqlite3ApiBootstrap,delete i.defaultConfig,J.asyncPostInit().then(d=>(typeof e<"u"&&e.debugModule("sqlite3.asyncPostInit() complete",d),delete d.asyncPostInit,delete d.scriptInfo,delete d.emscripten,d))},globalThis.sqlite3ApiBootstrap.initializers=[],globalThis.sqlite3ApiBootstrap.initializersAsync=[],globalThis.sqlite3ApiBootstrap.defaultConfig=Object.create(null),globalThis.sqlite3ApiBootstrap.sqlite3=void 0,globalThis.sqlite3ApiBootstrap.initializers.push(function(i){i.version={libVersion:"3.53.0",libVersionNumber:3053e3,sourceId:"2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",downloadVersion:353e4,scm:{"sha3-256":"4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",branch:"trunk",tags:"release major-release version-3.53.0",datetime:"2026-04-09T11:41:38.498Z"}}}),globalThis.WhWasmUtilInstaller=function(t){t.bigIntEnabled===void 0&&(t.bigIntEnabled=!!globalThis.BigInt64Array);const r=(...o)=>{throw new Error(o.join(" "))};if(!t.pointerSize&&!t.pointerIR&&t.alloc&&t.dealloc){const o=t.alloc(1);t.pointerSize=typeof o=="bigint"?8:4,t.dealloc(o)}t.pointerSize&&!t.pointerIR&&(t.pointerIR=t.pointerSize===4?"i32":"i64");const s=t.pointerIR??="i32",_=t.pointerSize??=s==="i32"?4:s==="i64"?8:0;delete t.pointerSize,delete t.pointerIR,s!=="i32"&&s!=="i64"?r("Invalid pointerIR:",s):_!==8&&_!==4&&r("Invalid pointerSize:",_);const c=t.bigIntEnabled?o=>BigInt(o||0):o=>r("BigInt support is disabled in this build."),M=_===4?o=>Number(o||0):c,I=M(0),S=function(...o){let u=M(0);for(const p of o)u+=M(p);return u};{const o=Object.create(null);Object.defineProperty(t,"ptr",{enumerable:!0,get:()=>o,set:()=>r("The ptr property is read-only.")}),(function u(p,q){return Object.defineProperty(o,p,{enumerable:!0,get:()=>q,set:()=>r("ptr["+p+"] is read-only.")}),u})("null",I)("size",_)("ir",s)("coerce",M)("add",S)("addn",s===4?S:(...u)=>Number(S(...u)))}t.exports||Object.defineProperty(t,"exports",{enumerable:!0,configurable:!0,get:()=>t.instance?.exports});const w=Object.create(null);w.heapSize=0,w.memory=null,w.freeFuncIndexes=[],w.scopedAlloc=[],w.scopedAlloc.pushPtr=o=>(w.scopedAlloc[w.scopedAlloc.length-1].push(o),o),w.utf8Decoder=new TextDecoder,w.utf8Encoder=new TextEncoder("utf-8"),t.sizeofIR=o=>{switch(o){case"i8":return 1;case"i16":return 2;case"i32":case"f32":case"float":return 4;case"i64":case"f64":case"double":return 8;case"*":return _;default:return(""+o).endsWith("*")?_:void 0}};const x=function(){if(!w.memory)w.memory=t.memory instanceof WebAssembly.Memory?t.memory:t.exports.memory;else if(w.heapSize===w.memory.buffer.byteLength)return w;const o=w.memory.buffer;return w.HEAP8=new Int8Array(o),w.HEAP8U=new Uint8Array(o),w.HEAP16=new Int16Array(o),w.HEAP16U=new Uint16Array(o),w.HEAP32=new Int32Array(o),w.HEAP32U=new Uint32Array(o),w.HEAP32F=new Float32Array(o),w.HEAP64F=new Float64Array(o),t.bigIntEnabled&&(typeof BigInt64Array<"u"?(w.HEAP64=new BigInt64Array(o),w.HEAP64U=new BigUint64Array(o)):r("BigInt support is enabled, but the BigInt64Array type is missing.")),w.heapSize=o.byteLength,w};t.heap8=()=>x().HEAP8,t.heap8u=()=>x().HEAP8U,t.heap16=()=>x().HEAP16,t.heap16u=()=>x().HEAP16U,t.heap32=()=>x().HEAP32,t.heap32u=()=>x().HEAP32U,t.heapForSize=function(o,u=!0){const p=w.memory&&w.heapSize===w.memory.buffer.byteLength?w:x();switch(o){case Int8Array:return p.HEAP8;case Uint8Array:return p.HEAP8U;case Int16Array:return p.HEAP16;case Uint16Array:return p.HEAP16U;case Int32Array:return p.HEAP32;case Uint32Array:return p.HEAP32U;case 8:return u?p.HEAP8U:p.HEAP8;case 16:return u?p.HEAP16U:p.HEAP16;case 32:return u?p.HEAP32U:p.HEAP32;case 64:if(p.HEAP64)return u?p.HEAP64U:p.HEAP64;break;default:if(t.bigIntEnabled){if(o===globalThis.BigUint64Array)return p.HEAP64U;if(o===globalThis.BigInt64Array)return p.HEAP64;break}}r("Invalid heapForSize() size: expecting 8, 16, 32,","or (if BigInt is enabled) 64.")};const L=t.functionTable;delete t.functionTable,t.functionTable=L?()=>L:()=>t.exports.__indirect_function_table,t.functionEntry=function(o){const u=t.functionTable();return o{C<128?R[m](C):R[m](C%128|128,C>>7)},rxJSig:/^(\w)\((\w*)\)$/,sigParams:R=>{const m=o._.rxJSig.exec(R);return m?m[2]:R.substr(1)},letterType:R=>o._.sigTypes[R]||r("Invalid signature letter:",R),pushSigType:(R,m)=>R.push(o._.typeCodes[o._.letterType(m)])}),typeof u=="string"){const R=p;p=u,u=R}const q=o._,z=q.sigParams(p),V=[1,96];q.uleb128Encode(V,"push",z.length);for(const R of z)q.pushSigType(V,R);return p[0]==="v"?V.push(0):(V.push(1),q.pushSigType(V,p[0])),q.uleb128Encode(V,"unshift",V.length),V.unshift(0,97,115,109,1,0,0,0,1),V.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array(V)),{e:{f:u}}).exports.f};const H=function(u,p,q){if(q&&!w.scopedAlloc.length&&r("No scopedAllocPush() scope is active."),typeof u=="string"){const m=p;p=u,u=m}(typeof p!="string"||!(u instanceof Function))&&r("Invalid arguments: expecting (function,signature) or (signature,function).");const z=t.functionTable(),V=M(z.length);let R;for(;(R=w.freeFuncIndexes.pop())&&z.get(R);){R=null;continue}R||(R=M(V),z.grow(M(1)));try{return z.set(R,u),q&&w.scopedAlloc.pushPtr(R),R}catch(m){if(!(m instanceof TypeError))throw R===V&&w.freeFuncIndexes.push(V),m}try{const m=t.jsFuncToWasm(u,p);z.set(R,m),q&&w.scopedAlloc.pushPtr(R)}catch(m){throw R===V&&w.freeFuncIndexes.push(V),m}return R};t.installFunction=(o,u)=>H(o,u,!1),t.scopedInstallFunction=(o,u)=>H(o,u,!0),t.uninstallFunction=function(o){if(!o&&I!==o)return;const u=t.functionTable();w.freeFuncIndexes.push(o);const p=u.get(o);return u.set(o,null),p},t.peek=function(u,p="i8"){p.endsWith("*")&&(p=s);const q=w.memory&&w.heapSize===w.memory.buffer.byteLength?w:x(),z=Array.isArray(u)?[]:void 0;let V;do{switch(z&&(u=arguments[0].shift()),p){case"i1":case"i8":V=q.HEAP8[Number(u)>>0];break;case"i16":V=q.HEAP16[Number(u)>>1];break;case"i32":V=q.HEAP32[Number(u)>>2];break;case"float":case"f32":V=q.HEAP32F[Number(u)>>2];break;case"double":case"f64":V=Number(q.HEAP64F[Number(u)>>3]);break;case"i64":if(q.HEAP64){V=c(q.HEAP64[Number(u)>>3]);break}default:r("Invalid type for peek():",p)}z&&z.push(V)}while(z&&arguments[0].length);return z||V},t.poke=function(o,u,p="i8"){p.endsWith("*")&&(p=s);const q=w.memory&&w.heapSize===w.memory.buffer.byteLength?w:x();for(const z of Array.isArray(o)?o:[o])switch(p){case"i1":case"i8":q.HEAP8[Number(z)>>0]=u;continue;case"i16":q.HEAP16[Number(z)>>1]=u;continue;case"i32":q.HEAP32[Number(z)>>2]=u;continue;case"float":case"f32":q.HEAP32F[Number(z)>>2]=u;continue;case"double":case"f64":q.HEAP64F[Number(z)>>3]=u;continue;case"i64":if(q.HEAP64){q.HEAP64[Number(z)>>3]=c(u);continue}default:r("Invalid type for poke(): "+p)}return this},t.peekPtr=(...o)=>t.peek(o.length===1?o[0]:o,s),t.pokePtr=(o,u=0)=>t.poke(o,u,s),t.peek8=(...o)=>t.peek(o.length===1?o[0]:o,"i8"),t.poke8=(o,u)=>t.poke(o,u,"i8"),t.peek16=(...o)=>t.peek(o.length===1?o[0]:o,"i16"),t.poke16=(o,u)=>t.poke(o,u,"i16"),t.peek32=(...o)=>t.peek(o.length===1?o[0]:o,"i32"),t.poke32=(o,u)=>t.poke(o,u,"i32"),t.peek64=(...o)=>t.peek(o.length===1?o[0]:o,"i64"),t.poke64=(o,u)=>t.poke(o,u,"i64"),t.peek32f=(...o)=>t.peek(o.length===1?o[0]:o,"f32"),t.poke32f=(o,u)=>t.poke(o,u,"f32"),t.peek64f=(...o)=>t.peek(o.length===1?o[0]:o,"f64"),t.poke64f=(o,u)=>t.poke(o,u,"f64"),t.getMemValue=t.peek,t.getPtrValue=t.peekPtr,t.setMemValue=t.poke,t.setPtrValue=t.pokePtr,t.isPtr32=o=>typeof o=="number"&&o>=0&&o===(o|0),t.isPtr64=o=>typeof o=="bigint"?o>=0:t.isPtr32(o),t.isPtr=_===4?t.isPtr32:t.isPtr64,t.cstrlen=function(o){if(!o||!t.isPtr(o))return null;o=Number(o);const u=x().HEAP8U;let p=o;for(;u[p]!==0;++p);return p-o};const g=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,h=o=>o.buffer instanceof g;t.isSharedTypedArray=h;const D=(o,u,p)=>(_===8&&(typeof u=="bigint"&&(u=Number(u)),typeof p=="bigint"&&(p=Number(p))),h(o)?o.slice(u,p):o.subarray(u,p));t.typedArrayPart=D;const Q=(o,u,p)=>w.utf8Decoder.decode(D(o,u,p));t.typedArrayToString=Q,t.cstrToJs=function(o){const u=t.cstrlen(o);return u?Q(x().HEAP8U,Number(o),Number(o)+u):u===null?u:""},t.jstrlen=function(o){if(typeof o!="string")return null;const u=o.length;let p=0;for(let q=0;q=55296&&z<=57343&&(z=65536+((z&1023)<<10)|o.charCodeAt(++q)&1023),z<=127?++p:z<=2047?p+=2:z<=65535?p+=3:p+=4}return p},t.jstrcpy=function(o,u,p=0,q=-1,z=!0){if((!u||!(u instanceof Int8Array)&&!(u instanceof Uint8Array))&&r("jstrcpy() target must be an Int8Array or Uint8Array."),q=Number(q),p=Number(p),q<0&&(q=u.length-p),!(q>0)||!(p>=0))return 0;let V=0,R=o.length;const m=p,C=p+q-(z?1:0);for(;V=55296&&B<=57343&&(B=65536+((B&1023)<<10)|o.charCodeAt(++V)&1023),B<=127){if(p>=C)break;u[p++]=B}else if(B<=2047){if(p+1>=C)break;u[p++]=192|B>>6,u[p++]=128|B&63}else if(B<=65535){if(p+2>=C)break;u[p++]=224|B>>12,u[p++]=128|B>>6&63,u[p++]=128|B&63}else{if(p+3>=C)break;u[p++]=240|B>>18,u[p++]=128|B>>12&63,u[p++]=128|B>>6&63,u[p++]=128|B&63}}return z&&(u[p++]=0),p-m},t.cstrncpy=function(o,u,p){if((!o||!u)&&r("cstrncpy() does not accept NULL strings."),p<0)p=t.cstrlen(strPtr)+1;else if(!(p>0))return 0;const q=t.heap8u();let z=0,V;const R=Number(o),m=Number(u);for(;zw.utf8Encoder.encode(u?o+"\0":o);const A=(o,u)=>{(!(o.alloc instanceof Function)||!(o.dealloc instanceof Function))&&r("Object is missing alloc() and/or dealloc() function(s)","required by",u+"().")},N=function(o,u,p,q){if(A(t,q),typeof o!="string")return null;const z=w.utf8Encoder.encode(o),V=p(z.length+1);let R=V;try{const m=x().HEAP8U;return m.set(z,Number(V)),m[S(V,z.length)]=0,R=I,u?[V,z.length]:V}finally{R&&t.dealloc(R)}};t.allocCString=(o,u=!1)=>N(o,u,t.alloc,"allocCString()"),t.scopedAllocPush=function(){A(t,"scopedAllocPush");const o=[];return w.scopedAlloc.push(o),o},t.scopedAllocPop=function(o){A(t,"scopedAllocPop");const u=arguments.length?w.scopedAlloc.indexOf(o):w.scopedAlloc.length-1;u<0&&r("Invalid state object for scopedAllocPop()."),arguments.length===0&&(o=w.scopedAlloc[u]),w.scopedAlloc.splice(u,1);for(let p;p=o.pop();)t.functionEntry(p)?t.uninstallFunction(p):t.dealloc(p)},t.scopedAlloc=function(o){w.scopedAlloc.length||r("No scopedAllocPush() scope is active.");const u=M(t.alloc(o));return w.scopedAlloc.pushPtr(u)},Object.defineProperty(t.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>w.scopedAlloc.length,set:()=>r("The 'active' property is read-only.")}),t.scopedAllocCString=(o,u=!1)=>N(o,u,t.scopedAlloc,"scopedAllocCString()");const J=function(o,u){const p=t[o?"scopedAlloc":"alloc"]((u.length+1)*t.ptr.size);let q=0;return u.forEach(z=>{t.pokePtr(S(p,t.ptr.size*q++),t[o?"scopedAllocCString":"allocCString"](""+z))}),t.pokePtr(S(p,t.ptr.size*q),0),p};t.scopedAllocMainArgv=o=>J(!0,o),t.allocMainArgv=o=>J(!1,o),t.cArgvToJs=(o,u)=>{const p=[];for(let q=0;qd(o,u,"alloc"),t.scopedAllocPtr=(o=1,u=!0)=>d(o,u,"scopedAlloc"),t.xGet=function(o){return t.exports[o]||r("Cannot find exported symbol:",o)};const y=(o,u)=>r(o+"() requires",u,"argument(s).");t.xCall=function(o,...u){const p=o instanceof Function?o:t.xGet(o);return p instanceof Function||r("Exported symbol",o,"is not a function."),p.length!==u.length&&y(p===o?p.name:o,p.length),arguments.length===2&&Array.isArray(arguments[1])?p.apply(null,arguments[1]):p.apply(null,u)},w.xWrap=Object.create(null),w.xWrap.convert=Object.create(null),w.xWrap.convert.arg=new Map,w.xWrap.convert.result=new Map;const F=w.xWrap.convert.arg,W=w.xWrap.convert.result,P=M;F.set("i64",c).set("i32",o=>o|0).set("i16",o=>(o|0)&65535).set("i8",o=>(o|0)&255).set("f32",o=>Number(o).valueOf()).set("float",F.get("f32")).set("f64",F.get("f32")).set("double",F.get("f64")).set("int",F.get("i32")).set("null",o=>o).set(null,F.get("null")).set("**",P).set("*",P),W.set("*",P).set("pointer",P).set("number",o=>Number(o)).set("void",o=>{}).set(void 0,W.get("void")).set("null",o=>o).set(null,W.get("null"));for(const o of["i8","i16","i32","i64","int","f32","float","f64","double"])F.set(o+"*",P),W.set(o+"*",P),W.set(o,F.get(o)||r("Maintenance required: missing arg converter for",o));const X=o=>typeof o=="string"?t.scopedAllocCString(o):M(o);F.set("string",X).set("utf8",X),W.set("string",o=>t.cstrToJs(o)).set("utf8",W.get("string")).set("string:dealloc",o=>{try{return o?t.cstrToJs(o):null}finally{t.dealloc(o)}}).set("utf8:dealloc",W.get("string:dealloc")).set("json",o=>JSON.parse(t.cstrToJs(o))).set("json:dealloc",o=>{try{return o?JSON.parse(t.cstrToJs(o)):null}finally{t.dealloc(o)}});const ee=class{constructor(o){this.name=o.name||"unnamed adapter"}convertArg(o,u,p){r("AbstractArgAdapter must be subclassed.")}};F.FuncPtrAdapter=class rt extends ee{constructor(u){super(u),F.FuncPtrAdapter.warnOnUse&&console.warn("xArg.FuncPtrAdapter is an internal-only API","and is not intended to be invoked from","client-level code. Invoked with:",u),this.name=u.name||"unnamed",this.signature=u.signature,u.contextKey instanceof Function&&(this.contextKey=u.contextKey,u.bindScope||(u.bindScope="context")),this.bindScope=u.bindScope||r("FuncPtrAdapter options requires a bindScope (explicit or implied)."),rt.bindScopes.indexOf(u.bindScope)<0&&r("Invalid options.bindScope ("+u.bindMod+") for FuncPtrAdapter. Expecting one of: ("+rt.bindScopes.join(", ")+")"),this.isTransient=this.bindScope==="transient",this.isContext=this.bindScope==="context",this.isPermanent=this.bindScope==="permanent",this.singleton=this.bindScope==="singleton"?[]:void 0,this.callProxy=u.callProxy instanceof Function?u.callProxy:void 0}contextKey(u,p){return this}contextMap(u){const p=this.__cmap||(this.__cmap=new Map);let q=p.get(u);return q===void 0&&p.set(u,q=[]),q}convertArg(u,p,q){let z=this.singleton;if(!z&&this.isContext&&(z=this.contextMap(this.contextKey(p,q))),z&&z.length===2&&z[0]===u)return z[1];if(u instanceof Function){this.callProxy&&(u=this.callProxy(u));const V=H(u,this.signature,this.isTransient);if(rt.debugFuncInstall&&rt.debugOut("FuncPtrAdapter installed",this,this.contextKey(p,q),"@"+V,u),z){if(z[1]){rt.debugFuncInstall&&rt.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(p,q),"@"+z[1],u);try{w.scopedAlloc.pushPtr(z[1])}catch{}}z[0]=arguments[0]||I,z[1]=V}return V}else if(t.isPtr(u)||u===null||u===void 0){if(z&&z[1]&&z[1]!==u){rt.debugFuncInstall&&rt.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(p,q),"@"+z[1],u);try{w.scopedAlloc.pushPtr(z[1])}catch{}z[0]=z[1]=u||I}return u||I}else throw new TypeError("Invalid FuncPtrAdapter argument type. Expecting a function pointer or a "+(this.name?this.name+" ":"")+"function matching signature "+this.signature+".")}},F.FuncPtrAdapter.warnOnUse=!1,F.FuncPtrAdapter.debugFuncInstall=!1,F.FuncPtrAdapter.debugOut=console.debug.bind(console),F.FuncPtrAdapter.bindScopes=["transient","context","singleton","permanent"];const Z=o=>F.get(o)||r("Argument adapter not found:",o),te=o=>W.get(o)||r("Result adapter not found:",o);w.xWrap.convertArg=(o,...u)=>Z(o)(...u),w.xWrap.convertArgNoCheck=(o,...u)=>F.get(o)(...u),w.xWrap.convertResult=(o,u)=>o===null?u:o?te(o)(u):void 0,w.xWrap.convertResultNoCheck=(o,u)=>o===null?u:o?W.get(o)(u):void 0,t.xWrap=function o(u,p,...q){arguments.length===3&&Array.isArray(arguments[2])&&(q=arguments[2]),t.isPtr(u)&&(u=t.functionEntry(u)||r("Function pointer not found in WASM function table."));const z=u instanceof Function,V=z?u:t.xGet(u);if(z&&(u=V.name||"unnamed function"),q.length!==V.length&&y(u,V.length),V.length===0&&(p===null||p==="null"))return V;te(p);for(const m of q)m instanceof ee?F.set(m,(...C)=>m.convertArg(...C)):Z(m);const R=w.xWrap;return V.length===0?(...m)=>m.length?y(u,V.length):R.convertResult(p,V.call(null)):function(...m){m.length!==V.length&&y(u,V.length);const C=t.scopedAllocPush();try{let B=0;for(o.debug&&console.debug("xWrap() preparing: resultType ",p,"xf",V,"argTypes",q,"args",m);Bfetch(t.uri,{credentials:"same-origin"}),s=this,_=function(c){if(t.wasmUtilTarget){const b=(...I)=>{throw new Error(I.join(" "))},M=t.wasmUtilTarget;if(M.module=c.module,M.instance=c.instance,M.instance.exports.memory||(M.memory=t?.imports?.env?.memory||b("Missing 'memory' object!")),!M.alloc&&c.instance.exports.malloc){const I=c.instance.exports;M.alloc=function(S){return I.malloc(S)||b("Allocation of",S,"bytes failed.")},M.dealloc=function(S){S&&I.free(S)}}s(M)}return c.config=t,t.onload&&t.onload(c),c};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(r(),t.imports||{}).then(_):()=>r().then(c=>c.arrayBuffer()).then(c=>WebAssembly.instantiate(c,t.imports||{})).then(_)}).bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function i(t){const r=(...T)=>{throw new Error(T.join(" "))};{let T=t.heap;T instanceof WebAssembly.Memory?T=(function(){return new Uint8Array(this.buffer)}).bind(T):T instanceof Function||r("config.heap must be WebAssembly.Memory instance or","a function which returns one."),t.heap=T}["alloc","dealloc"].forEach(function(T){t[T]instanceof Function||r("Config option '"+T+"' must be a function.")});const s=i,_=t.heap,c=t.alloc,b=t.dealloc;t.realloc;const M=t.log||console.debug.bind(console),I=t.memberPrefix||"",S=t.memberSuffix||"",w=globalThis.BigInt,x=globalThis.BigInt64Array,L=t.bigIntEnabled??!!x;let H;const g=t.pointerSize||t.ptrSize||(typeof(H=c(1))=="bigint"?8:4),h=t.pointerIR||t.ptrIR||(g===4?"i32":"i64");H&&(b(H),H=void 0),g!==4&&g!==8&&r("Invalid pointer size:",g),h!=="i32"&&h!=="i64"&&r("Invalid pointer representation:",h);const D=L&&w?T=>w(T||0):T=>r("BigInt support is disabled in this build."),Q=h=="i32"?Number:D,A=Q(0),N=function(...T){let U=A;for(let K=0;KT[1]==="(",F=T=>T==="p"||T==="P"||T==="s",W=T=>T==="P",P=T=>T?y(T)?"p":T[0]:void 0,X=function(T){switch(P(T)){case"c":case"C":return"i8";case"i":return"i32";case"p":case"P":case"s":return h;case"j":return"i64";case"f":return"float";case"d":return"double"}r("Unhandled signature IR:",T)},ee=function(T){switch(P(T)){case"c":case"C":return 1;case"i":return 4;case"p":case"P":case"s":return g;case"j":return 8;case"f":return 4;case"d":return 8}r("Unhandled signature sizeof:",T)},Z=x?()=>!0:()=>r("BigInt64Array is not available."),te=function(T){switch(P(T)){case"p":case"P":case"s":switch(g){case 4:return"getInt32";case 8:return Z()&&"getBigInt64"}break;case"i":return"getInt32";case"c":return"getInt8";case"C":return"getUint8";case"j":return Z()&&"getBigInt64";case"f":return"getFloat32";case"d":return"getFloat64"}r("Unhandled DataView getter for signature:",T)},E=function(T){switch(P(T)){case"p":case"P":case"s":switch(g){case 4:return"setInt32";case 8:return Z()&&"setBigInt64"}break;case"i":return"setInt32";case"c":return"setInt8";case"C":return"setUint8";case"j":return Z()&&"setBigInt64";case"f":return"setFloat32";case"d":return"setFloat64"}r("Unhandled DataView setter for signature:",T)},o=function(T){switch(P(T)){case"i":case"f":case"c":case"C":case"d":return Number;case"j":return D;case"p":case"P":case"s":switch(g){case 4:return Number;case 8:return D}break}r("Unhandled DataView set wrapper for signature:",T)},u=(T,U)=>T+"::"+U,p=function(T,U){return()=>r(u(T,U),"is read-only.")},q=function T(U,K=!0){let re=T.map.get(U);return!re&&K&&T.map.set(U,re=T.create(U)),re};q.map=new WeakMap,q.create=T=>Object.assign(Object.create(null),{o:T,p:void 0,ownsPointer:!1,zod:!1,xb:0});const z=T=>q.map.delete(T),V=T=>typeof T=="number"&&T===(T|0)&&T>=0,m=g===4?V:T=>typeof T=="bigint"&&T>=0||V(T),C=T=>m(T)&&T>0,B=function(T,U,K){const re=q(U,!1);if(re){if(z(U),!K&&!(K=re.p)){console.warn("Cannot(?) happen: __freeStruct() found no instanceInfo");return}if(Array.isArray(U.ondispose)){let ue;for(;ue=U.ondispose.pop();)try{ue instanceof Function?ue.call(U):ue instanceof Ge?ue.dispose():m(ue)&&b(ue)}catch(Te){console.warn("ondispose() for",T.structName,"@",K,"threw. NOT propagating it.",Te)}}else if(U.ondispose instanceof Function)try{U.ondispose()}catch(ue){console.warn("ondispose() for",T.structName,"@",K,"threw. NOT propagating it.",ue)}delete U.ondispose,T.debugFlags.__flags.dealloc&&M("debug.dealloc:",re.ownsPointer?"":"EXTERNAL",T.structName,"instance:",T.structInfo.sizeof,"bytes @"+K),re.ownsPointer&&((re.zod||T.structInfo.zeroOnDispose)&&_().fill(0,Number(K),Number(K)+T.structInfo.sizeof+re.xb),b(K))}},Y=()=>({configurable:!1,writable:!1,iterable:!1}),ne=T=>({...Y(),value:T}),ae=function(U,K,re){let ue;const Te=Ae=>{C(Ae)||r("Invalid pointer value",arguments[0],"for",U.structName,"constructor.")};arguments.length>=3?re&&typeof re=="object"?(ue=re,re=ue?.wrap):(Te(re),ue={wrap:re}):ue={};const Me=!re;let He=0,$e=!1;if(re)Te(re),$e=!!ue?.takeOwnership;else{const Ae=ue?.extraBytes??0;(Ae<0||Ae!==(Ae|0))&&r("Invalid extraBytes value:",ue?.extraBytes),He=U.structInfo.sizeof+Ae,re=c(He)||r("Allocation of",U.structName,"structure failed."),$e=!0}try{ue?.debugFlags&&K.debugFlags(ue.debugFlags),U.debugFlags.__flags.alloc&&M("debug.alloc:",Me?"":"EXTERNAL",U.structName,"instance:",U.structInfo.sizeof,"bytes @"+re),Me&&_().fill(0,Number(re),Number(re)+He);const Ae=q(K);Ae.p=re,Ae.ownsPointer=$e,Ae.xb=He?He-U.structInfo.sizeof:0,Ae.zod=!!ue?.zeroOnDispose,ue?.ondispose&&ue.ondispose!==re&&K.addOnDispose(ue.ondispose)}catch(Ae){throw B(U,K,re),Ae}},ce=function T(U){return T.rxSig1??=/^[ipPsjfdcC]$/,T.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,T.rxSig1.test(U)||T.rxSig2.test(U)},ke=(function(T){let U=this.get(T);return U||(U=[Object.create(null),Object.create(null),Object.create(null)],this.set(T,U)),U}).bind(new WeakMap),Ne=function(T,U,K,re){const ue=ke(T)[U];return arguments.length===3?ue[K]:re?ue[K]=re:delete ue[K]},Xe=function(T,...U){return Ne(this,0,T,...U)},at=function(T,U){ce(U)&&r(T,"(",U,") collides with a data type signature.")},O=function(T,...U){return at("Setter adaptor",T),Ne(this,1,T,...U)},j=function(T,...U){return at("Struct adaptor",T),Ne(this,2,T,...U)},G=function(T,U){const K=typeof U=="string"?Ne(T,2,U):U;return typeof K!="object"&&r("Invalid struct mapping object. Arg =",U,JSON.stringify(K)),K},se=ne(T=>I+T+S),le=function(T,U,K=!0){let re=T.members[U];if(!re&&(I||S)){for(const ue of Object.values(T.members))if(ue.key===U){re=ue;break}!re&&K&&r(u(T.name||T.structName,U),"is not a mapped struct member.")}return re},_e=function T(U,K,re=!1){T._||(T._=Te=>Te.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i"));const ue=le(U.structInfo,K,!0);return re?T._(ue.signature):ue.signature},oe=ne(function(){const T=[];for(const U of Object.keys(this.structInfo.members))T.push(this.memberKey(U));return T}),pe=new TextDecoder("utf-8"),we=new TextEncoder,Pe=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,be=function(T,U,K){return g===8&&(U=Number(U),K=Number(K)),pe.decode(T.buffer instanceof Pe?T.slice(U,K):T.subarray(U,K))},Ue=function(T,U,K=!1){const re=le(T.structInfo,U,K);return re&&re.signature.length===1&&re.signature[0]==="s"?re:!1},Ye=function(T){T.signature!=="s"&&r("Invalid member type signature for C-string value:",JSON.stringify(T))},pt=function(U,K){const re=le(U.structInfo,K,!0);Ye(re);const ue=U[re.key];if(!ue)return null;let Te=ue;const Me=_();for(;Me[Te]!==0;++Te);return ue===Te?"":be(Me,ue,Te)},Ze=function(T,...U){T.ondispose?Array.isArray(T.ondispose)||(T.ondispose=[T.ondispose]):T.ondispose=[],T.ondispose.push(...U)},ct=function(T){const U=we.encode(T),K=c(U.length+1);K||r("Allocation error while duplicating string:",T);const re=_();return re.set(U,Number(K)),re[N(K,U.length)]=0,K},qt=function(T,U,K){const re=le(T.structInfo,U,!0);Ye(re);const ue=ct(K);return T[re.key]=ue,Ze(T,ue),T},Ge=function(U,K){arguments[2]!==ne&&r("Do not call the StructType constructor","from client-level code."),Object.defineProperties(this,{structName:ne(U),structInfo:ne(K)})};Ge.prototype=Object.create(null,{dispose:ne(function(){B(this.constructor,this)}),lookupMember:ne(function(T,U=!0){return le(this.structInfo,T,U)}),memberToJsString:ne(function(T){return pt(this,T)}),memberIsString:ne(function(T,U=!0){return Ue(this,T,U)}),memberKey:se,memberKeys:oe,memberSignature:ne(function(T,U=!1){return _e(this,T,U)}),memoryDump:ne(function(){const T=this.pointer;return T?new Uint8Array(_().slice(Number(T),Number(T)+this.structInfo.sizeof)):null}),extraBytes:{configurable:!1,enumerable:!1,get:function(){return q(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return q(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return q(this,!1)?.p},set:()=>r("Cannot assign the 'pointer' property of a struct.")},setMemberCString:ne(function(T,U){return qt(this,T,U)})}),Object.assign(Ge.prototype,{addOnDispose:function(...T){return Ze(this,...T),this}}),Object.defineProperties(Ge,{allocCString:ne(ct),isA:ne(T=>T instanceof Ge),hasExternalPointer:ne(T=>{const U=q(T,!1);return!!(U?.p&&!U?.ownsPointer)}),memberKey:se});const wt=function(T){return T.get||(T.adaptGet?Ke.adaptGet(T.adaptGet):void 0)},Zt=function(T){return T.set||(T.adaptSet?Ke.adaptSet(T.adaptSet):void 0)},Ir=function T(U,K,re){const ue=T.innerStructs??=new Map,Te=U.memberKey(K);re.signature!==void 0&&r("'signature' cannot be used on an embedded struct (",U.structName,".",Te,")."),Zt(re)&&r("'set' and 'adaptSet' are not permitted for nested struct members."),re.structName??=U.structName+"::"+K,re.key=Te,re.name=K,re.constructor=this.call(this,re.structName,re);const Me=wt(re),He=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:p(U.structName,Te),get:function(){const $e=this.debugFlags.__flags,Ae=this.pointer,ze=Ae+"."+Te;let fe=ue.get(ze);return $e.getter&&M("debug.getter: k =",ze),fe||(fe=new re.constructor(N(Ae,re.offset)),ue.set(ze,fe),this.addOnDispose(()=>fe.dispose()),fe.addOnDispose(()=>ue.delete(ze))),Me&&(fe=Me.apply(this,[fe,Te])),$e.getter&&M("debug.getter: result =",fe),fe}});Object.defineProperty(U.prototype,Te,He)},kr=function T(U,K,re){if(re=G(this,re),re.members)return Ir.call(this,U,K,re);if(!T.cache){T.cache={getters:{},setters:{},sw:{}};const ze=["i","c","C","p","P","s","f","d","v()"];L&&ze.push("j"),ze.forEach(function(fe){T.cache.getters[fe]=te(fe),T.cache.setters[fe]=E(fe),T.cache.sw[fe]=o(fe)}),T.sigCheck=function(fe,Re,Et,tn){Object.prototype.hasOwnProperty.call(fe,Et)&&r(fe.structName,"already has a property named",Et+"."),ce(tn)||r("Malformed signature for",u(fe.structName,Re)+":",tn)}}const ue=U.memberKey(K);T.sigCheck(U.prototype,K,ue,re.signature),re.key=ue,re.name=K;const Te=P(re.signature),Me=u(U.structName,ue),He=U.debugFlags.__flags,$e=wt(re),Ae=Object.create(null);if(Ae.configurable=!1,Ae.enumerable=!1,Ae.get=function(){He.getter&&M("debug.getter:",T.cache.getters[Te],"for",X(Te),Me,"@",this.pointer,"+",re.offset,"sz",re.sizeof);let ze=new DataView(_().buffer,Number(this.pointer)+re.offset,re.sizeof)[T.cache.getters[Te]](0,d);return $e&&(ze=$e.apply(this,[ue,ze])),He.getter&&M("debug.getter:",Me,"result =",ze),ze},re.readOnly)Ae.set=p(U.prototype.structName,ue);else{const ze=Zt(re);Ae.set=function(fe){He.setter&&M("debug.setter:",T.cache.setters[Te],"for",X(Te),Me,"@",this.pointer,"+",re.offset,"sz",re.sizeof,fe),this.pointer||r("Cannot set native property on a disposed",this.structName,"instance."),ze&&(fe=ze.apply(this,[ue,fe])),fe==null?fe=A:F(re.signature)&&!m(fe)&&(W(re.signature)&&fe instanceof Ge?(fe=fe.pointer||A,He.setter&&M("debug.setter:",Me,"resolved to",fe)):r("Invalid value for pointer-type",Me+".")),new DataView(_().buffer,Number(this.pointer)+re.offset,re.sizeof)[T.cache.setters[Te]](0,T.cache.sw[Te](fe),d)}}Object.defineProperty(U.prototype,ue,Ae)},en=function T(U,K,re=Object.create(null)){const ue=function fe(Re){this instanceof fe||r("The",U,"constructor may only be called via 'new'."),ae(fe,this,...arguments)},Te=this,Me=fe=>typeof fe=="string"&&ce(fe)?{signature:fe}:G(Te,fe);arguments.length===1?(K=Me(U),U=K.structName||K.name):arguments.length===2?(K=Me(K),K.name??=U):K=Me(K),U??=K.structName,U??=re.structName,U||r("One of 'name' or 'structName' are required."),K.adapt&&(Object.keys(K.adapt.struct||{}).forEach(fe=>{j.call(T,fe,K.adapt.struct[fe])}),Object.keys(K.adapt.set||{}).forEach(fe=>{O.call(T,fe,K.adapt.set[fe])}),Object.keys(K.adapt.get||{}).forEach(fe=>{Xe.call(T,fe,K.adapt.get[fe])})),!K.members&&!K.sizeof&&(K.sizeof=ee(K.signature));const He=ne(s.__makeDebugFlags(Ke.debugFlags));Object.defineProperties(ue,{debugFlags:He,isA:ne(fe=>fe instanceof ue),memberKey:se,memberKeys:oe,structInfo:ne(K),structName:ne(U),ptrAdd:ne(N)}),ue.prototype=new Ge(U,K,ne),Object.defineProperties(ue.prototype,{debugFlags:He,constructor:ne(ue),ptrAdd:ne(J)});let $e=!1,Ae=0;const ze=!!K.autoCalcSizeOffset;return ze||K.sizeof||r(U,"description is missing its sizeof property."),K.offset??=0,Object.keys(K.members||{}).forEach(fe=>{let Re=Me(K.members[fe]);!Re.members&&!Re.sizeof&&(Re.sizeof=ee(Re.signature),Re.sizeof||r(u(U,fe),"is missing a sizeof property.",Re)),Re.offset===void 0&&(ze?Re.offset=Ae:r(u(U,fe),"is missing its offset.",JSON.stringify(Re))),K.members[fe]=Re,(!$e||$e.offset{throw new Error(g.join(" "))},r=i.capi,s=i.wasm,_=i.util;globalThis.WhWasmUtilInstaller(s),delete globalThis.WhWasmUtilInstaller;const c={core:[["sqlite3_aggregate_context","void*","sqlite3_context*","int"],["sqlite3_bind_double","int","sqlite3_stmt*","int","f64"],["sqlite3_bind_int","int","sqlite3_stmt*","int","int"],["sqlite3_bind_null",void 0,"sqlite3_stmt*","int"],["sqlite3_bind_parameter_count","int","sqlite3_stmt*"],["sqlite3_bind_parameter_index","int","sqlite3_stmt*","string"],["sqlite3_bind_parameter_name","string","sqlite3_stmt*","int"],["sqlite3_bind_pointer","int","sqlite3_stmt*","int","*","string:static","*"],["sqlite3_bind_zeroblob","int","sqlite3_stmt*","int","int"],["sqlite3_busy_handler","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({signature:"i(pi)",contextKey:(g,h)=>g[0]}),"*"]],["sqlite3_busy_timeout","int","sqlite3*","int"],["sqlite3_changes","int","sqlite3*"],["sqlite3_clear_bindings","int","sqlite3_stmt*"],["sqlite3_collation_needed","int","sqlite3*","*","*"],["sqlite3_column_blob","*","sqlite3_stmt*","int"],["sqlite3_column_bytes","int","sqlite3_stmt*","int"],["sqlite3_column_count","int","sqlite3_stmt*"],["sqlite3_column_decltype","string","sqlite3_stmt*","int"],["sqlite3_column_double","f64","sqlite3_stmt*","int"],["sqlite3_column_int","int","sqlite3_stmt*","int"],["sqlite3_column_name","string","sqlite3_stmt*","int"],["sqlite3_column_type","int","sqlite3_stmt*","int"],["sqlite3_column_value","sqlite3_value*","sqlite3_stmt*","int"],["sqlite3_commit_hook","void*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_commit_hook",signature:"i(p)",contextKey:g=>g[0]}),"*"]],["sqlite3_compileoption_get","string","int"],["sqlite3_compileoption_used","int","string"],["sqlite3_complete","int","string:flexible"],["sqlite3_context_db_handle","sqlite3*","sqlite3_context*"],["sqlite3_data_count","int","sqlite3_stmt*"],["sqlite3_db_filename","string","sqlite3*","string"],["sqlite3_db_handle","sqlite3*","sqlite3_stmt*"],["sqlite3_db_name","string","sqlite3*","int"],["sqlite3_db_readonly","int","sqlite3*","string"],["sqlite3_db_status","int","sqlite3*","int","*","*","int"],["sqlite3_errcode","int","sqlite3*"],["sqlite3_errmsg","string","sqlite3*"],["sqlite3_error_offset","int","sqlite3*"],["sqlite3_errstr","string","int"],["sqlite3_exec","int",["sqlite3*","string:flexible",new s.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:g=>{let h;return(D,Q,A,N)=>{try{const J=s.cArgvToJs(Q,A);return h||(h=s.cArgvToJs(Q,N)),g(J,h)|0}catch(J){return J.resultCode||r.SQLITE_ERROR}}}}),"*","**"]],["sqlite3_expanded_sql","string","sqlite3_stmt*"],["sqlite3_extended_errcode","int","sqlite3*"],["sqlite3_extended_result_codes","int","sqlite3*","int"],["sqlite3_file_control","int","sqlite3*","string","int","*"],["sqlite3_finalize","int","sqlite3_stmt*"],["sqlite3_free",void 0,"*"],["sqlite3_get_autocommit","int","sqlite3*"],["sqlite3_get_auxdata","*","sqlite3_context*","int"],["sqlite3_initialize",void 0],["sqlite3_interrupt",void 0,"sqlite3*"],["sqlite3_is_interrupted","int","sqlite3*"],["sqlite3_keyword_count","int"],["sqlite3_keyword_name","int",["int","**","*"]],["sqlite3_keyword_check","int",["string","int"]],["sqlite3_libversion","string"],["sqlite3_libversion_number","int"],["sqlite3_limit","int",["sqlite3*","int","int"]],["sqlite3_malloc","*","int"],["sqlite3_next_stmt","sqlite3_stmt*",["sqlite3*","sqlite3_stmt*"]],["sqlite3_open","int","string","*"],["sqlite3_open_v2","int","string","*","int","string"],["sqlite3_realloc","*","*","int"],["sqlite3_reset","int","sqlite3_stmt*"],["sqlite3_result_blob",void 0,"sqlite3_context*","*","int","*"],["sqlite3_result_double",void 0,"sqlite3_context*","f64"],["sqlite3_result_error",void 0,"sqlite3_context*","string","int"],["sqlite3_result_error_code",void 0,"sqlite3_context*","int"],["sqlite3_result_error_nomem",void 0,"sqlite3_context*"],["sqlite3_result_error_toobig",void 0,"sqlite3_context*"],["sqlite3_result_int",void 0,"sqlite3_context*","int"],["sqlite3_result_null",void 0,"sqlite3_context*"],["sqlite3_result_pointer",void 0,"sqlite3_context*","*","string:static","*"],["sqlite3_result_subtype",void 0,"sqlite3_value*","int"],["sqlite3_result_text",void 0,"sqlite3_context*","string","int","*"],["sqlite3_result_zeroblob",void 0,"sqlite3_context*","int"],["sqlite3_rollback_hook","void*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_rollback_hook",signature:"v(p)",contextKey:g=>g[0]}),"*"]],["sqlite3_set_auxdata",void 0,["sqlite3_context*","int","*","*"]],["sqlite3_set_errmsg","int","sqlite3*","int","string"],["sqlite3_shutdown",void 0],["sqlite3_sourceid","string"],["sqlite3_sql","string","sqlite3_stmt*"],["sqlite3_status","int","int","*","*","int"],["sqlite3_step","int","sqlite3_stmt*"],["sqlite3_stmt_busy","int","sqlite3_stmt*"],["sqlite3_stmt_readonly","int","sqlite3_stmt*"],["sqlite3_stmt_status","int","sqlite3_stmt*","int","int"],["sqlite3_strglob","int","string","string"],["sqlite3_stricmp","int","string","string"],["sqlite3_strlike","int","string","string","int"],["sqlite3_strnicmp","int","string","string","int"],["sqlite3_table_column_metadata","int","sqlite3*","string","string","string","**","**","*","*","*"],["sqlite3_total_changes","int","sqlite3*"],["sqlite3_trace_v2","int",["sqlite3*","int",new s.xWrap.FuncPtrAdapter({name:"sqlite3_trace_v2::callback",signature:"i(ippp)",contextKey:(g,h)=>g[0]}),"*"]],["sqlite3_txn_state","int",["sqlite3*","string"]],["sqlite3_uri_boolean","int","sqlite3_filename","string","int"],["sqlite3_uri_key","string","sqlite3_filename","int"],["sqlite3_uri_parameter","string","sqlite3_filename","string"],["sqlite3_user_data","void*","sqlite3_context*"],["sqlite3_value_blob","*","sqlite3_value*"],["sqlite3_value_bytes","int","sqlite3_value*"],["sqlite3_value_double","f64","sqlite3_value*"],["sqlite3_value_dup","sqlite3_value*","sqlite3_value*"],["sqlite3_value_free",void 0,"sqlite3_value*"],["sqlite3_value_frombind","int","sqlite3_value*"],["sqlite3_value_int","int","sqlite3_value*"],["sqlite3_value_nochange","int","sqlite3_value*"],["sqlite3_value_numeric_type","int","sqlite3_value*"],["sqlite3_value_pointer","*","sqlite3_value*","string:static"],["sqlite3_value_subtype","int","sqlite3_value*"],["sqlite3_value_type","int","sqlite3_value*"],["sqlite3_vfs_find","*","string"],["sqlite3_vfs_register","int","sqlite3_vfs*","int"],["sqlite3_vfs_unregister","int","sqlite3_vfs*"]],int64:[["sqlite3_bind_int64","int",["sqlite3_stmt*","int","i64"]],["sqlite3_changes64","i64",["sqlite3*"]],["sqlite3_column_int64","i64",["sqlite3_stmt*","int"]],["sqlite3_deserialize","int","sqlite3*","string","*","i64","i64","int"],["sqlite3_last_insert_rowid","i64",["sqlite3*"]],["sqlite3_malloc64","*","i64"],["sqlite3_msize","i64","*"],["sqlite3_overload_function","int",["sqlite3*","string","int"]],["sqlite3_realloc64","*","*","i64"],["sqlite3_result_int64",void 0,"*","i64"],["sqlite3_result_zeroblob64","int","*","i64"],["sqlite3_serialize","*","sqlite3*","string","*","int"],["sqlite3_set_last_insert_rowid",void 0,["sqlite3*","i64"]],["sqlite3_status64","int","int","*","*","int"],["sqlite3_db_status64","int","sqlite3*","int","*","*","int"],["sqlite3_total_changes64","i64",["sqlite3*"]],["sqlite3_update_hook","*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:g=>g[0],callProxy:g=>(h,D,Q,A,N)=>{g(h,D,s.cstrToJs(Q),s.cstrToJs(A),N)}}),"*"]],["sqlite3_uri_int64","i64",["sqlite3_filename","string","i64"]],["sqlite3_value_int64","i64","sqlite3_value*"]],wasmInternal:[["sqlite3__wasm_db_reset","int","sqlite3*"],["sqlite3__wasm_db_vfs","sqlite3_vfs*","sqlite3*","string"],["sqlite3__wasm_vfs_create_file","int","sqlite3_vfs*","string","*","int"],["sqlite3__wasm_posix_create_file","int","string","*","int"],["sqlite3__wasm_vfs_unlink","int","sqlite3_vfs*","string"],["sqlite3__wasm_qfmt_token","string:dealloc","string","int"]]};if(s.exports.sqlite3_progress_handler&&c.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new s.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(g,h)=>g[0]}),"*"]]),s.exports.sqlite3_stmt_explain&&c.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]),s.exports.sqlite3_set_authorizer&&c.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(g,h)=>g[0],callProxy:g=>(h,D,Q,A,N,J)=>{try{return Q=Q&&s.cstrToJs(Q),A=A&&s.cstrToJs(A),N=N&&s.cstrToJs(N),J=J&&s.cstrToJs(J),g(h,D,Q,A,N,J)|0}catch(d){return d.resultCode||r.SQLITE_ERROR}}}),"*"]]),s.exports.sqlite3_column_origin_name&&c.core.push(["sqlite3_column_database_name","string","sqlite3_stmt*","int"],["sqlite3_column_origin_name","string","sqlite3_stmt*","int"],["sqlite3_column_table_name","string","sqlite3_stmt*","int"]),s.bigIntEnabled&&s.exports.sqlite3_declare_vtab&&c.int64.push(["sqlite3_create_module","int",["sqlite3*","string","sqlite3_module*","*"]],["sqlite3_create_module_v2","int",["sqlite3*","string","sqlite3_module*","*","*"]],["sqlite3_declare_vtab","int",["sqlite3*","string:flexible"]],["sqlite3_drop_modules","int",["sqlite3*","**"]],["sqlite3_vtab_collation","string","sqlite3_index_info*","int"],["sqlite3_vtab_distinct","int","sqlite3_index_info*"],["sqlite3_vtab_in","int","sqlite3_index_info*","int","int"],["sqlite3_vtab_in_first","int","sqlite3_value*","**"],["sqlite3_vtab_in_next","int","sqlite3_value*","**"],["sqlite3_vtab_nochange","int","sqlite3_context*"],["sqlite3_vtab_on_conflict","int","sqlite3*"],["sqlite3_vtab_rhs_value","int","sqlite3_index_info*","int","**"]),s.bigIntEnabled&&s.exports.sqlite3_preupdate_hook&&c.int64.push(["sqlite3_preupdate_blobwrite","int","sqlite3*"],["sqlite3_preupdate_count","int","sqlite3*"],["sqlite3_preupdate_depth","int","sqlite3*"],["sqlite3_preupdate_hook","*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:g=>g[0],callProxy:g=>(h,D,Q,A,N,J,d)=>{g(h,D,Q,s.cstrToJs(A),s.cstrToJs(N),J,d)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]),s.bigIntEnabled&&s.exports.sqlite3changegroup_add&&s.exports.sqlite3session_create&&s.exports.sqlite3_preupdate_hook){const g={signature:"i(ps)",callProxy:h=>(D,Q)=>{try{return h(D,s.cstrToJs(Q))|0}catch(A){return A.resultCode||r.SQLITE_ERROR}}};c.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changegroup_delete",void 0,["sqlite3_changegroup*"]],["sqlite3changegroup_new","int",["**"]],["sqlite3changegroup_output","int",["sqlite3_changegroup*","int*","**"]],["sqlite3changegroup_output_strm","int",["sqlite3_changegroup*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_concat","int",["int","void*","int","void*","int*","**"]],["sqlite3changeset_concat_strm","int",[new s.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_conflict","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_finalize","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_fk_conflicts","int",["sqlite3_changeset_iter*","int*"]],["sqlite3changeset_invert","int",["int","void*","int*","**"]],["sqlite3changeset_invert_strm","int",[new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_new","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_next","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_old","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_op","int",["sqlite3_changeset_iter*","**","int*","int*","int*"]],["sqlite3changeset_pk","int",["sqlite3_changeset_iter*","**","int*"]],["sqlite3changeset_start","int",["**","int","*"]],["sqlite3changeset_start_strm","int",["**",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*","int"]],["sqlite3session_attach","int",["sqlite3_session*","string"]],["sqlite3session_changeset","int",["sqlite3_session*","int*","**"]],["sqlite3session_changeset_size","i64",["sqlite3_session*"]],["sqlite3session_changeset_strm","int",["sqlite3_session*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_config","int",["int","void*"]],["sqlite3session_create","int",["sqlite3*","string","**"]],["sqlite3session_diff","int",["sqlite3_session*","string","string","**"]],["sqlite3session_enable","int",["sqlite3_session*","int"]],["sqlite3session_indirect","int",["sqlite3_session*","int"]],["sqlite3session_isempty","int",["sqlite3_session*"]],["sqlite3session_memory_used","i64",["sqlite3_session*"]],["sqlite3session_object_config","int",["sqlite3_session*","int","void*"]],["sqlite3session_patchset","int",["sqlite3_session*","*","**"]],["sqlite3session_patchset_strm","int",["sqlite3_session*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new s.xWrap.FuncPtrAdapter({name:"xFilter",...g,contextKey:(h,D)=>h[0]}),"*"]])}i.StructBinder=globalThis.Jaccwabyt({heap:s.heap8u,alloc:s.alloc,dealloc:s.dealloc,bigIntEnabled:s.bigIntEnabled,pointerIR:s.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{const g=s.xWrap.argAdapter("string");s.xWrap.argAdapter("string:flexible",A=>g(_.flexibleString(A))),s.xWrap.argAdapter("string:static",(function(A){return s.isPtr(A)?A:(A=""+A,this[A]||(this[A]=s.allocCString(A)))}).bind(Object.create(null)));const h=s.xWrap.argAdapter("*"),D=function(){};s.xWrap.argAdapter("sqlite3_filename",h)("sqlite3_context*",h)("sqlite3_value*",h)("void*",h)("sqlite3_changegroup*",h)("sqlite3_changeset_iter*",h)("sqlite3_session*",h)("sqlite3_stmt*",A=>h(A instanceof(i?.oo1?.Stmt||D)?A.pointer:A))("sqlite3*",A=>h(A instanceof(i?.oo1?.DB||D)?A.pointer:A))("sqlite3_vfs*",A=>typeof A=="string"?r.sqlite3_vfs_find(A)||i.SQLite3Error.toss(r.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",A):h(A instanceof(r.sqlite3_vfs||D)?A.pointer:A)),s.exports.sqlite3_declare_vtab&&s.xWrap.argAdapter("sqlite3_index_info*",A=>h(A instanceof(r.sqlite3_index_info||D)?A.pointer:A))("sqlite3_module*",A=>h(A instanceof(r.sqlite3_module||D)?A.pointer:A));const Q=s.xWrap.resultAdapter("*");s.xWrap.resultAdapter("sqlite3*",Q)("sqlite3_context*",Q)("sqlite3_stmt*",Q)("sqlite3_value*",Q)("sqlite3_vfs*",Q)("void*",Q);for(const A of c.core)r[A[0]]=s.xWrap.apply(null,A);for(const A of c.wasmInternal)_[A[0]]=s.xWrap.apply(null,A);for(const A of c.int64)r[A[0]]=s.bigIntEnabled?s.xWrap.apply(null,A):()=>t(A[0]+"() is unavailable due to lack","of BigInt support in this build.");delete c.core,delete c.int64,delete c.wasmInternal,_.sqlite3__wasm_db_error=function(A,N,J){return A?(N instanceof i.WasmAllocError?(N=r.SQLITE_NOMEM,J=0):N instanceof Error&&(J=J||""+N,N=N.resultCode||r.SQLITE_ERROR),r.sqlite3_set_errmsg(A,N,J)||N):r.SQLITE_MISUSE}}{const g=s.xCall("sqlite3__wasm_enum_json");g||t("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!"),s.ctype=JSON.parse(s.cstrToJs(g));const h=["access","authorizer","blobFinalizers","changeset","config","dataTypes","dbConfig","dbStatus","encodings","fcntl","flock","ioCap","limits","openFlags","prepareFlags","resultCodes","sqlite3Status","stmtStatus","syncFlags","trace","txnState","udfFlags","version"];s.bigIntEnabled&&h.push("serialize","session","vtab");for(const A of h)for(const N of Object.entries(s.ctype[A]))r[N[0]]=N[1];s.functionEntry(r.SQLITE_WASM_DEALLOC)||t("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+r.SQLITE_WASM_DEALLOC+").");const D=Object.create(null);for(const A of Object.entries(s.ctype.resultCodes))D[A[1]]=A[0];r.sqlite3_js_rc_str=A=>D[A];const Q=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!s.bigIntEnabled,sqlite3_index_constraint:!s.bigIntEnabled,sqlite3_index_orderby:!s.bigIntEnabled,sqlite3_index_constraint_usage:!s.bigIntEnabled});for(const A of s.ctype.structs)Q[A.name]||(r[A.name]=i.StructBinder(A));if(r.sqlite3_index_info){for(const A of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])r.sqlite3_index_info[A]=r[A],delete r[A];r.sqlite3_vtab_config=s.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}const b=(g,h,D)=>_.sqlite3__wasm_db_error(g,r.SQLITE_MISUSE,h+"() requires "+D+" argument"+(D===1?"":"s")+"."),M=g=>_.sqlite3__wasm_db_error(g,r.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),I=g=>s.xWrap.argAdapter("sqlite3*")(g),S=g=>s.isPtr(g)?s.cstrToJs(g):g,w=(function(g,h){g=I(g);let D=this.dbMap.get(g);if(h)!D&&h>0&&this.dbMap.set(g,D=Object.create(null));else return this.dbMap.delete(g),D;return D}).bind(Object.assign(Object.create(null),{dbMap:new Map}));w.addCollation=function(g,h){const D=w(g,1);D.collation||(D.collation=new Set),D.collation.add(S(h).toLowerCase())},w._addUDF=function(g,h,D,Q){h=S(h).toLowerCase();let A=Q.get(h);A||Q.set(h,A=new Set),A.add(D<0?-1:D)},w.addFunction=function(g,h,D){const Q=w(g,1);Q.udf||(Q.udf=new Map),this._addUDF(g,h,D,Q.udf)},s.exports.sqlite3_create_window_function&&(w.addWindowFunc=function(g,h,D){const Q=w(g,1);Q.wudf||(Q.wudf=new Map),this._addUDF(g,h,D,Q.wudf)}),w.cleanup=function(g){g=I(g);for(const Q of[["sqlite3_busy_handler",3],["sqlite3_commit_hook",3],["sqlite3_preupdate_hook",3],["sqlite3_progress_handler",4],["sqlite3_rollback_hook",3],["sqlite3_set_authorizer",3],["sqlite3_trace_v2",4],["sqlite3_update_hook",3]]){const[A,N]=Q;if(!s.exports[A])continue;const J=[g];J.length=N;try{r[A](...J)}catch(d){i.config.warn("close-time call of",A+"(",J,") threw:",d)}}const h=w(g,0);if(!h)return;if(h.collation){for(const Q of h.collation)try{r.sqlite3_create_collation_v2(g,Q,r.SQLITE_UTF8,0,0,0)}catch{}delete h.collation}let D;for(D=0;D<2;++D){const Q=D?h.wudf:h.udf;if(!Q)continue;const A=D?r.sqlite3_create_window_function:r.sqlite3_create_function_v2;for(const N of Q){const J=N[0],d=N[1],y=[g,J,0,r.SQLITE_UTF8,0,0,0,0,0];D&&y.push(0);for(const F of d)try{y[2]=F,A.apply(null,y)}catch{}d.clear()}Q.clear()}delete h.udf,delete h.wudf};{const g=s.xWrap("sqlite3_close_v2","int","sqlite3*");r.sqlite3_close_v2=function(h){if(arguments.length!==1)return b(h,"sqlite3_close_v2",1);if(h)try{w.cleanup(h)}catch{}return g(h)}}if(r.sqlite3session_create){const g=s.xWrap("sqlite3session_delete",void 0,["sqlite3_session*"]);r.sqlite3session_delete=function(h){if(arguments.length!==1)return b(pDb,"sqlite3session_delete",1);h&&r.sqlite3session_table_filter(h,0,0),g(h)}}{const g=(D,Q)=>"argv["+Q+"]:"+D[0]+":"+s.cstrToJs(D[1]).toLowerCase(),h=s.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new s.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:g}),new s.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:g})]);r.sqlite3_create_collation_v2=function(D,Q,A,N,J,d){if(arguments.length!==6)return b(D,"sqlite3_create_collation_v2",6);if((A&15)===0)A|=r.SQLITE_UTF8;else if(r.SQLITE_UTF8!==(A&15))return M(D);try{const y=h(D,Q,A,N,J,d);return y===0&&J instanceof Function&&w.addCollation(D,Q),y}catch(y){return _.sqlite3__wasm_db_error(D,y)}},r.sqlite3_create_collation=(D,Q,A,N,J)=>arguments.length===5?r.sqlite3_create_collation_v2(D,Q,A,N,J,0):b(D,"sqlite3_create_collation",5)}{const g=function(A,N){return A[0]+":"+(A[2]<0?-1:A[2])+":"+N+":"+s.cstrToJs(A[1]).toLowerCase()},h=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:g,callProxy:A=>(N,J,d)=>{try{A(N,...r.sqlite3_values_to_js(J,d))}catch(y){r.sqlite3_result_error_js(N,y)}}},xFinalAndValue:{signature:"v(p)",contextKey:g,callProxy:A=>N=>{try{r.sqlite3_result_js(N,A(N))}catch(J){r.sqlite3_result_error_js(N,J)}}},xFunc:{signature:"v(pip)",contextKey:g,callProxy:A=>(N,J,d)=>{try{r.sqlite3_result_js(N,A(N,...r.sqlite3_values_to_js(J,d)))}catch(y){r.sqlite3_result_error_js(N,y)}}},xDestroy:{signature:"v(p)",contextKey:g,callProxy:A=>N=>{try{A(N)}catch(J){console.error("UDF xDestroy method threw:",J)}}}}),D=s.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new s.xWrap.FuncPtrAdapter({name:"xFunc",...h.xFunc}),new s.xWrap.FuncPtrAdapter({name:"xStep",...h.xInverseAndStep}),new s.xWrap.FuncPtrAdapter({name:"xFinal",...h.xFinalAndValue}),new s.xWrap.FuncPtrAdapter({name:"xDestroy",...h.xDestroy})]),Q=s.exports.sqlite3_create_window_function?s.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new s.xWrap.FuncPtrAdapter({name:"xStep",...h.xInverseAndStep}),new s.xWrap.FuncPtrAdapter({name:"xFinal",...h.xFinalAndValue}),new s.xWrap.FuncPtrAdapter({name:"xValue",...h.xFinalAndValue}),new s.xWrap.FuncPtrAdapter({name:"xInverse",...h.xInverseAndStep}),new s.xWrap.FuncPtrAdapter({name:"xDestroy",...h.xDestroy})]):void 0;r.sqlite3_create_function_v2=function A(N,J,d,y,F,W,P,X,ee){if(A.length!==arguments.length)return b(N,"sqlite3_create_function_v2",A.length);if((y&15)===0)y|=r.SQLITE_UTF8;else if(r.SQLITE_UTF8!==(y&15))return M(N);try{const Z=D(N,J,d,y,F,W,P,X,ee);return Z===0&&(W instanceof Function||P instanceof Function||X instanceof Function||ee instanceof Function)&&w.addFunction(N,J,d),Z}catch(Z){return console.error("sqlite3_create_function_v2() setup threw:",Z),_.sqlite3__wasm_db_error(N,Z,"Creation of UDF threw: "+Z)}},r.sqlite3_create_function=function A(N,J,d,y,F,W,P,X){return A.length===arguments.length?r.sqlite3_create_function_v2(N,J,d,y,F,W,P,X,0):b(N,"sqlite3_create_function",A.length)},Q?r.sqlite3_create_window_function=function A(N,J,d,y,F,W,P,X,ee,Z){if(A.length!==arguments.length)return b(N,"sqlite3_create_window_function",A.length);if((y&15)===0)y|=r.SQLITE_UTF8;else if(r.SQLITE_UTF8!==(y&15))return M(N);try{const te=Q(N,J,d,y,F,W,P,X,ee,Z);return te===0&&(W instanceof Function||P instanceof Function||X instanceof Function||ee instanceof Function||Z instanceof Function)&&w.addWindowFunc(N,J,d),te}catch(te){return console.error("sqlite3_create_window_function() setup threw:",te),_.sqlite3__wasm_db_error(N,te,"Creation of UDF threw: "+te)}}:delete r.sqlite3_create_window_function,r.sqlite3_create_function_v2.udfSetResult=r.sqlite3_create_function.udfSetResult=r.sqlite3_result_js,r.sqlite3_create_window_function&&(r.sqlite3_create_window_function.udfSetResult=r.sqlite3_result_js),r.sqlite3_create_function_v2.udfConvertArgs=r.sqlite3_create_function.udfConvertArgs=r.sqlite3_values_to_js,r.sqlite3_create_window_function&&(r.sqlite3_create_window_function.udfConvertArgs=r.sqlite3_values_to_js),r.sqlite3_create_function_v2.udfSetError=r.sqlite3_create_function.udfSetError=r.sqlite3_result_error_js,r.sqlite3_create_window_function&&(r.sqlite3_create_window_function.udfSetError=r.sqlite3_result_error_js)}{const g=(D,Q)=>(typeof D=="string"?Q=-1:_.isSQLableTypedArray(D)?(Q=D.byteLength,D=s.typedArrayToString(D instanceof ArrayBuffer?new Uint8Array(D):D)):Array.isArray(D)&&(D=D.join(""),Q=-1),[D,Q]),h={basic:s.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:s.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};r.sqlite3_prepare_v3=function D(Q,A,N,J,d,y){if(D.length!==arguments.length)return b(Q,"sqlite3_prepare_v3",D.length);const[F,W]=g(A,Number(N));switch(typeof F){case"string":return h.basic(Q,F,W,J,d,null);case typeof s.ptr.null:return h.full(Q,s.ptr.coerce(F),W,J,d,y);default:return _.sqlite3__wasm_db_error(Q,r.SQLITE_MISUSE,"Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+typeof F)}},r.sqlite3_prepare_v2=function D(Q,A,N,J,d){return D.length===arguments.length?r.sqlite3_prepare_v3(Q,A,N,0,J,d):b(Q,"sqlite3_prepare_v2",D.length)}}{const g=s.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),h=s.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);r.sqlite3_bind_text=function D(Q,A,N,J,d){if(D.length!==arguments.length)return b(r.sqlite3_db_handle(Q),"sqlite3_bind_text",D.length);if(s.isPtr(N)||N===null)return g(Q,A,N,J,d);N instanceof ArrayBuffer?N=new Uint8Array(N):Array.isArray(pMem)&&(N=pMem.join(""));let y,F;try{if(_.isSQLableTypedArray(N))y=s.allocFromTypedArray(N),F=N.byteLength;else if(typeof N=="string")[y,F]=s.allocCString(N);else return _.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),r.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_text().");return g(Q,A,y,F,r.SQLITE_WASM_DEALLOC)}catch(W){return s.dealloc(y),_.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),W)}},r.sqlite3_bind_blob=function D(Q,A,N,J,d){if(D.length!==arguments.length)return b(r.sqlite3_db_handle(Q),"sqlite3_bind_blob",D.length);if(s.isPtr(N)||N===null)return h(Q,A,N,J,d);N instanceof ArrayBuffer?N=new Uint8Array(N):Array.isArray(N)&&(N=N.join(""));let y,F;try{if(_.isBindableTypedArray(N))y=s.allocFromTypedArray(N),F=J>=0?J:N.byteLength;else if(typeof N=="string")[y,F]=s.allocCString(N);else return _.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),r.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_blob().");return h(Q,A,y,F,r.SQLITE_WASM_DEALLOC)}catch(W){return s.dealloc(y),_.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),W)}}}if(!r.sqlite3_column_text){const g=s.xWrap.argAdapter("sqlite3_stmt*"),h=s.xWrap.argAdapter("int"),D=s.xWrap.argAdapter("sqlite3_value*"),Q=(A,N)=>s.typedArrayToString(s.heap8u(),Number(A),Number(A)+N);r.sqlite3_column_text=function(A,N){const J=g(A),d=h(N),y=s.exports.sqlite3_column_text(J,d);return y?Q(y,s.exports.sqlite3_column_bytes(J,d)):null},r.sqlite3_value_text=function(A){const N=D(A),J=s.exports.sqlite3_value_text(N);return J?Q(J,s.exports.sqlite3_value_bytes(N)):null}}r.sqlite3_config=function(g,...h){if(arguments.length<2)return r.SQLITE_MISUSE;switch(g){case r.SQLITE_CONFIG_COVERING_INDEX_SCAN:case r.SQLITE_CONFIG_MEMSTATUS:case r.SQLITE_CONFIG_SMALL_MALLOC:case r.SQLITE_CONFIG_SORTERREF_SIZE:case r.SQLITE_CONFIG_STMTJRNL_SPILL:case r.SQLITE_CONFIG_URI:return s.exports.sqlite3__wasm_config_i(g,h[0]);case r.SQLITE_CONFIG_LOOKASIDE:return s.exports.sqlite3__wasm_config_ii(g,h[0],h[1]);case r.SQLITE_CONFIG_MEMDB_MAXSIZE:return s.exports.sqlite3__wasm_config_j(g,h[0]);case r.SQLITE_CONFIG_GETMALLOC:case r.SQLITE_CONFIG_GETMUTEX:case r.SQLITE_CONFIG_GETPCACHE2:case r.SQLITE_CONFIG_GETPCACHE:case r.SQLITE_CONFIG_HEAP:case r.SQLITE_CONFIG_LOG:case r.SQLITE_CONFIG_MALLOC:case r.SQLITE_CONFIG_MMAP_SIZE:case r.SQLITE_CONFIG_MULTITHREAD:case r.SQLITE_CONFIG_MUTEX:case r.SQLITE_CONFIG_PAGECACHE:case r.SQLITE_CONFIG_PCACHE2:case r.SQLITE_CONFIG_PCACHE:case r.SQLITE_CONFIG_PCACHE_HDRSZ:case r.SQLITE_CONFIG_PMASZ:case r.SQLITE_CONFIG_SERIALIZED:case r.SQLITE_CONFIG_SINGLETHREAD:case r.SQLITE_CONFIG_SQLLOG:case r.SQLITE_CONFIG_WIN32_HEAPSIZE:default:return r.SQLITE_NOTFOUND}};{const g=new Set;r.sqlite3_auto_extension=function(h){if(h instanceof Function)h=s.installFunction("i(ppp)",h);else if(arguments.length!==1||!s.isPtr(h))return r.SQLITE_MISUSE;const D=s.exports.sqlite3_auto_extension(h);return h!==arguments[0]&&(D===0?g.add(h):s.uninstallFunction(h)),D},r.sqlite3_cancel_auto_extension=function(h){return!h||arguments.length!==1||!s.isPtr(h)?0:s.exports.sqlite3_cancel_auto_extension(h)},r.sqlite3_reset_auto_extension=function(){s.exports.sqlite3_reset_auto_extension();for(const h of g)s.uninstallFunction(h);g.clear()}}s.xWrap.FuncPtrAdapter.warnOnUse=!0;const x=i.StructBinder,L=function g(h,D,Q,A=g.installMethodArgcCheck){if(h instanceof x.StructType?!(Q instanceof Function)&&!s.isPtr(Q)&&t("Usage error: expecting a Function or WASM pointer to one."):t("Usage error: target object is-not-a StructType."),arguments.length===1)return(y,F)=>g(h,y,F,A);g.argcProxy||(g.argcProxy=function(y,F,W,P){return function(...X){return W.length!==arguments.length&&t("Argument mismatch for",y.structInfo.name+"::"+F+": Native signature is:",P),W.apply(this,X)}},g.removeFuncList=function(){this.ondispose.__removeFuncList&&(this.ondispose.__removeFuncList.forEach((y,F)=>{if(s.isPtr(y))try{s.uninstallFunction(y)}catch{}}),delete this.ondispose.__removeFuncList)});const N=h.memberSignature(D);N.length<2&&t("Member",D,"does not have a function pointer signature:",N);const J=h.memberKey(D),d=A&&!s.isPtr(Q)?g.argcProxy(h,J,Q,N):Q;if(s.isPtr(d))d&&!s.functionEntry(d)&&t("Pointer",d,"is not a WASM function table entry."),h[J]=d;else{const y=s.installFunction(d,N);h[J]=y,(!h.ondispose||!h.ondispose.__removeFuncList)&&(h.addOnDispose("ondispose.__removeFuncList handler",g.removeFuncList),h.ondispose.__removeFuncList=[]),h.ondispose.__removeFuncList.push(J,y)}return(y,F)=>g(h,y,F,A)};L.installMethodArgcCheck=!1;const H=function(g,h,D=L.installMethodArgcCheck){const Q=new Map;for(const A of Object.keys(h)){const N=h[A],J=Q.get(N);if(J){const d=g.memberKey(A);g[d]=g[g.memberKey(J)]}else L(g,A,N,D),Q.set(N,A)}return g};x.StructType.prototype.installMethod=function(h,D,Q=L.installMethodArgcCheck){return arguments.length<3&&h&&typeof h=="object"?H(this,...arguments):L(this,...arguments)},x.StructType.prototype.installMethods=function(g,h=L.installMethodArgcCheck){return H(this,g,h)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){const t=(...E)=>{throw new i.SQLite3Error(...E)},r=i.capi,s=i.wasm,_=i.util,c=function(E){return(...o)=>E("sqlite3.oo1:",...o)};i.__isUnderTest?c(console.debug.bind(console)):c(i.config.debug),i.__isUnderTest?c(console.warn.bind(console)):c(i.config.warn),i.__isUnderTest?c(console.error.bind(console)):c(i.config.error);const b=new WeakMap,M=new Set,I=new WeakMap,S=(E,o,u)=>{const p=Object.getOwnPropertyDescriptor(E,o);return p?p.value:u},w=function(E,o){return o&&(E instanceof g&&(E=E.pointer),t(o,"sqlite3 result code",o+":",E?r.sqlite3_errmsg(E):r.sqlite3_errstr(o))),arguments[0]},x=s.installFunction("i(ippp)",(function(E,o,u,p){r.SQLITE_TRACE_STMT===E&&console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+o+"["+r.sqlite3_db_filename(o,null)+"]",s.cstrToJs(p))}).bind({counter:0})),L=Object.create(null),H=function E(...o){const u=E.normalizeArgs(...o);let p;if(p=u["sqlite3*"])u["sqlite3*:takeOwnership"]||M.add(this),this.filename=r.sqlite3_db_filename(p,"main");else{let q=u.filename,z=u.vfs,V=u.flags;(typeof q!="string"&&!s.isPtr(q)||typeof V!="string"||z&&typeof z!="string"&&!s.isPtr(z))&&(i.config.error("Invalid DB ctor args",u,arguments),t("Invalid arguments for DB constructor:",arguments,"opts:",u));let R=0;V.indexOf("c")>=0&&(R|=r.SQLITE_OPEN_CREATE|r.SQLITE_OPEN_READWRITE),V.indexOf("w")>=0&&(R|=r.SQLITE_OPEN_READWRITE),R===0&&(R|=r.SQLITE_OPEN_READONLY),R|=r.SQLITE_OPEN_EXRESCODE;const m=s.pstack.pointer;try{const C=s.pstack.allocPtr();let B=r.sqlite3_open_v2(q,C,R,z||s.ptr.null);p=s.peekPtr(C),w(p,B),r.sqlite3_extended_result_codes(p,1),V.indexOf("t")>=0&&r.sqlite3_trace_v2(p,r.SQLITE_TRACE_STMT,x,p)}catch(C){throw p&&r.sqlite3_close_v2(p),C}finally{s.pstack.restore(m)}this.filename=s.isPtr(q)?s.cstrToJs(q):q}if(b.set(this,p),I.set(this,Object.create(null)),!u["sqlite3*"])try{const q=L[r.sqlite3_js_db_vfs(p)||t("Internal error: cannot get VFS for new db handle.")];q&&(q instanceof Function?q(this,i):w(p,r.sqlite3_exec(p,q,0,0,0)))}catch(q){throw this.close(),q}};H.setVfsPostOpenCallback=function(E,o){o instanceof Function||t("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments),L[E]=o},H.normalizeArgs=function(E=":memory:",o="c",u=null){const p={};return arguments.length===1&&arguments[0]&&typeof arguments[0]=="object"?(Object.assign(p,arguments[0]),p.flags===void 0&&(p.flags="c"),p.vfs===void 0&&(p.vfs=null),p.filename===void 0&&(p.filename=":memory:")):(p.filename=E,p.flags=o,p.vfs=u),p};const g=function(...E){H.apply(this,E)};g.dbCtorHelper=H;const h={null:1,number:2,string:3,boolean:4,blob:5};s.bigIntEnabled&&(h.bigint=h.number);const D=function(){h!==arguments[2]&&t(r.SQLITE_MISUSE,"Do not call the Stmt constructor directly. Use DB.prepare()."),this.db=arguments[0],b.set(this,arguments[1]),arguments.length>3&&!arguments[3]&&M.add(this)},Q=function(E){return E.pointer||t("DB has been closed."),E},A=function(E,o){return(o!==(o|0)||o<0||o>=E.columnCount)&&t("Column index",o,"is out of range."),E},N=function(E,o){const u=Object.create(null);switch(u.opt=Object.create(null),o.length){case 1:typeof o[0]=="string"||_.isSQLableTypedArray(o[0])||Array.isArray(o[0])?u.sql=o[0]:o[0]&&typeof o[0]=="object"&&(u.opt=o[0],u.sql=u.opt.sql);break;case 2:u.sql=o[0],u.opt=o[1];break;default:t("Invalid argument count for exec().")}u.sql=_.flexibleString(u.sql),typeof u.sql!="string"&&t("Missing SQL argument or unsupported SQL value type.");const p=u.opt;switch(p.returnValue){case"resultRows":p.resultRows||(p.resultRows=[]),u.returnVal=()=>p.resultRows;break;case"saveSql":p.saveSql||(p.saveSql=[]),u.returnVal=()=>p.saveSql;break;case void 0:case"this":u.returnVal=()=>E;break;default:t("Invalid returnValue value:",p.returnValue)}if(!p.callback&&!p.returnValue&&p.rowMode!==void 0&&(p.resultRows||(p.resultRows=[]),u.returnVal=()=>p.resultRows),p.callback||p.resultRows)switch(p.rowMode===void 0?"array":p.rowMode){case"object":u.cbArg=(q,z)=>{z.columnNames||(z.columnNames=q.getColumnNames([]));const V=q.get([]),R=Object.create(null);for(const m in z.columnNames)R[z.columnNames[m]]=V[m];return R};break;case"array":u.cbArg=q=>q.get([]);break;case"stmt":Array.isArray(p.resultRows)&&t("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference."),u.cbArg=q=>q;break;default:if(_.isInt32(p.rowMode)){u.cbArg=q=>q.get(p.rowMode);break}else if(typeof p.rowMode=="string"&&p.rowMode.length>1&&p.rowMode[0]==="$"){const q=p.rowMode.substr(1);u.cbArg=z=>{const V=z.get(Object.create(null))[q];return V===void 0?t(r.SQLITE_NOTFOUND,"exec(): unknown result column:",q):V};break}t("Invalid rowMode:",p.rowMode)}return u},J=(E,o,u,...p)=>{const q=E.prepare(o);try{const z=q.bind(u).step()?q.get(...p):void 0;return q.reset(),z}finally{q.finalize()}},d=(E,o,u,p)=>E.exec({sql:o,bind:u,rowMode:p,returnValue:"resultRows"});g.checkRc=(E,o)=>w(E,o),g.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return Q(this)},close:function(){const E=this.pointer;if(E){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch{}if(Object.keys(I.get(this)).forEach((o,u)=>{if(u&&u.pointer)try{u.finalize()}catch{}}),b.delete(this),I.delete(this),M.delete(this)||r.sqlite3_close_v2(E),this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch{}delete this.filename}},changes:function(E=!1,o=!1){const u=Q(this).pointer;return E?o?r.sqlite3_total_changes64(u):r.sqlite3_total_changes(u):o?r.sqlite3_changes64(u):r.sqlite3_changes(u)},dbFilename:function(E="main"){return r.sqlite3_db_filename(Q(this).pointer,E)},dbName:function(E=0){return r.sqlite3_db_name(Q(this).pointer,E)},dbVfsName:function(E=0){let o;const u=r.sqlite3_js_db_vfs(Q(this).pointer,E);if(u){const p=new r.sqlite3_vfs(u);try{o=s.cstrToJs(p.$zName)}finally{p.dispose()}}return o},prepare:function(E){Q(this);const o=s.pstack.pointer;let u,p;try{u=s.pstack.alloc(8),g.checkRc(this,r.sqlite3_prepare_v2(this.pointer,E,-1,u,null)),p=s.peekPtr(u)}finally{s.pstack.restore(o)}p||t("Cannot prepare empty SQL.");const q=new D(this,p,h);return I.get(this)[p]=q,q},exec:function(){Q(this);const E=N(this,arguments);if(!E.sql)return t("exec() requires an SQL string.");const o=E.opt,u=o.callback,p=Array.isArray(o.resultRows)?o.resultRows:void 0;let q,z=o.bind,V=!!(E.cbArg||o.columnNames||p);const R=s.scopedAllocPush(),m=Array.isArray(o.saveSql)?o.saveSql:void 0;try{const C=_.isSQLableTypedArray(E.sql);let B=C?E.sql.byteLength:s.jstrlen(E.sql);const Y=s.scopedAlloc(2*s.ptr.size+(B+1)),ne=s.ptr.add(Y,s.ptr.size);let ae=s.ptr.add(ne,s.ptr.size);const ce=s.ptr.add(ae,B);for(C?s.heap8().set(E.sql,ae):s.jstrcpy(E.sql,s.heap8(),ae,B,!1),s.poke8(s.ptr.add(ae,B),0);ae&&s.peek8(ae);){s.pokePtr([Y,ne],0),g.checkRc(this,r.sqlite3_prepare_v3(this.pointer,ae,B,0,Y,ne));const ke=s.peekPtr(Y);if(ae=s.peekPtr(ne),B=Number(s.ptr.add(ce,-ae)),!!ke){if(m&&m.push(r.sqlite3_sql(ke).trim()),q=new D(this,ke,h),z&&q.parameterCount&&(q.bind(z),z=null),V&&q.columnCount){let Ne=Array.isArray(o.columnNames)?0:1;if(V=!1,E.cbArg||p){const Xe=Object.create(null);for(;q.step();X.delete(q)){Ne++===0&&q.getColumnNames(Xe.columnNames=o.columnNames||[]),X.add(q);const at=E.cbArg(q,Xe);if(p&&p.push(at),u&&u.call(o,at,q)===!1)break}X.delete(q)}Ne===0&&q.getColumnNames(o.columnNames)}else q.step();q.reset().finalize(),q=null}}}finally{q&&(X.delete(q),q.finalize()),s.scopedAllocPop(R)}return E.returnVal()},createFunction:function(o,u,p){const q=Xe=>Xe instanceof Function;switch(arguments.length){case 1:p=o,o=p.name,u=p.xFunc||0;break;case 2:q(u)||(p=u,u=p.xFunc||0);break}p||(p={}),typeof o!="string"&&t("Invalid arguments: missing function name.");let z=p.xStep||0,V=p.xFinal||0;const R=p.xValue||0,m=p.xInverse||0;let C;q(u)?(C=!1,(q(z)||q(V))&&t("Ambiguous arguments: scalar or aggregate?"),z=V=null):q(z)?(q(V)||t("Missing xFinal() callback for aggregate or window UDF."),u=null):q(V)?t("Missing xStep() callback for aggregate or window UDF."):t("Missing function-type properties."),C===!1?(q(R)||q(m))&&t("xValue and xInverse are not permitted for non-window UDFs."):q(R)?(q(m)||t("xInverse must be provided if xValue is."),C=!0):q(m)&&t("xValue must be provided if xInverse is.");const B=p.pApp;B!=null&&!s.isPtr(B)&&t("Invalid value for pApp property. Must be a legal WASM pointer value.");const Y=p.xDestroy||0;Y&&!q(Y)&&t("xDestroy property must be a function.");let ne=0;S(p,"deterministic")&&(ne|=r.SQLITE_DETERMINISTIC),S(p,"directOnly")&&(ne|=r.SQLITE_DIRECTONLY),S(p,"innocuous")&&(ne|=r.SQLITE_INNOCUOUS),o=o.toLowerCase();const ae=u||z,ce=S(p,"arity"),ke=typeof ce=="number"?ce:ae.length?ae.length-1:0;let Ne;return C?Ne=r.sqlite3_create_window_function(this.pointer,o,ke,r.SQLITE_UTF8|ne,B||0,z,V,R,m,Y):Ne=r.sqlite3_create_function_v2(this.pointer,o,ke,r.SQLITE_UTF8|ne,B||0,u,z,V,Y),g.checkRc(this,Ne),this},selectValue:function(E,o,u){return J(this,E,o,0,u)},selectValues:function(E,o,u){const p=this.prepare(E),q=[];try{for(p.bind(o);p.step();)q.push(p.get(0,u));p.reset()}finally{p.finalize()}return q},selectArray:function(E,o){return J(this,E,o,[])},selectObject:function(E,o){return J(this,E,o,{})},selectArrays:function(E,o){return d(this,E,o,"array")},selectObjects:function(E,o){return d(this,E,o,"object")},openStatementCount:function(){return this.pointer?Object.keys(I.get(this)).length:0},transaction:function(E){let o="BEGIN";arguments.length>1&&(/[^a-zA-Z]/.test(arguments[0])&&t(r.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier."),o+=" "+arguments[0],E=arguments[1]),Q(this).exec(o);try{const u=E(this);return this.exec("COMMIT"),u}catch(u){throw this.exec("ROLLBACK"),u}},savepoint:function(E){Q(this).exec("SAVEPOINT oo1");try{const o=E(this);return this.exec("RELEASE oo1"),o}catch(o){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),o}},checkRc:function(E){return w(this,E)}},g.wrapHandle=function(E,o=!1){if(!E||!s.isPtr(E))throw new i.SQLite3Error(r.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new g({"sqlite3*":E,"sqlite3*:takeOwnership":!!o})};const y=function(E){return E.pointer||t("Stmt has been closed."),E},F=function(E){let o=h[E==null?"null":typeof E];switch(o){case h.boolean:case h.null:case h.number:case h.string:return o;case h.bigint:return s.bigIntEnabled?o:void 0;default:return _.isBindableTypedArray(E)?h.blob:void 0}},W=function(E){return F(E)||t("Unsupported bind() argument type:",typeof E)},P=function(E,o){const u=typeof o=="number"?o:r.sqlite3_bind_parameter_index(E.pointer,o);return u===0||!_.isInt32(u)?t("Invalid bind() parameter name: "+o):(u<1||u>E.parameterCount)&&t("Bind index",o,"is out of range."),u},X=new Set,ee=new Set,Z=function(E,o){return X.has(E)&&t("Operation is illegal when statement is locked:",o),E},te=function E(o,u,p,q){Z(y(o),"bind()"),E._||(E._tooBigInt=V=>t("BigInt value is too big to store without precision loss:",V),E._={string:function(V,R,m,C){const[B,Y]=s.allocCString(m,!0);return(C?r.sqlite3_bind_blob:r.sqlite3_bind_text)(V.pointer,R,B,Y,r.SQLITE_WASM_DEALLOC)}}),W(q),u=P(o,u);let z=0;switch(q==null?h.null:p){case h.null:z=r.sqlite3_bind_null(o.pointer,u);break;case h.string:z=E._.string(o,u,q,!1);break;case h.number:{let V;_.isInt32(q)?V=r.sqlite3_bind_int:typeof q=="bigint"?_.bigIntFits64(q)?s.bigIntEnabled?V=r.sqlite3_bind_int64:_.bigIntFitsDouble(q)?(q=Number(q),V=r.sqlite3_bind_double):E._tooBigInt(q):E._tooBigInt(q):(q=Number(q),s.bigIntEnabled&&Number.isInteger(q)?V=r.sqlite3_bind_int64:V=r.sqlite3_bind_double),z=V(o.pointer,u,q);break}case h.boolean:z=r.sqlite3_bind_int(o.pointer,u,q?1:0);break;case h.blob:{if(typeof q=="string"){z=E._.string(o,u,q,!0);break}else q instanceof ArrayBuffer?q=new Uint8Array(q):_.isBindableTypedArray(q)||t("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");const V=s.alloc(q.byteLength||1);s.heap8().set(q.byteLength?q:[0],Number(V)),z=r.sqlite3_bind_blob(o.pointer,u,V,q.byteLength,r.SQLITE_WASM_DEALLOC);break}default:i.config.warn("Unsupported bind() argument type:",q),t("Unsupported bind() argument type: "+typeof q)}return z&&g.checkRc(o.db.pointer,z),o};D.prototype={finalize:function(){const E=this.pointer;if(E){Z(this,"finalize()");const o=M.delete(this)?0:r.sqlite3_finalize(E);return delete I.get(this.db)[E],b.delete(this),X.delete(this),ee.delete(this),delete this.parameterCount,delete this.db,o}},clearBindings:function(){return Z(y(this),"clearBindings()"),r.sqlite3_clear_bindings(this.pointer),ee.delete(this),this},reset:function(E){Z(this,"reset()"),E&&this.clearBindings();const o=r.sqlite3_reset(y(this).pointer);return ee.delete(this),w(this.db,o),this},bind:function(){y(this);let E,o;switch(arguments.length){case 1:E=1,o=arguments[0];break;case 2:E=arguments[0],o=arguments[1];break;default:t("Invalid bind() arguments.")}return o===void 0?this:(this.parameterCount||t("This statement has no bindable parameters."),ee.delete(this),o===null?te(this,E,h.null,o):Array.isArray(o)?(arguments.length!==1&&t("When binding an array, an index argument is not permitted."),o.forEach((u,p)=>te(this,p+1,W(u),u)),this):(o instanceof ArrayBuffer&&(o=new Uint8Array(o)),typeof o=="object"&&!_.isBindableTypedArray(o)?(arguments.length!==1&&t("When binding an object, an index argument is not permitted."),Object.keys(o).forEach(u=>te(this,u,W(o[u]),o[u])),this):te(this,E,W(o),o)))},bindAsBlob:function(E,o){y(this),arguments.length===1&&(o=E,E=1);const u=W(o);return h.string!==u&&h.blob!==u&&h.null!==u&&t("Invalid value type for bindAsBlob()"),te(this,E,h.blob,o)},step:function(){Z(this,"step()");const E=r.sqlite3_step(y(this).pointer);switch(E){case r.SQLITE_DONE:return ee.delete(this),!1;case r.SQLITE_ROW:return ee.add(this),!0;default:ee.delete(this),i.config.warn("sqlite3_step() rc=",E,r.sqlite3_js_rc_str(E),"SQL =",r.sqlite3_sql(this.pointer)),g.checkRc(this.db.pointer,E)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{const E=this.step();return this.reset(),E}finally{try{this.finalize()}catch{}}},get:function(E,o){if(ee.has(y(this))||t("Stmt.step() has not (recently) returned true."),Array.isArray(E)){let u=0;const p=this.columnCount;for(;u=Number.MIN_SAFE_INTEGER&&u<=Number.MAX_SAFE_INTEGER?Number(u).valueOf():u}else{const u=r.sqlite3_column_double(this.pointer,E);return(u>Number.MAX_SAFE_INTEGER||ut("The pointer property is read-only.")};Object.defineProperty(D.prototype,"pointer",E),Object.defineProperty(g.prototype,"pointer",E)}Object.defineProperty(D.prototype,"columnCount",{enumerable:!1,get:function(){return r.sqlite3_column_count(this.pointer)},set:()=>t("The columnCount property is read-only.")}),Object.defineProperty(D.prototype,"parameterCount",{enumerable:!1,get:function(){return r.sqlite3_bind_parameter_count(this.pointer)},set:()=>t("The parameterCount property is read-only.")}),D.wrapHandle=function(E,o,u=!1){if(!(E instanceof g)||!E.pointer)throw new i.SQLite3Error(i.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!o||!s.isPtr(o))throw new i.SQLite3Error(i.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new D(E,o,h,!!u)},i.oo1={DB:g,Stmt:D}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){const t=i.util;i.initWorker1API=(function(){const r=(...x)=>{throw new Error(x.join(" "))};globalThis.WorkerGlobalScope instanceof Function||r("initWorker1API() must be run from a Worker thread.");const s=this.sqlite3||r("Missing this.sqlite3 object."),_=s.oo1.DB,c=function(x){let L=b.idMap.get(x);return L||(L="db#"+ ++b.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),b.idMap.set(x,L),L)},b={dbList:[],idSeq:0,idMap:new WeakMap,xfer:[],open:function(x){const L=new _(x);return this.dbs[c(L)]=L,this.dbList.indexOf(L)<0&&this.dbList.push(L),L},close:function(x,L){if(x){delete this.dbs[c(x)];const H=x.filename,g=t.sqlite3__wasm_db_vfs(x.pointer,0);x.close();const h=this.dbList.indexOf(x);h>=0&&this.dbList.splice(h,1),L&&H&&g&&t.sqlite3__wasm_vfs_unlink(g,H)}},post:function(x,L){L&&L.length?(globalThis.postMessage(x,Array.from(L)),L.length=0):globalThis.postMessage(x)},dbs:Object.create(null),getDb:function(x,L=!0){return this.dbs[x]||(L?r("Unknown (or closed) DB ID:",x):void 0)}},M=function(x=b.dbList[0]){return x&&x.pointer?x:r("DB is not opened.")},I=function(x,L=!0){const H=b.getDb(x.dbId,!1)||b.dbList[0];return L?M(H):H},S=function(){return b.dbList[0]&&c(b.dbList[0])},w={open:function(x){const L=Object.create(null),H=x.args||Object.create(null);H.simulateError&&r("Throwing because of simulateError flag.");const g=Object.create(null);L.vfs=H.vfs,L.filename=H.filename||"";const h=b.open(L);return g.filename=h.filename,g.persistent=!!s.capi.sqlite3_js_db_uses_vfs(h.pointer,"opfs"),g.dbId=c(h),g.vfs=h.dbVfsName(),g},close:function(x){const L=I(x,!1),H={filename:L&&L.filename};if(L){const g=x.args&&typeof x.args=="object"?!!x.args.unlink:!1;b.close(L,g)}return H},exec:function(x){const L=typeof x.args=="string"?{sql:x.args}:x.args||Object.create(null);L.rowMode==="stmt"?r("Invalid rowMode for 'exec': stmt mode","does not work in the Worker API."):L.sql||r("'exec' requires input SQL.");const H=I(x);(L.callback||Array.isArray(L.resultRows))&&(H._blobXfer=b.xfer);const g=L.callback;let h=0;const D=!!L.columnNames;typeof g=="string"&&(D||(L.columnNames=[]),L.callback=function(Q,A){b.post({type:g,columnNames:L.columnNames,rowNumber:++h,row:Q},b.xfer)});try{const Q=L.countChanges?H.changes(!0,L.countChanges===64):void 0;H.exec(L),Q!==void 0&&(L.changeCount=H.changes(!0,L.countChanges===64)-Q);const A=L.lastInsertRowId?s.capi.sqlite3_last_insert_rowid(H):void 0;A!==void 0&&(L.lastInsertRowId=A),L.callback instanceof Function&&(L.callback=g,b.post({type:g,columnNames:L.columnNames,rowNumber:null,row:void 0}))}finally{delete H._blobXfer,L.callback&&(L.callback=g)}return L},"config-get":function(){const x=Object.create(null),L=s.config;return["bigIntEnabled"].forEach(function(H){Object.getOwnPropertyDescriptor(L,H)&&(x[H]=L[H])}),x.version=s.version,x.vfsList=s.capi.sqlite3_js_vfs_list(),x},export:function(x){const L=I(x),H={byteArray:s.capi.sqlite3_js_db_export(L.pointer),filename:L.filename,mimetype:"application/x-sqlite3"};return b.xfer.push(H.byteArray.buffer),H},toss:function(x){r("Testing worker exception")}};globalThis.onmessage=async function(x){x=x.data;let L,H=x.dbId,g=x.type;const h=performance.now();try{w.hasOwnProperty(g)&&w[g]instanceof Function?L=await w[g](x):r("Unknown db worker message type:",x.type)}catch(D){g="error",L={operation:x.type,message:D.message,errorClass:D.name,input:x},D.stack&&(L.stack=typeof D.stack=="string"?D.stack.split(/\n\s*/):D.stack)}H||(H=L.dbId||S()),b.post({type:g,dbId:H,messageId:x.messageId,workerReceivedTime:h,workerRespondTime:performance.now(),departureTime:x.departureTime,result:L},b.xfer)},globalThis.postMessage({type:"sqlite3-api",result:"worker1-ready"})}).bind({sqlite3:i})}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){const t=i.wasm,r=i.capi,s=i.util.toss3,_=Object.create(null);i.vfs=_,r.sqlite3_vfs.prototype.registerVfs=function(c=!1){this instanceof i.capi.sqlite3_vfs||s("Expecting a sqlite3_vfs-type argument.");const b=r.sqlite3_vfs_register(this,c?1:0);return b&&s("sqlite3_vfs_register(",this,") failed with rc",b),this.pointer!==r.sqlite3_vfs_find(this.$zName)&&s("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",this),this},_.installVfs=function(c){let b=0;const M=["io","vfs"];for(const I of M){const S=c[I];S&&(++b,S.struct.installMethods(S.methods,!!S.applyArgcCheck),I==="vfs"&&(!S.struct.$zName&&typeof S.name=="string"&&S.struct.addOnDispose(S.struct.$zName=t.allocCString(S.name)),S.struct.registerVfs(!!S.asDefault)))}return b||s("Misuse: installVfs() options object requires at least","one of:",M),this}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(!i.wasm.exports.sqlite3_declare_vtab)return;const t=i.wasm,r=i.capi,s=i.util.toss3,_=Object.create(null);i.vtab=_;const c=r.sqlite3_index_info;c.prototype.nthConstraint=function(I,S=!1){if(I<0||I>=this.$nConstraint)return!1;const w=t.ptr.add(this.$aConstraint,c.sqlite3_index_constraint.structInfo.sizeof*I);return S?w:new c.sqlite3_index_constraint(w)},c.prototype.nthConstraintUsage=function(I,S=!1){if(I<0||I>=this.$nConstraint)return!1;const w=t.ptr.add(this.$aConstraintUsage,c.sqlite3_index_constraint_usage.structInfo.sizeof*I);return S?w:new c.sqlite3_index_constraint_usage(w)},c.prototype.nthOrderBy=function(I,S=!1){if(I<0||I>=this.$nOrderBy)return!1;const w=t.ptr.add(this.$aOrderBy,c.sqlite3_index_orderby.structInfo.sizeof*I);return S?w:new c.sqlite3_index_orderby(w)};const b=function(I,S){return(function(w,x=!1){if(arguments.length===0&&(w=new S),w instanceof S)return this.set(w.pointer,w),w;t.isPtr(w)||i.SQLite3Error.toss("Invalid argument to",I+"()");let L=this.get(w);return x&&this.delete(w),L}).bind(new Map)},M=function(I,S){const w=b(I,S);return Object.assign(Object.create(null),{StructType:S,create:x=>{const L=w();return t.pokePtr(x,L.pointer),L},get:x=>w(x),unget:x=>w(x,!0),dispose:x=>w(x,!0)?.dispose?.()})};_.xVtab=M("xVtab",r.sqlite3_vtab),_.xCursor=M("xCursor",r.sqlite3_vtab_cursor),_.xIndexInfo=I=>new r.sqlite3_index_info(I),_.xError=function I(S,w,x){if(I.errorReporter instanceof Function)try{I.errorReporter("sqlite3_module::"+S+"(): "+w.message)}catch{}let L;return w instanceof i.WasmAllocError?L=r.SQLITE_NOMEM:arguments.length>2?L=x:w instanceof i.SQLite3Error&&(L=w.resultCode),L||r.SQLITE_ERROR},_.xError.errorReporter=i.config.error.bind(i.config),_.xRowid=(I,S)=>t.poke(I,S,"i64"),_.setupModule=function(I){let S=!1;const w=this instanceof r.sqlite3_module?this:I.struct||(S=new r.sqlite3_module);try{const x=I.methods||s("Missing 'methods' object.");for(const L of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){const H=L[0],g=L[1];x[H]===!0?x[H]=x[g]:x[g]===!0&&(x[g]=x[H])}if(I.catchExceptions){const L=function(h,D){return["xConnect","xCreate"].indexOf(h)>=0?function(Q,A,N,J,d,y){try{return D(...arguments)||0}catch(F){return F instanceof i.WasmAllocError||(t.dealloc(t.peekPtr(y)),t.pokePtr(y,t.allocCString(F.message))),_.xError(h,F)}}:function(...Q){try{return D(...Q)||0}catch(A){return _.xError(h,A)}}},H=["xCreate","xConnect","xBestIndex","xDisconnect","xDestroy","xOpen","xClose","xFilter","xNext","xEof","xColumn","xRowid","xUpdate","xBegin","xSync","xCommit","xRollback","xFindFunction","xRename","xSavepoint","xRelease","xRollbackTo","xShadowName"],g=Object.create(null);for(const h of H){const D=x[h];if(D instanceof Function)h==="xConnect"&&x.xCreate===D?g[h]=x.xCreate:h==="xCreate"&&x.xConnect===D?g[h]=x.xConnect:g[h]=L(h,D);else continue}w.installMethods(g,!1)}else w.installMethods(x,!!I.applyArgcCheck);if(w.$iVersion===0){let L;typeof I.iVersion=="number"?L=I.iVersion:w.$xIntegrity?L=4:w.$xShadowName?L=3:w.$xSavePoint||w.$xRelease||w.$xRollbackTo?L=2:L=1,w.$iVersion=L}}catch(x){throw S&&S.dispose(),x}return w},r.sqlite3_module.prototype.setupModule=function(I){return _.setupModule.call(this,I)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(i.config.disable?.vfs?.kvvfs)return;const t=i.capi,r=t.sqlite3_kvvfs_methods,s=t.KVVfsFile,_=i.capi.sqlite3_vfs_find("kvvfs");if(delete t.sqlite3_kvvfs_methods,delete t.KVVfsFile,!_)return;const c=i.util,b=i.wasm,M=c.toss3,I=new r(b.exports.sqlite3__wasm_kvvfs_methods());c.assert(32<=I.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+I.$nKeySize);const S=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:b.allocCString("jrnl"),zKeySz:b.allocCString("sz"),keySize:I.$nKeySize,buffer:Object.assign(Object.create(null),{n:I.$nBufferSize,pool:Object.create(null)})});S.memBuffer=(O=0)=>S.buffer.pool[O]??=b.alloc(S.buffer.n),S.memBufferFree=O=>{const j=S.buffer.pool[O];j&&(b.dealloc(j),delete S.buffer.pool[O])};const w=()=>{},x=i.__isUnderTest?(...O)=>i.config.debug?.("kvvfs:",...O):w,L=(...O)=>i.config.warn?.("kvvfs:",...O),H=(...O)=>i.config.error?.("kvvfs:",...O);class g{#e=Object.create(null);#i=null;#s=0;constructor(){this.clear()}#t(){return this.#i??=Object.keys(this.#e)}key(j){return j<0||j>=this.#s?null:this.#t()[j]}getItem(j){return this.#e[j]??null}setItem(j,G){j in this.#e||(++this.#s,this.#i=null),this.#e[j]=""+G}removeItem(j){j in this.#e&&(delete this.#e[j],--this.#s,this.#i=null)}clear(){this.#e=Object.create(null),this.#i=null,this.#s=0}get length(){return this.#s}}const h=O=>O==="local"||O==="session",D=O=>h(O)?"kvvfs-"+O+"-":"",Q=function(O,j=!1){if(h(O))return;const G=new Blob([O]).size;G||M(t.SQLITE_MISUSE,"Empty name is not permitted.");let $=S.keySize-1;S.rxJournalSuffix.test(O)?j||M(t.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix."):["-wal","-shm"].filter(le=>O.endsWith(le)).length?M(t.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix."):$-=8,G>$&&M(t.SQLITE_RANGE,"Storage name is too long. Limit =",$);let se;for(se=0;seObject.assign(Object.create(null),{jzClass:O,refc:1,deleteAtRefc0:!1,storage:j||new g,keyPrefix:D(O),files:[],listeners:void 0}),N=i.kvvfs=Object.create(null);i.__isUnderTest&&(N.log=Object.assign(Object.create(null),{xOpen:!1,xClose:!1,xWrite:!1,xRead:!1,xSync:!1,xAccess:!1,xFileControl:!1,xRcrdRead:!1,xRcrdWrite:!1,xRcrdDelete:!1}));const J=function(O){const j=S.rxJournalSuffix.test(O.jzClass)?O.jzClass.replace(S.rxJournalSuffix,""):O.jzClass+"-journal";N?.log?.xClose&&x("cleaning up storage handles [",O.jzClass,j,"]",O),delete S.storagePool[O.jzClass],delete S.storagePool[j],i.__isUnderTest||(delete O.storage,delete O.refc)},d=O=>S.storagePool[O.jzClass]=S.storagePool[O.jzClass+"-journal"]=O,y=".";S.storagePool=Object.assign(Object.create(null),{[y]:A(y)}),globalThis.Storage&&(globalThis.localStorage instanceof globalThis.Storage&&(S.storagePool.local=A("local",globalThis.localStorage)),globalThis.sessionStorage instanceof globalThis.Storage&&(S.storagePool.session=A("session",globalThis.sessionStorage))),S.builtinStorageNames=Object.keys(S.storagePool);const F=O=>S.builtinStorageNames.indexOf(O)>-1;for(const O of Object.keys(S.storagePool)){const j=S.storagePool[O];S.storagePool[O+"-journal"]=j}S.setError=(O=void 0,j=t.SQLITE_ERROR)=>O?(S.lastError=O,O.resultCode|0||j):(delete S.lastError,0),S.popError=()=>{const O=S.lastError;return delete S.lastError,O};const W=O=>{L("kvvfs.listener handler threw:",O)},P=b.exports.sqlite3__wasm_kvvfs_decode,X=b.exports.sqlite3__wasm_kvvfs_encode,ee=async function(O,j,...G){try{j.keyPrefix&&G[0]&&(G[0]=G[0].replace(j.keyPrefix,""));let $,se,le,_e;for(const oe of j.listeners){const pe=Object.create(null);pe.storageName=j.jzClass,pe.type=O,oe.decodePages;const we=oe.events[O];if(we){if(!oe.includeJournal&&G[0]==="jrnl")continue;if(O==="write"&&oe.decodePages&&+G[0]>0){if(pe.data=[G[0]],_e?.[G[0]]){pe.data[1]=_e[G[0]];continue}$??=new TextEncoder("utf-8"),se??=S.memBuffer(10),le??=S.memBuffer(11);const Pe=$.encode(G[1]),be=b.heap8u();be.set(Pe,Number(se)),be[b.ptr.addn(se,Pe.length)]=0;const Ue=P(se,le,S.buffer.n);if(Ue>0)_e??=Object.create(null),_e[G[0]]=pe.data[1]=be.slice(Number(le),b.ptr.addn(le,Ue));else continue}else pe.data=G.length?G.length===1?G[0]:G:void 0;try{we(pe)?.catch?.(W)}catch(Pe){L("notifyListeners [",j.jzClass,"]",O,Pe)}}}}catch($){W($)}},Z=O=>typeof O=="string"?S.storagePool[O]:S.storagePool[b.cstrToJs(O)],te=b.exports.sqlite3__wasm_kvvfsMakeKey,E=(O,j,G)=>j&&O.keyPrefix?te(j,G):G,o=(O,j,G)=>b.cstrToJs(E(O,j,G)),u=O=>+O.storage.getItem(O.keyPrefix+"sz"),p=new Map,q={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},z=new t.sqlite3_vfs(I.$pVfs),V=new t.sqlite3_io_methods(I.$pIoDb),R=new t.sqlite3_io_methods(I.$pIoJrnl),m=Object.create(null),C=Object.assign(Object.create(null),{pFileHandles:p,cache:S,storageForZClass:Z,KVVfsStorage:g,disablePageSizeChange:!0});N.log&&(N.internal=C);const B={recordHandler:{xRcrdRead:(O,j,G,$)=>{try{const se=b.cstrToJs(O),le=Z(se);if(!le)return-1;const _e=o(le,O,j);N?.log?.xRcrdRead&&L("xRcrdRead",se,_e,$,le);const oe=le.storage.getItem(_e);if(oe===null)return-1;const pe=oe.length;if($<=0)return pe;if($===1)return b.poke(G,0),pe;$+1{try{const $=Z(O),se=o($,O,j),le=b.cstrToJs(G);return N?.log?.xRcrdWrite&&L("xRcrdWrite",se,$),$.storage.setItem(se,le),$.listeners&&ee("write",$,se,le),0}catch($){return H("kvrecordWrite()",$),S.setError($,t.SQLITE_IOERR)}},xRcrdDelete:(O,j)=>{try{const G=Z(O),$=o(G,O,j);return N?.log?.xRcrdDelete&&L("xRcrdDelete",$,G),G.storage.removeItem($),G.listeners&&ee("delete",G,$),0}catch(G){return H("kvrecordDelete()",G),S.setError(G,t.SQLITE_IOERR)}}},vfs:{xOpen:function(O,j,G,$,se){S.popError();let le;try{j||(le=b.allocCString(""+G+"."+(Math.random()*1e5|0)),j=le);const _e=b.cstrToJs(j);N?.log?.xOpen&&x("xOpen",_e,"flags =",$),Q(_e,!0),$&(t.SQLITE_OPEN_MAIN_DB|t.SQLITE_OPEN_TEMP_DB|t.SQLITE_OPEN_TRANSIENT_DB)&&S.rxJournalSuffix.test(_e)&&M(t.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let oe=Z(_e);!oe&&!($&t.SQLITE_OPEN_CREATE)&&M(t.SQLITE_ERROR,"Storage not found:",_e);const pe=q.vfs.xOpen(O,j,G,$,se);if(pe)return pe;let we=!!(t.SQLITE_OPEN_DELETEONCLOSE&$);b.isPtr(arguments[1])&&t.sqlite3_uri_boolean(j,"delete-on-close",0)&&(we=!0);const Pe=new s(G);if(c.assert(Pe.$zClass,"Missing f.$zClass"),Pe.addOnDispose(le),le=void 0,oe)++oe.refc,oe.files.push(Pe),b.poke32(se,$);else{b.poke32(se,$|t.SQLITE_OPEN_CREATE),c.assert(!Pe.$isJournal,"Opening a journal before its db? "+_e);const be=_e.replace(S.rxJournalSuffix,"");oe=A(be),d(oe),oe.files.push(Pe),oe.deleteAtRefc0=we,N?.log?.xOpen&&x("xOpen installed storage handle [",be,be+"-journal","]",oe)}return p.set(G,{store:oe,file:Pe,jzClass:_e}),oe.listeners&&ee("open",oe,oe.files.length),0}catch(_e){return L("xOpen:",_e),S.setError(_e)}finally{le&&b.dealloc(le)}},xDelete:function(O,j,G){S.popError();try{const $=b.cstrToJs(j);return S.rxJournalSuffix.test($)&&m.xRcrdDelete(j,S.zKeyJrnl),0}catch($){return L("xDelete",$),S.setError($)}},xAccess:function(O,j,G,$){S.popError();try{const se=Z(j),le=se?.jzClass||b.cstrToJs(j);if(N?.log?.xAccess&&x("xAccess",le,"flags =",G,"*pResOut =",b.peek32($),"store =",se),!se)try{Q(le)}catch{return b.poke32($,0),0}if(se){const _e=se.keyPrefix+(S.rxJournalSuffix.test(le)?"jrnl":"1"),oe=se.storage.getItem(_e)?0:1;b.poke32($,oe)}else b.poke32($,0);return 0}catch(se){return H("xAccess",se),S.setError(se)}},xRandomness:function(O,j,G){const $=b.heap8u();let se=0;const le=Number(G);for(;sej&&b.poke8(b.ptr.add(G,j,-1),0),x("set xGetLastError",$.message),$.resultCode|0||t.SQLITE_IOERR}catch{return t.SQLITE_NOMEM}finally{b.scopedAllocPop(se)}}return 0}},ioDb:{xClose:function(O){S.popError();try{const j=p.get(O);if(N?.log?.xClose&&x("xClose",O,j),j){p.delete(O);const G=j.store;G.files=G.files.filter($=>$!==j.file),--G.refc<=0&&G.deleteAtRefc0&&J(G),q.ioDb.xClose(O),j.file.dispose(),G.listeners&&ee("close",G,G.files.length)}return 0}catch(j){return H("xClose",j),S.setError(j)}},xFileControl:function(O,j,G){S.popError();try{const $=p.get(O);if(c.assert($,"Missing KVVfsFile handle"),N?.log?.xFileControl&&x("xFileControl",$,"op =",j),j===t.SQLITE_FCNTL_PRAGMA&&C.disablePageSizeChange){const le=b.peekPtr(b.ptr.add(G,b.ptr.size));if(b.cstrToJs(le)==="page_size"){N?.log?.xFileControl&&x("xFileControl pragma",b.cstrToJs(le));const _e=b.peekPtr(b.ptr.add(G,2*b.ptr.size));if(_e)return N?.log?.xFileControl&&L("xFileControl pragma",$,"NOT setting page size to",b.cstrToJs(_e)),$.file.$szPage=-1,0;if($.file.$szPage>0)return N?.log?.xFileControl&&L("xFileControl",$,"getting page size",$.file.$szPage),b.pokePtr(G,b.allocCString(""+$.file.$szPage)),0}}const se=q.ioDb.xFileControl(O,j,G);return se==0&&t.SQLITE_FCNTL_SYNC===j&&$.store.listeners&&ee("sync",$.store,!1),se}catch($){return H("xFileControl",$),S.setError($)}},xSync:function(O,j){S.popError();try{const G=p.get(O);N?.log?.xSync&&x("xSync",G),c.assert(G,"Missing KVVfsFile handle");const $=q.ioDb.xSync(O,j);return $==0&&G.store.listeners&&ee("sync",G.store,!0),$}catch(G){return H("xSync",G),S.setError(G)}}},ioJrnl:{xClose:!0}};try{c.assert(S.buffer.n>1024*129,"Heap buffer is not large enough");for(const O of Object.entries(B.recordHandler)){const j=O[0],G=O[1];m[j]=G,I[I.memberKey(j)]=b.installFunction(I.memberSignature(j),G)}for(const O of Object.entries(B.vfs)){const j=O[0],G=O[1],$=z.memberKey(j),se=z.structInfo.members[j]||c.toss("Missing pVfs.structInfo[",j,"]");q.vfs[j]=b.functionEntry(z[$]),z[$]=b.installFunction(se.signature,G)}for(const O of Object.entries(B.ioDb)){const j=O[0],G=O[1],$=V.memberKey(j);q.ioDb[j]=b.functionEntry(V[$])||c.toss("Missing native pIoDb[",$,"]"),V[$]=b.installFunction(V.memberSignature(j),G)}for(const O of Object.entries(B.ioJrnl)){const j=O[0],G=O[1],$=R.memberKey(j);q.ioJrnl[j]=b.functionEntry(R[$])||c.toss("Missing native pIoJrnl[",$,"]"),G===!0?R[$]=V[$]||c.toss("Missing copied pIoDb[",$,"]"):R[$]=b.installFunction(R.memberSignature(j),G)}}finally{I.dispose(),z.dispose(),V.dispose(),R.dispose()}const Y=function O(j){if(j==="")return O("local")+O("session");const G=Z(j);if(!G)return 0;G.files.length&&(globalThis.localStorage===G.storage||globalThis.sessionStorage===G.storage||M(t.SQLITE_ACCESS,"Cannot clear in-use database storage."));const $=G.storage,se=[];let le,_e=$.length;for(le=0;le<_e;++le){const oe=$.key(le);(!G.keyPrefix||oe.startsWith(G.keyPrefix))&&se.push(oe)}return se.forEach(oe=>$.removeItem(oe)),se.length},ne=function O(j){if(j==="")return O("local")+O("session");const G=Z(j);if(!G)return 0;const $=G.storage;let se,le=0;for(se=0;se<$.length;++se){const _e=$.key(se);(!G.keyPrefix||_e.startsWith(G.keyPrefix))&&(le+=_e.length,le+=$.getItem(_e).length)}return le*2},ae=function(...j){let G;j.length===1&&typeof j[0]=="object"?G=j[0]:j.length&&(G=Object.assign(Object.create(null),{name:j[0]}));const $=G?Z(G.name):null;$||M(t.SQLITE_NOTFOUND,"There is no kvvfs storage named",G?.name);const se=$.storage,le=Object.assign(Object.create(null),{name:$.jzClass,timestamp:Date.now(),pages:[]}),_e=Object.create(null),oe=$.keyPrefix,pe=oe?/^kvvfs-[^-]+-(\w+)/:void 0;let we=0,Pe=se.length;for(;we+be).sort().forEach(be=>le.pages.push(_e[be])),le},ce=function(O,j=!1){!O?.timestamp||!O.name||O.size===void 0||!Array.isArray(O.pages)?M(t.SQLITE_MISUSE,"Malformed export object."):(!O.size||O.size!==(O.size|0)||O.size>=2147483647)&&M(t.SQLITE_RANGE,"Invalid db size: "+O.size),Q(O.name);let G=Z(O.name);const $=!G;G?(j?!G.files||!G.jzClass?M(t.SQLITE_ERROR,"Internal storage object",O.name,"seems to be malformed."):G.files.length&&M(t.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use."):M(t.SQLITE_ACCESS,"Storage '"+O.name+"' already exists and","overwrite was not specified."),Y(O.name)):G=A(O.name);const se=D(O.name);let le;try{const _e=G.storage;_e.setItem(se+"sz",O.size),O.journal&&_e.setItem(se+"jrnl",O.journal),O.pages[0]instanceof Uint8Array?O.pages.forEach((oe,pe)=>{const we=oe.length;le??=S.memBuffer(1);const Pe=S.memBuffer(0),be=b.heap8u();be.set(oe,Number(Pe)),be[b.ptr.addn(Pe,we)]=0;const Ue=X(Pe,we,le);c.assert(Ue_e.setItem(se+(pe+1),oe)),$&&d(G)}catch{if(!$)try{Y(O.name)}catch{}}finally{le&&S.memBufferFree(1)}return this},ke=function(O){let j=Z(O);if(j){++j.refc;return}Q(O),d(A(O))},Ne=function(O){const j=Z(O);return!j||h(j.jzClass)||F(j.jzClass)||S.rxJournalSuffix.test(O)?!1:j.refc>j.files.length||j.files.length===0?(--j.refc<=0&&J(j),!0):!1},Xe=function(O){(!O||typeof O!="object")&&M(t.SQLITE_MISUSE,"Expecting a listener object.");let j=Z(O.storage);j||(O.storage&&O.reserve?(ke(O.storage),j=Z(O.storage),c.assert(j,"Unexpectedly cannot fetch reserved storage "+O.storage)):M(t.SQLITE_NOTFOUND,"No such storage:",O.storage)),O.events&&(j.listeners??=[]).push(O)},at=function(O){const j=Z(O?.storage);if(j?.listeners&&O.events){const G=j.listeners.length;j.listeners=j.listeners.filter(se=>se!==O);const $=G>j.listeners.length;return j.listeners.length||(j.listeners=void 0),$}return!1};if(i.kvvfs.reserve=ke,i.kvvfs.import=ce,i.kvvfs.export=ae,i.kvvfs.unlink=Ne,i.kvvfs.listen=Xe,i.kvvfs.unlisten=at,i.kvvfs.exists=O=>!!Z(O),i.kvvfs.estimateSize=ne,i.kvvfs.clear=Y,globalThis.Storage&&(t.sqlite3_js_kvvfs_size=(O="")=>ne(O),t.sqlite3_js_kvvfs_clear=(O="")=>Y(O)),i.oo1?.DB){const O=i.oo1.DB;i.oo1.JsStorageDb=function(G=i.oo1.JsStorageDb.defaultStorageName){const $=O.dbCtorHelper.normalizeArgs(...arguments);switch($.vfs="kvvfs",$.filename){case":sessionStorage:":$.filename="session";break;case":localStorage:":$.filename="local";break}const se=/(file:(\/\/)?)([^?]+)/.exec($.filename);Q(se?se[3]:$.filename),O.dbCtorHelper.call(this,$)},i.oo1.JsStorageDb.defaultStorageName=S.storagePool.session?"session":y;const j=i.oo1.JsStorageDb;j.prototype=Object.create(O.prototype),j.clearStorage=Y,j.prototype.clearStorage=function(){return j.clearStorage(this.affirmOpen().dbFilename(),!0)},j.storageSize=ne,j.prototype.storageSize=function(){return j.storageSize(this.affirmOpen().dbFilename(),!0)}}if(i.__isUnderTest&&i.vtab){const O=Object.assign(Object.create(null),{rowid:{type:"INTEGER"},name:{type:"TEXT"},nRef:{type:"INTEGER"},nOpen:{type:"INTEGER"},isTransient:{type:"INTEGER"},dbSize:{type:"INTEGER"}});Object.keys(O).forEach((_e,oe)=>O[_e].colId=oe);const j=i.vtab,G=Object.assign(Object.create(null),{row:function(){return S.storagePool[this.names[this.rowid]]}});Object.assign(Object.create(G),{rowid:0,names:Object.keys(S.storagePool).filter(_e=>!S.rxJournalSuffix.test(_e))});const $=function(_e,oe){const pe=_e instanceof t.sqlite3_vtab_cursor?_e:j.xCursor.get(_e);return(oe||!pe.vTabState)&&(pe.vTabState=Object.assign(Object.create(G),{rowid:0,names:Object.keys(S.storagePool).filter(we=>!S.rxJournalSuffix.test(we))})),pe.vTabState},se=()=>{},le=function _e(){return _e.mod??=new i.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(oe,pe,we,Pe,be,Ue){try{const Ye=[];Object.keys(O).forEach(Ze=>{Ye.push(Ze+" "+O[Ze].type)});const pt=t.sqlite3_declare_vtab(oe,"CREATE TABLE ignored("+Ye.join(",")+")");if(pt===0){const Ze=j.xVtab.create(be);c.assert(Ze===j.xVtab.get(b.peekPtr(be)),"output pointer check failed")}return pt}catch(Ye){return j.xError("xConnect",Ye,t.SQLITE_ERROR)}},xCreate:b.ptr.null,xDisconnect:function(oe){return j.xVtab.dispose(oe),0},xOpen:function(oe,pe){return j.xCursor.create(pe),0},xClose:function(oe){const pe=j.xCursor.unget(oe);return delete pe.vTabState,pe.dispose(),0},xNext:function(oe){const pe=j.xCursor.get(oe);return++$(pe).rowid,0},xColumn:function(oe,pe,we){const Pe=$(oe),be=Pe.row();switch(c.assert(be,"Unexpected xColumn call"),we){case O.rowid.colId:t.sqlite3_result_int(pe,Pe.rowid);break;case O.name.colId:t.sqlite3_result_text(pe,be.jzClass,-1,t.SQLITE_TRANSIENT);break;case O.nRef.colId:t.sqlite3_result_int(pe,be.refc);break;case O.nOpen.colId:t.sqlite3_result_int(pe,be.files.length);break;case O.isTransient.colId:t.sqlite3_result_int(pe,!!be.deleteAtRefc0);break;case O.dbSize.colId:t.sqlite3_result_int(pe,u(be));break;default:return t.sqlite3_result_error(pe,"Invalid column id: "+we),t.SQLITE_RANGE}return 0},xRowid:function(oe,pe){const we=$(oe);return j.xRowid(pe,we.rowid),0},xEof:function(oe){const pe=$(oe);return se("xEof?="+!pe.row(),...arguments),!pe.row()},xFilter:function(oe,pe,we,Pe,be){return $(oe,!0),0},xBestIndex:function(oe,pe){const we=new t.sqlite3_index_info(pe);return we.$estimatedRows=S.storagePool.size,we.$estimatedCost=1,we.dispose(),0}}})};i.kvvfs.create_module=function(_e,oe="sqlite_kvvfs"){return t.sqlite3_create_module(_e,oe,le(),b.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(i.config.disable?.vfs?.opfs&&i.config.disable.vfs["opfs-vfs"])return;const t=i.util.toss;i.capi;const r=i.util;i.wasm;const s=i.opfs=Object.create(null);s.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,s.getRootDir=async function c(){return c.promise??=navigator.storage.getDirectory().then(b=>(s.rootDirectory=b,b)).catch(b=>{throw delete c.promise,b})},s.getResolvedPath=function(c,b){const M=new URL(c,"file://irrelevant").pathname;return b?M.split("/").filter(I=>!!I):M},s.getDirForFilename=async function(b,M=!1){const I=s.getResolvedPath(b,!0),S=I.pop();let w=await s.getRootDir();for(const x of I)x&&(w=await w.getDirectoryHandle(x,{create:!!M}));return[w,S]},s.mkdir=async function(c){try{return await s.getDirForFilename(c+"/filepart",!0),!0}catch{return!1}},s.entryExists=async function(c){try{const[b,M]=await s.getDirForFilename(c);return await b.getFileHandle(M),!0}catch{return!1}},s.randomFilename=function c(b=16){c._chars||(c._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",c._n=c._chars.length);const M=[];let I=0;for(;I=15&&(r.affirmDbHeader(x),L=!0),S.write(x,{at:w}),w+=x.byteLength;if((w<512||w%512!==0)&&t("Input size",w,"is not correct for an SQLite database."),!L){const H=new Uint8Array(20);S.read(H,{at:0}),r.affirmDbHeader(H)}return S.write(new Uint8Array([1,1]),{at:18}),w}catch(H){throw await S.close(),S=void 0,await M.removeEntry(I).catch(()=>{}),H}finally{S&&await S.close()}};s.importDb=async function(c,b){if(b instanceof Function)return _(c,b);b instanceof ArrayBuffer&&(b=new Uint8Array(b)),r.affirmIsDb(b);const M=b.byteLength,[I,S]=await s.getDirForFilename(c,!0);let w,x=0;try{return w=await(await I.getFileHandle(S,{create:!0})).createSyncAccessHandle(),w.truncate(0),x=w.write(b,{at:0}),x!=M&&t("Expected to write "+M+" bytes but wrote "+x+"."),w.write(new Uint8Array([1,1]),{at:18}),x}catch(L){throw w&&(await w.close(),w=void 0),await I.removeEntry(S).catch(()=>{}),L}finally{w&&await w.close()}},s.vfsInstallationFeatureCheck=function(c){!globalThis.SharedArrayBuffer||!globalThis.Atomics?t("Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics.","The server must emit the COOP/COEP response headers to enable those.","See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep"):typeof WorkerGlobalScope>"u"?t("The OPFS sqlite3_vfs cannot run in the main thread","because it requires Atomics.wait()."):!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle||!navigator?.storage?.getDirectory?t("Missing required OPFS APIs."):c==="opfs-wl"&&!globalThis.Atomics.waitAsync&&t("The",c,"VFS requires Atomics.waitAsync(), which is not available.")},s.initOptions=function(b,M){const I=new URL(globalThis.location.href).searchParams;if(!I.has(b+"-disable")){try{s.vfsInstallationFeatureCheck(b)}catch{return}return M=r.nu(M),M.vfsName=b,M.verbose??=I.has("opfs-verbose")?+I.get("opfs-verbose"):1,M.sanityChecks??=I.has("opfs-sanity-check"),s.proxyUri||(s.proxyUri="sqlite3-opfs-async-proxy.js",i.scriptInfo?.sqlite3Dir&&(s.proxyUri=i.scriptInfo.sqlite3Dir+s.proxyUri)),M.proxyUri??=s.proxyUri,typeof M.proxyUri=="function"&&(M.proxyUri=M.proxyUri()),s.options=M}},s.createVfsState=function(){const c=r.nu(),b=s.options;c.verbose=b.verbose;const M=[i.config.error,i.config.warn,i.config.log],I=b.vfsName||t("Maintenance required: missing VFS name"),S=(P,...X)=>{c.verbose>P&&M[P](I+":",...X)},w=(...P)=>S(2,...P),x=(...P)=>S(1,...P),L=(...P)=>S(0,...P),H=i.capi,g=i.wasm,h=c.vfs=new H.sqlite3_vfs,D=h.ioMethods=new H.sqlite3_io_methods;D.$iVersion=1,h.$iVersion=2,h.$szOsFile=H.sqlite3_file.structInfo.sizeof,h.$mxPathname=1024,h.$zName=g.allocCString(I),h.addOnDispose("$zName",h.$zName,D),h.metrics=r.nu({counters:r.nu(),dump:function(){let P,X=0,ee=0,Z=0;for(P in c.opIds){const te=Q[P];X+=te.count,ee+=te.time,Z+=te.wait,te.avgTime=te.count&&te.time?te.time/te.count:0,te.avgWait=te.count&&te.wait?te.wait/te.count:0}i.config.log(globalThis.location.href,"metrics for",globalThis.location.href,":",Q,` +Total of`,X,"op(s) for",ee,"ms (incl. "+Z+" ms of waiting on the async side)"),i.config.log("Serialization metrics:",h.metrics.counters.s11n),h.worker?.postMessage?.({type:"opfs-async-metrics"})},reset:function(){let P;const X=te=>te.count=te.time=te.wait=0,ee=h.metrics.counters;for(P in c.opIds)X(ee[P]=Object.create(null));let Z=ee.s11n=Object.create(null);Z=Z.serialize=Object.create(null),Z.count=Z.time=0,Z=ee.s11n.deserialize=Object.create(null),Z.count=Z.time=0}}),c.asyncIdleWaitTime=150,c.asyncS11nExceptions=1,c.fileBufferSize=1024*64,c.sabS11nOffset=c.fileBufferSize,c.sabS11nSize=h.$mxPathname*2,c.sabIO=new SharedArrayBuffer(c.fileBufferSize+c.sabS11nSize),c.opIds=Object.create(null);{let P=0;c.opIds.whichOp=P++,c.opIds.rc=P++,c.opIds.xAccess=P++,c.opIds.xClose=P++,c.opIds.xDelete=P++,c.opIds.xDeleteNoWait=P++,c.opIds.xFileSize=P++,c.opIds.xLock=P++,c.opIds.xOpen=P++,c.opIds.xRead=P++,c.opIds.xSleep=P++,c.opIds.xSync=P++,c.opIds.xTruncate=P++,c.opIds.xUnlock=P++,c.opIds.xWrite=P++,c.opIds.mkdir=P++,c.opIds["opfs-async-metrics"]=P++,c.opIds["opfs-async-shutdown"]=P++,c.opIds.retry=P++,c.sabOP=new SharedArrayBuffer(P*4)}c.sq3Codes=Object.create(null);for(const P of["SQLITE_ACCESS_EXISTS","SQLITE_ACCESS_READWRITE","SQLITE_BUSY","SQLITE_CANTOPEN","SQLITE_ERROR","SQLITE_IOERR","SQLITE_IOERR_ACCESS","SQLITE_IOERR_CLOSE","SQLITE_IOERR_DELETE","SQLITE_IOERR_FSYNC","SQLITE_IOERR_LOCK","SQLITE_IOERR_READ","SQLITE_IOERR_SHORT_READ","SQLITE_IOERR_TRUNCATE","SQLITE_IOERR_UNLOCK","SQLITE_IOERR_WRITE","SQLITE_LOCK_EXCLUSIVE","SQLITE_LOCK_NONE","SQLITE_LOCK_PENDING","SQLITE_LOCK_RESERVED","SQLITE_LOCK_SHARED","SQLITE_LOCKED","SQLITE_MISUSE","SQLITE_NOTFOUND","SQLITE_OPEN_CREATE","SQLITE_OPEN_DELETEONCLOSE","SQLITE_OPEN_MAIN_DB","SQLITE_OPEN_READONLY","SQLITE_LOCK_NONE","SQLITE_LOCK_SHARED","SQLITE_LOCK_RESERVED","SQLITE_LOCK_PENDING","SQLITE_LOCK_EXCLUSIVE"])c.sq3Codes[P]=H[P]??t("Maintenance required: not found:",P);c.opfsFlags=Object.assign(Object.create(null),{OPFS_UNLOCK_ASAP:1,OPFS_UNLINK_BEFORE_OPEN:2,defaultUnlockAsap:!1}),h.metrics.reset();const Q=h.metrics.counters,A=h.opRun=(P,...X)=>{const ee=c.opIds[P]||t(h.vfsName+": Invalid op ID:",P);c.s11n.serialize(...X),Atomics.store(c.sabOPView,c.opIds.rc,-1),Atomics.store(c.sabOPView,c.opIds.whichOp,ee),Atomics.notify(c.sabOPView,c.opIds.whichOp);const Z=performance.now();for(;Atomics.wait(c.sabOPView,c.opIds.rc,-1)!=="not-equal";);const te=Atomics.load(c.sabOPView,c.opIds.rc);if(Q[P].wait+=performance.now()-Z,te&&c.asyncS11nExceptions){const E=c.s11n.deserialize();E&&L(P+"() async error:",...E)}return te},N=Object.create(null);N.op=void 0,N.start=void 0;const J=h.mTimeStart=P=>{N.start=performance.now(),N.op=P,++Q[P].count},d=h.mTimeEnd=()=>Q[N.op].time+=performance.now()-N.start,y=h.__openFiles=Object.create(null);h.ioSyncWrappers=r.nu({xCheckReservedLock:function(P,X){return g.poke(X,0,"i32"),0},xClose:function(P){J("xClose");let X=0;const ee=y[P];return ee&&(delete y[P],X=A("xClose",P),ee.sq3File&&ee.sq3File.dispose()),d(),X},xDeviceCharacteristics:function(P){return H.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(P,X,ee){return H.SQLITE_NOTFOUND},xFileSize:function(P,X){J("xFileSize");let ee=A("xFileSize",P);if(ee==0)try{const Z=c.s11n.deserialize()[0];g.poke(X,Z,"i64")}catch(Z){L("Unexpected error reading xFileSize() result:",Z),ee=c.sq3Codes.SQLITE_IOERR}return d(),ee},xRead:function(P,X,ee,Z){J("xRead");const te=y[P];let E;try{E=A("xRead",P,ee,Number(Z)),(E===0||H.SQLITE_IOERR_SHORT_READ===E)&&g.heap8u().set(te.sabView.subarray(0,ee),Number(X))}catch(o){L("xRead(",arguments,") failed:",o,te),E=H.SQLITE_IOERR_READ}return d(),E},xSync:function(P,X){J("xSync");const ee=A("xSync",P,X);return d(),ee},xTruncate:function(P,X){J("xTruncate");const ee=A("xTruncate",P,Number(X));return d(),ee},xWrite:function(P,X,ee,Z){J("xWrite");const te=y[P];let E;try{te.sabView.set(g.heap8u().subarray(Number(X),Number(X)+ee)),E=A("xWrite",P,ee,Number(Z))}catch(o){L("xWrite(",arguments,") failed:",o,te),E=H.SQLITE_IOERR_WRITE}return d(),E}}),h.vfsSyncWrappers={xAccess:function(P,X,ee,Z){J("xAccess");const te=A("xAccess",g.cstrToJs(X));return g.poke(Z,te?0:1,"i32"),d(),0},xCurrentTime:function(P,X){return g.poke(X,24405875e-1+new Date().getTime()/864e5,"double"),0},xCurrentTimeInt64:function(P,X){return g.poke(X,24405875e-1*864e5+new Date().getTime(),"i64"),0},xDelete:function(P,X,ee){J("xDelete");const Z=A("xDelete",g.cstrToJs(X),ee,!1);return d(),Z},xFullPathname:function(P,X,ee,Z){return g.cstrncpy(Z,X,ee)te[typeof u]||t("Maintenance required: this value type cannot be serialized.",u),o=u=>{switch(u){case te.number.id:return te.number;case te.bigint.id:return te.bigint;case te.boolean.id:return te.boolean;case te.string.id:return te.string;default:t("Invalid type ID:",u)}};return c.s11n.deserialize=function(u=!1){performance.now();const p=ee[0],q=p?[]:null;if(p){const z=[];let V=1,R,m,C;for(R=0;R(te=!0,h.dispose(),Z(R)),o=()=>{try{X(i,h)}catch(R){return E(R)}return te=!1,ee(i)},u=s.options;u.proxyUri+(u.proxyUri.indexOf("?")<0?"?":"&")+I;const p=new URL("/assets/sqlite3-opfs-async-proxy-D_xnb1D8.js",self.location.href);p.searchParams.set("vfs",I);const q=h.worker=new Worker(p.toString());let z=setTimeout(()=>{te===void 0&&E(new Error("Timeout while waiting for OPFS async proxy worker."))},4e3);q._originalOnError=q.onerror,q.onerror=function(R){L("Error initializing OPFS asyncer:",R),E(new Error("Loading OPFS async Worker failed for unknown reasons."))},h.opRun;const V=function(){const R=g.scopedAllocPush(),m=new H.sqlite3_file;try{const C=m.pointer,B=H.SQLITE_OPEN_CREATE|H.SQLITE_OPEN_READWRITE|H.SQLITE_OPEN_MAIN_DB,Y=g.scopedAlloc(8),ne="/sanity/check/file"+randomFilename(8),ae=g.scopedAllocCString(ne);let ce;if(c.s11n.serialize("This is ä string."),ce=c.s11n.deserialize(),w("deserialize() says:",ce),ce[0]!=="This is ä string."&&t("String d13n error."),h.vfsSyncWrappers.xAccess(h.pointer,ae,0,Y),ce=g.peek(Y,"i32"),w("xAccess(",ne,") exists ?=",ce),ce=h.vfsSyncWrappers.xOpen(h.pointer,ae,C,B,Y),w("open rc =",ce,"state.sabOPView[xOpen] =",c.sabOPView[c.opIds.xOpen]),ce!==0){L("open failed with code",ce);return}h.vfsSyncWrappers.xAccess(h.pointer,ae,0,Y),ce=g.peek(Y,"i32"),ce||t("xAccess() failed to detect file."),ce=h.ioSyncWrappers.xSync(m.pointer,0),ce&&t("sync failed w/ rc",ce),ce=h.ioSyncWrappers.xTruncate(m.pointer,1024),ce&&t("truncate failed w/ rc",ce),g.poke(Y,0,"i64"),ce=h.ioSyncWrappers.xFileSize(m.pointer,Y),ce&&t("xFileSize failed w/ rc",ce),w("xFileSize says:",g.peek(Y,"i64")),ce=h.ioSyncWrappers.xWrite(m.pointer,ae,10,1),ce&&t("xWrite() failed!");const ke=g.scopedAlloc(16);ce=h.ioSyncWrappers.xRead(m.pointer,ke,6,2),g.poke(ke+6,0);let Ne=g.cstrToJs(ke);w("xRead() got:",Ne),Ne!=="sanity"&&t("Unexpected xRead() value."),h.vfsSyncWrappers.xSleep&&(w("xSleep()ing before close()ing..."),h.vfsSyncWrappers.xSleep(h.pointer,2e3),w("waking up from xSleep()")),ce=h.ioSyncWrappers.xClose(C),w("xClose rc =",ce,"sabOPView =",c.sabOPView),w("Deleting file:",ne),h.vfsSyncWrappers.xDelete(h.pointer,ae,4660),h.vfsSyncWrappers.xAccess(h.pointer,ae,0,Y),ce=g.peek(Y,"i32"),ce&&t("Expecting 0 from xAccess(",ne,") after xDelete()."),x("End of OPFS sanity checks.")}finally{m.dispose(),g.scopedAllocPop(R)}};q.onmessage=function({data:R}){switch(R.type){case"opfs-unavailable":E(new Error(R.payload.join(" ")));break;case"opfs-async-loaded":delete c.vfs,q.postMessage({type:"opfs-async-init",args:r.nu(c)});break;case"opfs-async-inited":if(te===!0)break;clearTimeout(z),z=null;try{i.vfs.installVfs({io:{struct:h.ioMethods,methods:h.ioSyncWrappers},vfs:{struct:h,methods:h.vfsSyncWrappers}}),c.sabOPView=new Int32Array(c.sabOP),c.sabFileBufView=new Uint8Array(c.sabIO,0,c.fileBufferSize),c.sabS11nView=new Uint8Array(c.sabIO,c.sabS11nOffset,c.sabS11nSize),h.initS11n(),delete h.initS11n,u.sanityChecks&&(x("Running sanity checks because of opfs-sanity-check URL arg..."),V()),s.thisThreadHasOPFS()?s.getRootDir().then(m=>{q.onerror=q._originalOnError,delete q._originalOnError,w("End of OPFS sqlite3_vfs setup.",h),o()}).catch(E):o()}catch(m){L(m),E(m)}break;case"debug":x("debug message from worker:",R);break;default:{const m="Unexpected message from the OPFS async worker: "+JSON.stringify(R);L(m),E(new Error(m));break}}}})},c}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(!i.opfs||i.config.disable?.vfs?.opfs)return;const t=i.util,r=i.opfs||i.util.toss("Missing sqlite3.opfs"),s=async function(_){if(_=r.initOptions("opfs",_),!_)return i;const c=i.capi,b=r.createVfsState().vfs,M=b.metrics.counters,I=b.mTimeStart,S=b.mTimeEnd,w=b.opRun,x=b.__openFiles;return b.bindVfs(t.nu({xLock:function(L,H){I("xLock"),++M.xLock.count;const g=x[L];let h=0;return g.lockType?g.lockType=H:(h=w("xLock",L,H),h===0&&(g.lockType=H)),S(),h},xUnlock:function(L,H){I("xUnlock"),++M.xUnlock.count;const g=x[L];let h=0;return c.SQLITE_LOCK_NONE===H&&g.lockType&&(h=w("xUnlock",L,H)),h===0&&(g.lockType=H),S(),h}}),function(L,H){if(L.oo1){const g=function(...h){const D=L.oo1.DB.dbCtorHelper.normalizeArgs(...h);D.vfs=H.$zName,L.oo1.DB.dbCtorHelper.call(this,D)};g.prototype=Object.create(L.oo1.DB.prototype),L.oo1.OpfsDb=g,g.importDb=r.importDb,L.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(b.pointer,function(h,D){D.capi.sqlite3_busy_timeout(h,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async _=>s().catch(c=>{_.config.warn("Ignoring inability to install 'opfs' sqlite3_vfs:",c)}))}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(i.config.disable?.vfs?.["opfs-sahpool"])return;const t=i.util.toss,r=i.util.toss3,s=Object.create(null),_=i.capi,c=i.util,b=i.wasm,M=4096,I=512,S=4,w=8,x=I+S,L=I,H=x,g=M,h=_.SQLITE_OPEN_MAIN_DB|_.SQLITE_OPEN_MAIN_JOURNAL|_.SQLITE_OPEN_SUPER_JOURNAL|_.SQLITE_OPEN_WAL,D=_.SQLITE_OPEN_MEMORY,Q=".opaque",A=()=>Math.random().toString(36).slice(2),N=new TextDecoder,J=new TextEncoder,d=Object.assign(Object.create(null),{name:"opfs-sahpool",directory:void 0,initialCapacity:6,clearOnInit:!1,verbosity:2,forceReinitIfPreviouslyFailed:!1}),y=[i.config.error,i.config.warn,i.config.log];i.config.log;const F=i.config.warn;i.config.error;const W=new Map,P=R=>W.get(R),X=(R,m)=>{m?W.set(R,m):W.delete(R)},ee=new Map,Z=R=>ee.get(R),te=(R,m)=>{m?ee.set(R,m):ee.delete(R)},E={xCheckReservedLock:function(R,m){const C=Z(R);return C.log("xCheckReservedLock"),C.storeErr(),b.poke32(m,1),0},xClose:function(R){const m=Z(R);m.storeErr();const C=m.getOFileForS3File(R);if(C)try{m.log(`xClose ${C.path}`),m.mapS3FileToOFile(R,!1),C.sah.flush(),C.flags&_.SQLITE_OPEN_DELETEONCLOSE&&m.deletePath(C.path)}catch(B){return m.storeErr(B,_.SQLITE_IOERR)}return 0},xDeviceCharacteristics:function(R){return _.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(R,m,C){return _.SQLITE_NOTFOUND},xFileSize:function(R,m){const C=Z(R);C.log("xFileSize");const B=C.getOFileForS3File(R).sah.getSize()-g;return b.poke64(m,BigInt(B)),0},xLock:function(R,m){const C=Z(R);C.log(`xLock ${m}`),C.storeErr();const B=C.getOFileForS3File(R);return B.lockType=m,0},xRead:function(R,m,C,B){const Y=Z(R);Y.storeErr();const ne=Y.getOFileForS3File(R);Y.log(`xRead ${ne.path} ${C} @ ${B}`);try{const ae=ne.sah.read(b.heap8u().subarray(Number(m),Number(m)+C),{at:g+Number(B)});return aem&&b.poke8(b.ptr.add(C,m,-1),0)}catch{return _.SQLITE_NOMEM}finally{b.scopedAllocPop(ne)}}return Y?Y.sqlite3Rc||_.SQLITE_IOERR:0},xOpen:function(m,C,B,Y,ne){const ae=P(m);try{Y&=~D,ae.log(`xOpen ${b.cstrToJs(C)} ${Y}`);const ce=C&&b.peek8(C)?ae.getPath(C):A();let ke=ae.getSAHForPath(ce);!ke&&Y&_.SQLITE_OPEN_CREATE&&(ae.getFileCount()X(m.pointer,0)),B&&(m.$xRandomness=B.$xRandomness,m.$xSleep=B.$xSleep,B.dispose()),!m.$xRandomness&&!u.xRandomness&&(u.xRandomness=function(Y,ne,ae){const ce=b.heap8u();let ke=0;const Ne=Number(ae);for(;ke0),i.vfs.installVfs({vfs:{struct:m,methods:u}}),m};class q{vfsDir;#e;#i;#s;#t=new Map;#n=new Map;#o=new Set;#a=new Map;#r=new Uint8Array(x);#c;#l;#_;constructor(m=Object.create(null)){this.#_=m.verbosity??d.verbosity,this.vfsName=m.name||d.name,this.#l=p(this.vfsName),X(this.#l.pointer,this),this.vfsDir=m.directory||"."+this.vfsName,this.#c=new DataView(this.#r.buffer,this.#r.byteOffset),this.isReady=this.reset(!!(m.clearOnInit??d.clearOnInit)).then(()=>{if(this.$error)throw this.$error;return this.getCapacity()?Promise.resolve(void 0):this.addCapacity(m.initialCapacity||d.initialCapacity)})}#u(m,...C){this.#_>m&&y[m](this.vfsName+":",...C)}log(...m){this.#u(2,...m)}warn(...m){this.#u(1,...m)}error(...m){this.#u(0,...m)}getVfs(){return this.#l}getCapacity(){return this.#t.size}getFileCount(){return this.#n.size}getFileNames(){const m=[];for(const C of this.#n.keys())m.push(C);return m}async addCapacity(m){for(let C=0;C{try{const ne=await Y.createSyncAccessHandle();if(this.#t.set(ne,B),m)ne.truncate(g),this.setAssociatedPath(ne,"",0);else{const ae=this.getAssociatedPath(ne);ae?this.#n.set(ae,ne):this.#o.add(ne)}}catch(ne){throw this.storeErr(ne),this.releaseAccessHandles(),ne}}))}getAssociatedPath(m){m.read(this.#r,{at:0});const C=this.#c.getUint32(L);if(this.#r[0]&&(C&_.SQLITE_OPEN_DELETEONCLOSE||(C&h)===0))return F(`Removing file with unexpected flags ${C.toString(16)}`,this.#r),this.setAssociatedPath(m,"",0),"";const B=new Uint32Array(w/4);m.read(B,{at:H});const Y=this.computeDigest(this.#r,C);if(B.every((ne,ae)=>ne===Y[ae])){const ne=this.#r.findIndex(ae=>ae===0);return ne===0&&m.truncate(g),ne?N.decode(this.#r.subarray(0,ne)):""}else return F("Disassociating file with bad digest."),this.setAssociatedPath(m,"",0),""}setAssociatedPath(m,C,B){const Y=J.encodeInto(C,this.#r);I<=Y.written+1&&t("Path too long:",C),C&&B&&(B|=D),this.#r.fill(0,Y.written,I),this.#c.setUint32(L,B);const ne=this.computeDigest(this.#r,B);m.write(this.#r,{at:0}),m.write(ne,{at:H}),m.flush(),C?(this.#n.set(C,m),this.#o.delete(m)):(m.truncate(g),this.#o.add(m))}computeDigest(m,C){if(C&D){let B=3735928559,Y=1103547991;for(const ne of m)B=Math.imul(B^ne,2654435761),Y=Math.imul(Y^ne,104729);return new Uint32Array([B>>>0,Y>>>0])}else return new Uint32Array([0,0])}async reset(m){await this.isReady;let C=await navigator.storage.getDirectory(),B;for(const Y of this.vfsDir.split("/"))Y&&(B=C,C=await C.getDirectoryHandle(Y,{create:!0}));return this.#e=C,this.#s=B,this.#i=await this.#e.getDirectoryHandle(Q,{create:!0}),this.releaseAccessHandles(),this.acquireAccessHandles(m)}getPath(m){return b.isPtr(m)&&(m=b.cstrToJs(m)),(m instanceof URL?m:new URL(m,"file://localhost/")).pathname}deletePath(m){const C=this.#n.get(m);return C&&(this.#n.delete(m),this.setAssociatedPath(C,"",0)),!!C}storeErr(m,C){return m&&(m.sqlite3Rc=C||_.SQLITE_IOERR,this.error(m)),this.$error=m,C}popErr(){const m=this.$error;return this.$error=void 0,m}nextAvailableSAH(){const[m]=this.#o.keys();return m}getOFileForS3File(m){return this.#a.get(m)}mapS3FileToOFile(m,C){C?(this.#a.set(m,C),te(m,this)):(this.#a.delete(m),te(m,!1))}hasFilename(m){return this.#n.has(m)}getSAHForPath(m){return this.#n.get(m)}async removeVfs(){if(!this.#l.pointer||!this.#i)return!1;_.sqlite3_vfs_unregister(this.#l.pointer),this.#l.dispose(),delete s[this.vfsName];try{this.releaseAccessHandles(),await this.#e.removeEntry(Q,{recursive:!0}),this.#i=void 0,await this.#s.removeEntry(this.#e.name,{recursive:!0}),this.#e=this.#s=void 0}catch(m){i.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",m)}return!0}pauseVfs(){return this.#a.size>0&&i.SQLite3Error.toss(_.SQLITE_MISUSE,"Cannot pause VFS",this.vfsName,"because it has opened files."),this.#t.size>0&&(_.sqlite3_vfs_unregister(this.vfsName),this.releaseAccessHandles()),this}isPaused(){return this.#t.size===0}async unpauseVfs(){return this.#t.size===0?this.acquireAccessHandles(!1).then(()=>_.sqlite3_vfs_register(this.#l,0),this):this}exportFile(m){const C=this.#n.get(m)||t("File not found:",m),B=C.getSize()-g,Y=new Uint8Array(B>0?B:0);if(B>0){const ne=C.read(Y,{at:g});ne!=B&&t("Expected to read "+B+" bytes but read "+ne+".")}return Y}async importDbChunked(m,C){const B=this.#n.get(m)||this.nextAvailableSAH()||t("No available handles to import to.");B.truncate(0);let Y=0,ne,ae=!1;try{for(;(ne=await C())!==void 0;)ne instanceof ArrayBuffer&&(ne=new Uint8Array(ne)),!ae&&Y===0&&ne.byteLength>=15&&(c.affirmDbHeader(ne),ae=!0),B.write(ne,{at:g+Y}),Y+=ne.byteLength;if((Y<512||Y%512!==0)&&t("Input size",Y,"is not correct for an SQLite database."),!ae){const ce=new Uint8Array(20);B.read(ce,{at:0}),c.affirmDbHeader(ce)}B.write(new Uint8Array([1,1]),{at:g+18})}catch(ce){throw this.setAssociatedPath(B,"",0),ce}return this.setAssociatedPath(B,m,_.SQLITE_OPEN_MAIN_DB),Y}importDb(m,C){if(C instanceof ArrayBuffer)C=new Uint8Array(C);else if(C instanceof Function)return this.importDbChunked(m,C);const B=this.#n.get(m)||this.nextAvailableSAH()||t("No available handles to import to."),Y=C.byteLength;(Y<512||Y%512!=0)&&t("Byte array size is invalid for an SQLite db.");const ne="SQLite format 3";for(let ce=0;ce<15;++ce)ne.charCodeAt(ce)!==C[ce]&&t("Input does not contain an SQLite database header.");const ae=B.write(C,{at:g});return ae!=Y?(this.setAssociatedPath(B,"",0),t("Expected to write "+Y+" bytes but wrote "+ae+".")):(B.write(new Uint8Array([1,1]),{at:g+18}),this.setAssociatedPath(B,m,_.SQLITE_OPEN_MAIN_DB)),ae}}class z{#e;constructor(m){this.#e=m,this.vfsName=m.vfsName}async addCapacity(m){return this.#e.addCapacity(m)}async reduceCapacity(m){return this.#e.reduceCapacity(m)}getCapacity(){return this.#e.getCapacity(this.#e)}getFileCount(){return this.#e.getFileCount()}getFileNames(){return this.#e.getFileNames()}async reserveMinimumCapacity(m){const C=this.#e.getCapacity();return Cthis)}isPaused(){return this.#e.isPaused()}}const V=async()=>{const R=await navigator.storage.getDirectory(),m=".opfs-sahpool-sync-check-"+A(),C=(await(await R.getFileHandle(m,{create:!0})).createSyncAccessHandle()).close();return await C,await R.removeEntry(m),C?.then&&t("The local OPFS API is too old for opfs-sahpool:","it has an async FileSystemSyncAccessHandle.close() method."),!0};i.installOpfsSAHPoolVfs=async function(R=Object.create(null)){R=Object.assign(Object.create(null),d,R||{});const m=R.name;if(R.$testThrowPhase1)throw R.$testThrowPhase1;if(s[m])try{return await s[m]}catch(C){if(R.forceReinitIfPreviouslyFailed)delete s[m];else throw C}return!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory?s[m]=Promise.reject(new Error("Missing required OPFS APIs.")):s[m]=V().then(async function(){if(R.$testThrowPhase2)throw R.$testThrowPhase2;const C=new q(R);return C.isReady.then(async()=>{const B=new z(C);if(i.oo1){const Y=i.oo1,ne=C.getVfs(),ae=function(...ce){const ke=Y.DB.dbCtorHelper.normalizeArgs(...ce);ke.vfs=ne.$zName,Y.DB.dbCtorHelper.call(this,ke)};ae.prototype=Object.create(Y.DB.prototype),B.OpfsSAHPoolDb=ae}return C.log("VFS initialized."),B}).catch(async B=>{throw await C.removeVfs().catch(()=>{}),B})}).catch(C=>s[m]=Promise.reject(C))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(!i.opfs||i.config.disable?.vfs?.["opfs-wl"])return;const t=i.util;i.util.toss;const r=i.opfs,s="opfs-wl",_=async function(c){if(c=r.initOptions(s,c),!c)return i;i.capi;const b=r.createVfsState().vfs;b.metrics.counters;const M=b.mTimeStart,I=b.mTimeEnd,S=b.opRun,w=b.__openFiles;return b.bindVfs(t.nu({xLock:function(x,L){M("xLock");const H=w[x],g=S("xLock",x,L);return g||(H.lockType=L),I(),g},xUnlock:function(x,L){M("xUnlock");const H=w[x],g=S("xUnlock",x,L);return g||(H.lockType=L),I(),g}}),function(x,L){if(x.oo1){const H=function(...g){const h=x.oo1.DB.dbCtorHelper.normalizeArgs(...g);h.vfs=L.$zName,x.oo1.DB.dbCtorHelper.call(this,h)};H.prototype=Object.create(x.oo1.DB.prototype),x.oo1.OpfsWlDb=H,H.importDb=r.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async c=>_().catch(b=>{c.config.warn("Ignoring inability to install the",s,"sqlite3_vfs:",b)}))});try{const i=Object.assign(Object.create(null),{memory:typeof nt<"u"?nt:n.wasmMemory,exports:typeof dt<"u"?dt:Object.prototype.hasOwnProperty.call(n,"wasmExports")?n.wasmExports:n.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});e.debugModule("Bootstrapping lib config",i);const t=globalThis.sqlite3ApiBootstrap(i);return delete globalThis.sqlite3ApiBootstrap,t}catch(i){throw console.error("sqlite3ApiBootstrap() error:",i),i}},et?ie=f:ie=new Promise((e,n)=>{Ce=e,je=n}),ie}At=(function(){const qe=At;if(!qe)throw new Error("Expecting sqlite3InitModule to be defined by the Emscripten build.");const ie=globalThis.sqlite3InitModuleState=Object.assign(Object.create(null),{moduleScript:globalThis?.document?.currentScript,isWorker:typeof WorkerGlobalScope<"u",location:globalThis.location,urlParams:globalThis?.location?.href?new URL(globalThis.location.href).searchParams:new URLSearchParams,wasmFilename:"sqlite3.wasm"});if(ie.debugModule=ie.urlParams.has("sqlite3.debugModule")?(...he)=>console.warn("sqlite3.debugModule:",...he):()=>{},ie.urlParams.has("sqlite3.dir"))ie.sqlite3Dir=ie.urlParams.get("sqlite3.dir")+"/";else if(ie.moduleScript){const he=ie.moduleScript.src.split("/");he.pop(),ie.sqlite3Dir=he.join("/")+"/"}const f=globalThis.sqlite3InitModule=function he(...ye){return ie.emscriptenLocateFile=ye[0]?.locateFile,ie.emscriptenInstantiateWasm=ye[0]?.instantiateWasm,qe(...ye).then(ge=>{ie.debugModule("sqlite3InitModule() sIMS =",ie),ie.debugModule("sqlite3InitModule() EmscriptenModule =",ge);const Se=ge.runSQLite3PostLoadInit(ie,ge,!!he.__isUnderTest);return ie.debugModule("sqlite3InitModule() sqlite3 =",Se),Se}).catch(ge=>{throw console.error("Exception loading sqlite3 module:",ge),ge})};if(f.ready=qe.ready,ie.moduleScript){let he=ie.moduleScript.src.split("/");he.pop(),ie.scriptDir=he.join("/")+"/"}return ie.debugModule("extern-post-js.c-pp.js sqlite3InitModuleState =",ie),f})();var nn=At;const rn=/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/,sn=1024;function ut(qe){if(typeof qe!="string"||!rn.test(qe)||qe.length-Number(qe.startsWith("-"))-Number(qe.includes("."))>sn)throw new TypeError('Decimal requires a finite base-10 string (for example "3.50")');return qe}function It(qe){const ie=ut(qe),f=ie.startsWith("-"),[he,ye=""]=(f?ie.slice(1):ie).split("."),ge=he.replace(/^0+(?=[0-9])/,""),Se=ye.replace(/0+$/,"");return{negative:f&&(ge!=="0"||Se!==""),integer:ge,fraction:Se}}function Lt(qe,ie){const f=It(qe),he=It(ie);if(f.negative!==he.negative)return f.negative?-1:1;const ye=f.negative?-1:1;if(f.integer.length!==he.integer.length)return Math.sign(f.integer.length-he.integer.length)*ye;if(f.integer!==he.integer)return(f.integerye.replace(/[0-9]/g,ge=>String(9-Number(ge)));return`0${he(f)}${he(ie.integer)}:${he(ie.fraction)}~`}function ln(qe,ie){ut(qe),ut(ie);const f=qe.split(".")[1]?.length??0,he=ie.split(".")[1]?.length??0,ye=Math.max(f,he),ge=(De,We)=>BigInt(De.replace(".",""))*10n**BigInt(ye-We),Se=ge(qe,f)+ge(ie,he);if(ye===0)return ut(Se.toString());const Be=Se<0n?"-":"",Qe=(Se<0n?-Se:Se).toString().padStart(ye+1,"0");return ut(`${Be}${Qe.slice(0,-ye)}.${Qe.slice(-ye)}`)}function an(qe,ie){const f=ye=>{if(typeof ye!="string")throw new TypeError("Inexact SQLite Decimal value");return ut(ye)};qe.createFunction({name:"teaql_decimal_cmp",arity:2,deterministic:!0,xFunc:(ye,ge,Se)=>ge===null||Se===null?null:Lt(f(ge),f(Se))}),qe.createFunction({name:"teaql_decimal_order_key",arity:1,deterministic:!0,xFunc:(ye,ge)=>ge===null?null:on(f(ge))});const he=[];for(const ye of["sum","min","max"]){const ge=new Map;he.push(ge),qe.createFunction({name:`teaql_decimal_${ye}`,arity:1,deterministic:!0,xStep(Se,Be){if(Be===null)return;const Qe=f(Be),De=ie.sqlite3_js_aggregate_context(Se,1);if(!De)throw new Error("SQLite aggregate context allocation failed");const We=ge.get(De);ge.set(De,We===void 0?Qe:ye==="sum"?ln(We,Qe):Lt(Qe,We)===(ye==="min"?-1:1)?Qe:We)},xFinal(Se){const Be=ie.sqlite3_js_aggregate_context(Se,0),Qe=ge.get(Be)??null;return ge.delete(Be),Qe}})}return()=>{for(const ye of he)ye.clear()}}function cn(qe={}){const ie=qe.scope??globalThis;let f,he,ye,ge,Se=Promise.resolve();const Be=()=>(f||(f=nn(qe.wasmUrl?{locateFile:Ee=>Ee.endsWith(".wasm")?qe.wasmUrl:Ee}:void 0)),f),Qe=async(Ie={})=>{De();const Ee=Ie.storage??"memory",Ce=Ie.databaseName??"teaql-browser.sqlite3",je=await Be();if(Ee==="opfs"){if(!je.oo1.OpfsDb){const et=new Error("OPFS SQLite is unavailable. Serve COOP/COEP headers and use a compatible browser.");throw et.name="BrowserSQLiteStorageUnavailableError",et}he=new je.oo1.OpfsDb(`/${Ce}`,"c")}else he=new je.oo1.DB(":memory:","c");ge={storage:Ee,databaseName:Ce};try{ye=an(he,je.capi)}catch(et){throw De(),et}he.exec("PRAGMA foreign_keys = ON")},De=()=>{try{he?.close()}finally{he=void 0,ye?.(),ye=void 0}},We=()=>{if(!he)throw new Error("Browser SQLite database is not open");return he},de=(Ie,Ee=[])=>{if(typeof Ie!="string"||!Ie.trim())throw new TypeError("SQL is required");if(!Array.isArray(Ee))throw new TypeError("SQL bind values must be an array");const Ce=We();let je;try{je=Ce.exec({sql:Ie,bind:Ee,rowMode:"object",returnValue:"resultRows"})}finally{ye?.()}const et=/^\s*(?:insert|update|delete|replace)\b/i.test(Ie);return{rows:je,rowCount:je.length||(et?Number(Ce.changes()):0)}},Le=async()=>{const Ie=We();Ie.exec("PRAGMA foreign_keys = OFF");const Ee=Ie.exec({sql:"SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",rowMode:"object",returnValue:"resultRows"});for(const Ce of Ee){const je=String(Ce.name).replace(/"/g,'""');Ie.exec(`DROP TABLE IF EXISTS "${je}"`)}if(Ie.exec("PRAGMA foreign_keys = ON"),!ge)throw new Error("Browser SQLite database is not open")};ie.addEventListener("message",Ie=>{const Ee=Ie.data;!Ee||Ee.type!=="teaql-browser-sqlite-request"||(Se=Se.then(async()=>{try{let Ce;if(Ee.operation==="open")Ce=await Qe(Ee.payload);else if(Ee.operation==="query")Ce=de(String(Ee.payload?.sql??""),Ee.payload?.values??[]);else if(Ee.operation==="reset")Ce=await Le();else if(Ee.operation==="close")De();else throw new Error(`Unsupported Browser SQLite operation: ${String(Ee.operation)}`);ie.postMessage({type:"teaql-browser-sqlite-response",requestId:Ee.requestId,result:Ce})}catch(Ce){const je=Ce instanceof Error?Ce:new Error(String(Ce));ie.postMessage({type:"teaql-browser-sqlite-response",requestId:Ee.requestId,error:{name:je.name,message:je.message,code:je.code}})}}))})}var un="/assets/sqlite3-BVKGSWc-.wasm";cn({wasmUrl:un})})(); diff --git a/assets/style-F0ZYuCV2.css b/assets/style-F0ZYuCV2.css new file mode 100644 index 0000000000000000000000000000000000000000..338634f51515693ae49cabf7aaf6a5a7b769bc01 --- /dev/null +++ b/assets/style-F0ZYuCV2.css @@ -0,0 +1 @@ +:root{font:16px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#17231b;background:#f5f4ed;font-synthesis:none;--ink: #17231b;--muted: #677067;--paper: #fffef8;--line: #d8ddd3;--green: #145b37;--green-deep: #0e4329;--lime: #dff45c;--orange: #ef8354;--blue: #2b66d9}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:#f5f4ed}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}.page-shell{width:min(1440px,100%);margin:0 auto;padding:0 42px}.site-header{height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand,.docs-link{color:var(--ink);text-decoration:none;font-weight:750}.brand{display:inline-flex;align-items:center;gap:11px;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;color:var(--lime);background:var(--green-deep);font-family:Georgia,serif;font-style:italic}.docs-link{color:var(--green);font-size:14px}.header-actions{display:flex;align-items:center;gap:18px}.language-switch{display:flex;gap:3px;padding:3px;border:1px solid var(--line);border-radius:8px}.language-switch button{padding:3px 7px;border:0;border-radius:5px;color:var(--muted);background:transparent;font-size:11px;cursor:pointer}.language-switch button.active{color:#fff;background:var(--green)}.hero{min-height:460px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(440px,.9fr);align-items:center;gap:72px;padding:76px 0 66px}.eyebrow,.section-index,.query-card-label{margin:0 0 14px;color:var(--green);font-size:11px;font-weight:850;letter-spacing:.18em}h1{margin:0;max-width:820px;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(42px,5.6vw,78px);font-weight:500;line-height:1.08;letter-spacing:-.055em}.hero-intro{max-width:680px;margin:26px 0 0;color:var(--muted);font-size:18px}.model-map{position:relative;min-height:310px;padding:38px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;border:1px solid #bfc8bb;border-radius:28px;background:linear-gradient(145deg,#fdfdf8,#e9eee5);box-shadow:0 18px 48px #213c280f;overflow:hidden}.model-map:before{content:"DOMAIN MODEL";position:absolute;top:18px;left:22px;color:#708073;font-size:10px;font-weight:800;letter-spacing:.16em}.model-flow{width:100%;display:grid;grid-template-columns:1fr auto 1fr auto 1fr;align-items:center;gap:10px}.model-flow>span:not(.model-arrow),.model-leaves span{min-width:0;padding:15px 17px;border:1px solid #b8c2b7;border-radius:12px;background:#fffffadb;font:750 14px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 22px #1e3a260d}.model-map small{display:block;margin-top:7px;color:var(--muted);font:12px/1.2 Inter,sans-serif}.model-flow>span.model-root{color:#fff;border-color:var(--green);background:var(--green)}.model-map .model-root small{color:#cce4d4}.model-arrow{color:#809087;font-size:22px;text-align:center}.model-arrow-split{height:22px;line-height:18px}.model-leaves{width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.runtime-language-panel{margin-bottom:28px;padding:24px;display:grid;grid-template-columns:minmax(240px,.72fr) minmax(0,1.8fr);align-items:center;gap:30px;border:1px solid var(--line);border-radius:18px;background:var(--paper)}.runtime-language-copy .section-index{margin-bottom:8px}.runtime-language-copy h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(22px,2.4vw,31px);font-weight:500;line-height:1.15;letter-spacing:-.035em}.runtime-language-copy p:last-child{margin:11px 0 0;color:var(--muted);font-size:13px}.runtime-language-selector{display:grid;grid-template-columns:repeat(7,minmax(82px,1fr));gap:8px}.runtime-language{min-width:0;padding:13px 8px 11px;display:flex;align-items:center;flex-direction:column;gap:4px;border:1px solid #d7ddd5;border-radius:12px;color:var(--ink);background:#fafbf7;text-align:center;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.runtime-language:hover{border-color:#98aa9d;background:#fff;transform:translateY(-2px)}.runtime-language.active{color:#fff;border-color:var(--green);background:var(--green);box-shadow:0 8px 20px #145b3724}.runtime-language-icon{font-size:25px;line-height:1.1}.runtime-language strong{overflow:hidden;max-width:100%;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.runtime-language small{color:#78837a;font-size:8px;line-height:1.25}.runtime-language.active small{color:#d5e7da}.development-process{margin:54px 0 28px;padding:42px;border:1px solid var(--line);border-radius:24px;background:var(--paper);box-shadow:0 18px 48px #213c280d}.development-process-heading{display:grid;grid-template-columns:minmax(280px,.9fr) minmax(0,1.1fr);align-items:end;gap:48px}.development-process-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,3.5vw,48px);font-weight:500;line-height:1.08;letter-spacing:-.04em}.development-process-intro>p{margin:0;color:var(--muted);font-size:16px;line-height:1.7}.development-process-links{margin-top:22px;display:flex;flex-wrap:wrap;gap:10px}.source-link{min-width:210px;padding:12px 15px;display:grid;gap:3px;border:1px solid #cad3c9;border-radius:10px;color:var(--ink);background:#f8faf5;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.source-link:hover,.source-link:focus-visible{border-color:#819586;background:#fff;outline:none;transform:translateY(-1px)}.source-link-primary{color:#fff;border-color:var(--green);background:var(--green)}.source-link-primary:hover,.source-link-primary:focus-visible{border-color:var(--green-deep);background:var(--green-deep)}.source-link span{color:#77847a;font-size:10px;font-weight:850;letter-spacing:.13em}.source-link-primary span{color:#c8dccd}.source-link strong{font-size:14px;line-height:1.35}.development-process-flow{margin:38px 0 0;padding:0;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));border:1px solid #d7ddd3;border-radius:16px;background:#f8faf5;list-style:none;overflow:hidden}.development-process-flow li{min-width:0;padding:22px;border-left:1px solid #d7ddd3}.development-process-flow li:first-child{border-left:0}.development-step{display:block;margin-bottom:20px;color:var(--orange);font:800 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace}.development-process-flow strong{display:block;min-height:48px;font-size:16px;line-height:1.45}.development-process-flow p{min-height:92px;margin:10px 0 18px;color:var(--muted);font-size:14px;line-height:1.6}.development-process-flow code{color:var(--green);font:650 12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.context-efficiency{margin-top:18px;padding:24px;display:grid;grid-template-columns:minmax(230px,.72fr) minmax(0,1.28fr);align-items:center;gap:34px;border-radius:14px;color:#edf7ef;background:var(--green-deep)}.context-efficiency .section-index{margin-bottom:8px;color:var(--lime)}.context-efficiency h3{margin:0;font:500 24px/1.2 Georgia,"Noto Serif SC",serif;letter-spacing:-.025em}.context-efficiency>p{margin:0;color:#c7d8cc;font-size:15px;line-height:1.7}.runtime-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}.observability-proof{padding:88px 0 52px}.observability-proof-heading{margin-bottom:26px;display:grid;grid-template-columns:minmax(260px,.72fr) minmax(0,1.28fr);align-items:end;gap:34px}.observability-proof-heading h2{margin:8px 0 0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,4vw,48px);font-weight:500;line-height:1.05;letter-spacing:-.04em}.observability-proof-heading>p{margin:0;color:var(--muted);font-size:15px;line-height:1.7}.observability-proof-figure{margin:0}.observability-proof-figure img{width:100%;height:auto;display:block;border:1px solid #d7ddd5;border-radius:18px;background:#f4f5fb;box-shadow:0 22px 54px #1c2d221a}.observability-proof-figure figcaption{margin-top:12px;color:var(--muted);font-size:11px}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.runtime-language-panel{grid-template-columns:1fr}.runtime-language-selector{grid-template-columns:repeat(4,minmax(100px,1fr))}.development-process-heading{grid-template-columns:1fr;align-items:start;gap:24px}.development-process-flow{grid-template-columns:repeat(2,minmax(0,1fr))}.development-process-flow li:nth-child(3){border-left:0;border-top:1px solid #d7ddd3}.development-process-flow li:nth-child(4){border-top:1px solid #d7ddd3}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}.observability-proof-heading{grid-template-columns:1fr;align-items:start;gap:14px}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-language-panel{padding:20px 16px;gap:20px}.runtime-language-selector{grid-template-columns:repeat(2,minmax(0,1fr))}.runtime-language:last-child{grid-column:1 / -1}.development-process{margin-top:38px;padding:26px 18px}.development-process-intro>p{font-size:15px}.development-process-links{align-items:stretch;flex-direction:column}.source-link{min-width:0;width:100%}.development-process-flow{grid-template-columns:1fr}.development-process-flow li{border-top:1px solid #d7ddd3;border-left:0}.development-process-flow li:first-child{border-top:0}.development-process-flow li:nth-child(3),.development-process-flow li:nth-child(4){border-left:0}.development-process-flow strong,.development-process-flow p{min-height:0}.context-efficiency{grid-template-columns:1fr;gap:16px;padding:20px}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}.observability-proof{padding:64px 0 34px}.observability-proof-figure img{border-radius:12px}} diff --git a/assets/workItems-DS6iz1SR.js b/assets/workItems-DS6iz1SR.js new file mode 100644 index 0000000000000000000000000000000000000000..eba613bc491f9fbe01bb45356541a36a8a0c04ac --- /dev/null +++ b/assets/workItems-DS6iz1SR.js @@ -0,0 +1 @@ +import{S as it,f as j,E as k,g as Q,L as l,M as I,n as U,C as w,d as f,a as b,j as z,e as O,Q as J,U as K,R as rt,B as st,D as nt,c as ot}from"./dynamic-search-BwvXmN4R.js";import{EntityCreationError as H,EntityCreation as v}from"./entity-creation-Bqaw1C4U.js";class N extends it{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",n=!0,s){return super.relationQuery(t,e,i,r,n,s)}}const R=Symbol("managed entity construction");class m{static teaqlTemporaryId=0;static teaqlMutationFields=new j("WorkItem",["id","title","description","platform","version"],{id:"immutable_field",version:"immutable_field"});id;title;description;platform;version;constructor(t,e,i=!1){if(e!==R)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];Object.assign(this,n),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof p?t.platform:p.fromRecord(t.platform),this.markLoaded("platform"))}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=v.hydrated(new m(t,R));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){return Object.fromEntries(Object.entries(this))}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return m.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"WorkItem",e,i=>new m({id:i},R,!0))}static teaqlCreate(t){return v.create(t,"WorkItem",e=>new m({id:e},R,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());return v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),i}teaqlValidateLoadedIdentities(t=new Set){t.has(this)||(t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version))}teaqlDiscardRestoredGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)))}teaqlNormalizeGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()}})))}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),m.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}return i}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y),y.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"WorkItem",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();return d.scopeFor(c),e.afterGraphRollback(()=>{for(const P of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,P)||delete this[P];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c),d.scopeFor(c),e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}const T=Symbol("managed entity construction");class p{static teaqlTemporaryId=0;static teaqlMutationFields=new j("Platform",["id","name","version"],{id:"immutable_field",version:"immutable_field"});id;name;version;constructor(t,e,i=!1){if(e!==T)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--p.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:i?new b:b.empty(),writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];if(delete n.workItemList,Object.assign(this,n),Array.isArray(t.workItemList)){const s=t.workItemList;this._workItemList=new b(s.map(o=>o instanceof m?o:m.fromRecord(o)),{totalCount:s.totalCount,aggregations:s.aggregations,summary:s.summary,facets:s.facets,isLoaded:s.isLoaded??!0}),this.markLoaded("workItemList")}}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const i of this._workItemList)i.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const i=v.hydrated(new p(t,T));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("workItemList")&&(t.workItemList=this._workItemList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return p.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"Platform",e,i=>new p({id:i},T,!0))}static teaqlCreate(t){return v.create(t,"Platform",e=>new p({id:e},T,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i);for(const r of this._workItemList)i=r.teaqlValidateMutationOrigins(t)||i;return i}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,i]of this._workItemList.entries())try{i.teaqlValidateLoadedIdentities(t)}catch(r){if(!(r instanceof w))throw r;const n=f.property("work_item_list").index(e);throw new w(r.violations.map(s=>({...s,location:s.location.prefixedBy(n)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));for(const i of this._workItemList)i.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},work_item_list:t.sourceMembers(this._workItemList)}));for(const i of this._workItemList){i.teaqlAttachRoot(this._root);const r=i.platform;(i._action!=="Update"||i._root.hasPending(i.teaqlEntityKey()))&&(this.id===void 0||!i.isLoaded("platform")||(typeof r=="object"&&r!==null?r.id:r)!==this.id)&&i.updatePlatform(this),i.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),p.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}let r=i;for(const[n,s]of this._workItemList.entries())try{r=s.teaqlAdmitGraph(t)||r}catch(o){if(!(o instanceof w))throw o;const y=f.property("work_item_list").index(n);throw new w(o.violations.map(d=>({...d,location:d.location.prefixedBy(y)})))}return r}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(u)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y);const d=y.scopeFor(this.teaqlEntityKey());for(const[u,a]of this._workItemList.entries()){a.teaqlAttachRoot(this._root);const q=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof q=="object"&&q!==null?q.id:q)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,i,d,n)}catch(c){if(!(c instanceof w))throw c;const $=f.property("work_item_list").index(u);throw new w(t.translateCheckResults(c.violations.map(P=>({...P,location:P.location.prefixedBy($)}))))}}}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"Platform",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const L=d.scopeFor(this.teaqlEntityKey());for(const[_,g]of this._workItemList.entries()){g.teaqlAttachRoot(this._root);const E=g.platform;(g._action!=="Update"||g._root.hasPending(g.teaqlEntityKey()))&&(this.id===void 0||!g.isLoaded("platform")||(typeof E=="object"&&E!==null?E.id:E)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,i,L,n)}catch(C){if(!(C instanceof w))throw C;const F=f.property("work_item_list").index(_);throw new w(t.translateCheckResults(C.violations.map(V=>({...V,location:V.location.prefixedBy(F)}))))}}return this}const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();d.scopeFor(c),e.afterGraphRollback(()=>{for(const L of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,L)||delete this[L];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c);const P=d.scopeFor(c);for(const[L,_]of this._workItemList.entries()){_.teaqlAttachRoot(this._root);const g=_.platform;(_._action!=="Update"||_._root.hasPending(_.teaqlEntityKey()))&&(this.id===void 0||!_.isLoaded("platform")||(typeof g=="object"&&g!==null?g.id:g)!==this.id)&&_.updatePlatform(this);try{await _.teaqlSaveWithinGraph(t,e,i,P,n)}catch(E){if(!(E instanceof w))throw E;const C=f.property("work_item_list").index(L);throw new w(t.translateCheckResults(E.violations.map(F=>({...F,location:F.location.prefixedBy(C)}))))}}return e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const Y=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class D{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Platform"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=z(i,t,Y,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new at(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({entityName:"WorkItem",toQuery:()=>new N("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({entityName:"WorkItem",toQuery:()=>new N("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new N("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{entityName:"WorkItem",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,n=r?[]:i.map(o=>o instanceof p?o:p.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof p?a:p.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof p?o:p.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class at{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return p.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class G{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"WorkItem"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=z(i,t,Y,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new ht(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title",t),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,n=r?[]:i.map(o=>o instanceof m?o:m.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof m?a:m.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof m?o:m.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class ht{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return m.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class A{static platforms(){return new D(!1)}static platformsWithMinimalFields(){return new D(!0)}static workItems(){return new G(!1)}static workItemsWithMinimalFields(){return new G(!0)}}const lt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function ut(h){let t=(await A.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];t||(t=p.teaqlBootstrapNew(h,"1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(h)),h.withActiveRoot({entity:"Platform",id:t.id})}const dt=new rt(lt,{Platform:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:f.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:f.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:f.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:f.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:f.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:f.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:f.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:ut}),ct={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},x=document.querySelector("#status"),pt=document.querySelector("#result"),B=document.querySelector("#persist"),W=document.querySelector("#reset");let S;const X=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=X==="opfs";async function mt(h){const t=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),e=await st.open(t,{...ct},{storage:h,databaseName:"teaql-browser-example.sqlite3"});e.install(dt);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new K().insertResource("dataService",e).withMutationPolicyRegistry(new nt(()=>({identity:i,review:(n,s)=>s.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ot(n=>({policy:n,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Z({context:h}){if(!(await A.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(h)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await(await A.workItems().comment("reserve one browser demo work item").purpose("seed deterministic data through managed creation").newEntity(h)).updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(h)}async function tt(h){const t=await A.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(h.context);pt.textContent=JSON.stringify(t,null,2),x.textContent=`${h.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function et(h){x.textContent=`Opening ${h.toUpperCase()} SQLite/WASM…`;const t=S;S=void 0,await t?.client.close();const e=await mt(h);S=e,await Z(e),await tt(e)}B.addEventListener("change",()=>{const h=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",h),et(h).catch(M)});W.addEventListener("click",async()=>{if(S){W.disabled=!0;try{await S.client.reset(S.context),await Z(S),await tt(S)}catch(h){M(h)}finally{W.disabled=!1}}});function M(h){const t=h instanceof Error?h:new Error(String(h));x.textContent=`${t.name}: ${t.message}`}et(X).catch(M); diff --git a/dist/assets/dynamic-search-BwvXmN4R.js b/dist/assets/dynamic-search-BwvXmN4R.js new file mode 100644 index 0000000000000000000000000000000000000000..13a6d3c917f969f76b204b94860f0d531a45230a --- /dev/null +++ b/dist/assets/dynamic-search-BwvXmN4R.js @@ -0,0 +1,13 @@ +var Ct=n=>{throw TypeError(n)};var $t=(n,e,t)=>e.has(n)||Ct("Cannot "+t);var x=(n,e,t)=>($t(n,e,"read from private field"),t?t.call(n):e.get(n)),Pe=(n,e,t)=>e.has(n)?Ct("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),_e=(n,e,t,i)=>($t(n,e,"write to private field"),i?i.call(n,t):e.set(n,t),t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const s of o.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&i(s)}).observe(document,{childList:!0,subtree:!0});function t(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=t(r);fetch(r.href,o)}})();const Zi=/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/,en=1024;function ue(n){if(typeof n!="string"||!Zi.test(n)||n.length-Number(n.startsWith("-"))-Number(n.includes("."))>en)throw new TypeError('Decimal requires a finite base-10 string (for example "3.50")');return n}const tn=/^-?(?:0|[1-9][0-9]*)$/,nn=-(1n<<63n),rn=(1n<<63n)-1n;function be(n){if(typeof n!="string"&&typeof n!="bigint")throw new TypeError("Long requires a signed 64-bit integer string or bigint");const e=String(n);if(!tn.test(e))throw new TypeError("Long requires a canonical integer string");const t=BigInt(e);if(trn)throw new RangeError("Long is outside signed 64-bit range");return t.toString()}const sn=/^(?:[01][0-9]|2[0-3]):[0-5][0-9]:[0-5][0-9](?:\.[0-9]{1,6})?$/;function Ce(n){if(typeof n!="string"||!sn.test(n))throw new TypeError("LocalTime requires HH:mm:ss with optional 1-6 fractional digits");const e=n.indexOf(".");if(e<0)return n;const t=n.slice(e+1).padEnd(6,"0");return t==="000000"?n.slice(0,e):`${n.slice(0,e)}.${t}`}const on="modulepreload",an=function(n){return"/"+n},Nt={},cn=function(e,t,i){let r=Promise.resolve();if(t&&t.length>0){let c=function(u){return Promise.all(u.map(l=>Promise.resolve(l).then(d=>({status:"fulfilled",value:d}),d=>({status:"rejected",reason:d}))))};document.getElementsByTagName("link");const s=document.querySelector("meta[property=csp-nonce]"),a=s?.nonce||s?.getAttribute("nonce");r=c(t.map(u=>{if(u=an(u),u in Nt)return;Nt[u]=!0;const l=u.endsWith(".css"),d=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${d}`))return;const h=document.createElement("link");if(h.rel=l?"stylesheet":on,l||(h.as="script"),h.crossOrigin="",h.href=u,a&&h.setAttribute("nonce",a),document.head.appendChild(h),l)return new Promise((f,p)=>{h.addEventListener("load",f),h.addEventListener("error",()=>p(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(s){const a=new Event("vite:preloadError",{cancelable:!0});if(a.payload=s,window.dispatchEvent(a),!a.defaultPrevented)throw s}return r.then(s=>{for(const a of s||[])a.status==="rejected"&&o(a.reason);return e().catch(o)})};function ln(n){const e=n instanceof Error&&n.constructor?.name?n.constructor.name.toLowerCase():typeof n;return/timeout|deadline/.test(e)?"timeout":/authentication|authorization|unauthorized|forbidden|permission/.test(e)?"authorization":/validation|invalidargument|valueerror|parse|format/.test(e)?"validation":/conflict|optimistic|version|duplicate|alreadyexists/.test(e)?"conflict":/transport|network|connection|socket|http|ioerror/.test(e)?"transport":/provider|sql|database|jdbc/.test(e)?"provider":"internal"}const xt=Object.freeze({success:()=>{},failure:()=>{}}),un=new Set(["teaql.entity.id","teaql.user.id","teaql.tenant.id","teaql.query.parameters","teaql.field.values","teaql.audit.reason","db.query.parameter_values","http.request.body","url.full"]);function dn(n){const e={"teaql.operation.family":n.family,"teaql.operation.name":n.name};for(const[t,i]of Object.entries(n.attributes||{}))un.has(t)||(e[t]=i);return Object.freeze({...n,attributes:Object.freeze(e)})}function H(n,e){if(!n)return xt;try{const t=n.start(dn(e));let i=!1;return{correlation:()=>{try{return t.correlation?.()}catch{return}},run:t.run?r=>t.run(r):r=>r(),success(r){if(!i){i=!0;try{t?.success(r)}catch{}}},failure(r){if(!i){i=!0;try{t?.failure(r)}catch{}}}}}catch{return xt}}async function me(n,e,t,i){const r=H(n,e);try{const o=await(r.run?r.run(t):t());return r.success(i?.(o)),o}catch(o){throw r.failure(o),o}}const xe=class xe extends Error{constructor(e){super(`Check failed: ${e.map(i=>i.message??`${i.ruleId}:${i.location}`).join("; ")}`),this.violations=e,this.name="CheckException";const t=[...e];Object.defineProperty(this,"violations",{value:t,enumerable:!0}),xe.owned.set(this,t)}refreshPresentation(e){const t=xe.owned.get(this);t&&(e.length===t.length&&e.every((i,r)=>i.message===t[r].message)||(t.splice(0,t.length,...e),this.message=`Check failed: ${e.map(i=>i.message??`${i.ruleId}:${i.location}`).join("; ")}`))}};xe.owned=new WeakMap;let G=xe;function hi(n){const e=n.split("_");return e[0]+e.slice(1).map(t=>t?t[0].toUpperCase()+t.slice(1):"").join("")}function hn(n,e){if(e==="snake_case")return n;const t=hi(n);return e==="camelCase"||!t?t:t[0].toUpperCase()+t.slice(1)}function fn(n){return n.replace(/~/g,"~0").replace(/\//g,"~1")}class F{constructor(e){this.segments=e}static root(){return new F([])}static property(e){return F.root().property(e)}property(e){return new F([...this.segments,{kind:"property",name:e}])}index(e){return new F([...this.segments,{kind:"index",index:e}])}prefixedBy(e){return new F([...e.segments,...this.segments])}modelPath(){return this.render(e=>e)}nativePath(){return this.render(hi)}instancePath(e="camelCase"){return this.segments.map(t=>t.kind==="index"?String(t.index):fn(hn(t.name,e))).map(t=>`/${t}`).join("")}toString(){return this.nativePath()}render(e){let t="";for(const i of this.segments)i.kind==="index"?t+=`[${i.index}]`:t+=`${t?".":""}${e(i.name)}`;return t}}const fi=-(1n<<63n),pi=(1n<<63n)-1n,qt=BigInt(Number.MAX_SAFE_INTEGER);class X extends G{constructor(e,t="mutation"){super([{ruleId:e,location:F.property("version"),message:e==="version_exhausted"?`${t} version is exhausted in the signed 64-bit domain`:`${t} requires an exact version in its permitted lifecycle state`}]),this.code=e,this.name="MutationVersionError"}}function M(n){let e;if(typeof n=="bigint")e=n;else if(typeof n=="number"&&Number.isSafeInteger(n))e=BigInt(n);else if(typeof n=="string"&&/^(?:0|-?[1-9][0-9]*)$/.test(n))e=BigInt(n);else throw new X("invalid_type");if(epi)throw new X("invalid_type");return e>=-qt&&e<=qt?Number(e):be(e)}function ct(n,e){if(n==="Create")return 1;const t=BigInt(M(e));let i;switch(n){case"Update":if(t<=0n)throw new X("invalid_type",n);i=t+1n;break;case"Delete":if(t<=0n)throw new X("invalid_type",n);i=-t-1n;break;case"Recover":if(t>=0n)throw new X("invalid_type",n);i=-t+1n;break;default:throw new X("invalid_type")}if(ipi)throw new X("version_exhausted",n);return M(i)}const qe=new WeakMap,He=new WeakMap;function Mt(n){return He.get(n)}function pn(n,e){He.set(n,e)}function mn(n){return qe.get(n)}function je(n,e){qe.set(e,qe.get(n)??N(n))}function N(n,e=new Map){if(!n||typeof n!="object")return n;if(e.has(n))return e.get(n);if(n instanceof Date)return new Date(n.getTime());if(n instanceof Uint8Array)return new Uint8Array(n);const t=Array.isArray(n)?[]:Object.create(Object.getPrototypeOf(n));e.set(n,t);for(const o of Reflect.ownKeys(n)){const s=Object.getOwnPropertyDescriptor(n,o);"value"in s&&s.enumerable&&(s.value=N(s.value,e)),Object.defineProperty(t,o,s)}const i=qe.get(n);i&&qe.set(t,i);const r=He.get(n);return r&&He.set(t,r),t}function B(n){return Object.freeze(n.map(e=>Object.freeze({...e})))}class gn{#e;#t;constructor(e,t){this.#e=e,this.#t=Object.freeze({...t}),Object.freeze(this)}recover(){const e=[];let t=this;for(;t;)e.push(t.#t),t=t.#e;return B(e.reverse())}}function yn(n,e,t,i,r){const o=n?r:i;if(n&&(typeof o!="string"||new RegExp("^\\p{White_Space}*$","u").test(o)))return n;const s=String(t),a=/^(0|[1-9][0-9]*)$/.test(s)&&BigInt(s)<=18446744073709551615n?t:void 0;return new gn(n,{kind:"auditReason",name:e,entityId:a,detail:o})}const bn=new Set(["comment","purpose","auditReason"]),lt=n=>!new RegExp("^\\p{White_Space}*$","u").test(n);function gt(n,e,t){const i=s=>{for(let a=n.length-1;a>=0;a--)if(n[a].kind===s)return n[a].detail??""},r=["operation","provider","sql"].every(s=>n.some(a=>a.kind===s));let o;if(r)o=n.filter(s=>!bn.has(s.kind));else{const s=n.find(c=>lt(c.name))?.name??"unknown";let a=s;if(t!=="select")for(const c of n)c.kind==="entity"&<(c.name)&&(a=c.name);o=[{kind:"operation",name:s,detail:t==="select"?"query":"mutation"},{kind:t==="select"?"request":"entity",name:t==="select"?s:a,detail:""},...n.filter(c=>c.kind==="relation"),{kind:"provider",name:lt(e)?e:"unknown",detail:""},{kind:"sql",name:t,detail:""}]}return Object.freeze({tracePath:B(o),comment:i("comment"),purpose:i("purpose"),auditReason:i("auditReason")})}function mi(n,e,t){return B([{kind:"comment",name:n,detail:e},{kind:"purpose",name:n,detail:t}])}const C=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class wn{constructor(){this.changes=new Map,this.originalVersions=new Map,this.newKeys=new Map,this.deletedKeys=new Map,this.traces=new Map}setTraceChain(e,t){this.traces.set(C(e),{key:Object.freeze({...e}),nodes:B(t)})}traceChain(e){return this.traces.get(C(e))?.nodes}set(e,t,i){if(!t.trim())throw new TypeError("field is required");const r=C(e),o=this.changes.get(r)??{key:Object.freeze({...e}),values:Object.create(null)};o.values[t]=i,this.changes.set(r,o)}snapshot(){return[...this.changes.values()].map(e=>({key:Object.freeze({...e.key}),values:Object.freeze({...e.values})}))}change(e){return Object.freeze({...this.changes.get(C(e))?.values??{}})}captureFields(e,t){const i=C(e),r=this.changes.get(i)?.values??{},o=new Map(t.map(s=>[s,{present:Object.prototype.hasOwnProperty.call(r,s),value:N(r[s])}]));return()=>{const s=this.changes.get(i)??{key:Object.freeze({...e}),values:Object.create(null)};for(const[a,c]of o)c.present?s.values[a]=N(c.value):delete s.values[a];Object.keys(s.values).length?this.changes.set(i,s):this.changes.delete(i)}}discardFields(e,t){const i=C(e),r=this.changes.get(i);if(r){for(const[o,s]of Object.entries(t))Object.prototype.hasOwnProperty.call(r.values,o)&&Object.is(r.values[o],s)&&delete r.values[o];Object.keys(r.values).length||this.changes.delete(i)}}mergeFrom(e){if(e!==this){for(const t of e.snapshotVersions())this.requireMatchingVersion(t.key,t.version);for(const t of e.snapshot())for(const[i,r]of Object.entries(t.values))this.set(t.key,i,r);for(const t of e.newKeys.values())this.markAsNew(t);for(const t of e.deletedKeys.values())this.markAsDeleted(t);for(const t of e.snapshotVersions())this.setOriginalVersion(t.key,t.version);for(const t of e.traces.values())this.setTraceChain(t.key,t.nodes)}}mergeEntityFrom(e,t){if(e===this)return;const i=e.originalVersion(t);i!==void 0&&this.requireMatchingVersion(t,i);for(const[o,s]of Object.entries(e.change(t)))this.set(t,o,s);e.isNew(t)&&this.markAsNew(t),e.isDeleted(t)&&this.markAsDeleted(t),i!==void 0&&this.setOriginalVersion(t,i);const r=e.traceChain(t);r&&this.setTraceChain(t,r)}hasPending(e){const t=C(e);return this.newKeys.has(t)||this.deletedKeys.has(t)||Object.keys(this.changes.get(t)?.values??{}).length>0}snapshotVersions(){return[...this.originalVersions.values()]}rekey(e,t){const i=C(e),r=C(t);if(i===r)return;const o=this.originalVersion(e);o!==void 0&&this.requireMatchingVersion(t,o);const s=this.changes.get(i);if(s){this.changes.delete(i);for(const[u,l]of Object.entries(s.values))this.set(t,u,l)}const a=this.originalVersions.get(i);a!==void 0&&(this.originalVersions.delete(i),this.originalVersions.set(r,{key:Object.freeze({...t}),version:a.version})),this.newKeys.delete(i)&&this.newKeys.set(r,Object.freeze({...t})),this.deletedKeys.delete(i)&&this.deletedKeys.set(r,Object.freeze({...t}));const c=this.traces.get(i);c&&(this.traces.delete(i),this.setTraceChain(t,c.nodes))}clearEntity(e){const t=C(e);this.changes.delete(t),this.newKeys.delete(t),this.deletedKeys.delete(t),this.traces.delete(t)}requireMatchingVersion(e,t){const i=this.originalVersion(e);if(i!==void 0&&i!==t)throw new Error("ENTITY_VERSION_CONFLICT: one graph cannot contain different loaded versions of the same typed entity")}setOriginalVersion(e,t){const i=M(t);this.requireMatchingVersion(e,i),this.originalVersions.set(C(e),{key:Object.freeze({...e}),version:i})}acceptCommittedVersion(e,t){const i=M(t);if(this.hasPending(e))throw new Error("ENTITY_COMMIT_PENDING: clear committed changes before accepting the persisted version");this.originalVersions.set(C(e),{key:Object.freeze({...e}),version:i})}originalVersion(e){return this.originalVersions.get(C(e))?.version}markAsNew(e){this.newKeys.set(C(e),Object.freeze({...e}))}isNew(e){return this.newKeys.has(C(e))}markAsDeleted(e){const t=C(e);this.changes.delete(t),this.deletedKeys.set(t,Object.freeze({...e}))}isDeleted(e){return this.deletedKeys.has(C(e))}clearCommitted(){this.changes.clear(),this.newKeys.clear(),this.deletedKeys.clear(),this.traces.clear()}}const Ve=new WeakMap;class Ue extends G{constructor(e){super([{ruleId:"entity_version_conflict",location:F.property(e),message:"ENTITY_VERSION_CONFLICT: loaded entity identity must remain unchanged"}]),this.code="ENTITY_VERSION_CONFLICT",this.name="LoadedEntityIdentityError"}}class ${#e;#t;#n;#r;#i;constructor(e={},t,i,r="hydrated"){if(this.#e=N(e),this.#r=r,r==="hydrated"&&t&&i!==void 0){const o=M(i);this.#i=o,o!==0&&(e.id!==void 0&&(this.#n=Object.freeze({...t})),this.#t=Object.freeze({key:Object.freeze({...t}),version:o}))}!this.#n&&t&&e.id!==void 0&&(this.#n=Object.freeze({...t})),Object.freeze(this)}values(){return N(this.#e)}get origin(){return this.#r}get persistedVersion(){return this.#i}changedField(e){return[...new Set([...Object.keys(this.#e),...Object.keys(e)])].sort().find(i=>!Object.prototype.hasOwnProperty.call(this.#e,i)||!Object.prototype.hasOwnProperty.call(e,i)||!yt(this.#e[i],e[i]))}validateNativeIdentity(e,t,i){const r=this.#n;if(r&&(r.entity!==e.entity||!Object.is(r.id,e.id)||!Object.is(r.id,t)))throw new Ue("id");if(this.#t){let o;try{o=M(i)}catch{throw new Ue("version")}if(o!==this.#t.version)throw new Ue("version")}}validateMutationVersion(e,t){if(!(!this.#t||!e.hasPending(t))&&(this.#t.key.entity!==t.entity||!Object.is(this.#t.key.id,t.id)||e.isNew(t)||e.originalVersion(t)!==this.#t.version))throw new Ue("version")}static captureFor(e,t,i,r,o="hydrated"){const s=new $(t,i,r,o);return Ve.set(e,s),s}static forEntity(e){return Ve.get(e)}static restoreFor(e,t){t?Ve.set(e,t):Ve.delete(e)}discardRestoredFields(e,t,i){const r=this.#t;if(!r||r.key.entity!==t.entity||!Object.is(r.key.id,t.id)||e.originalVersion(t)!==r.version||e.isNew(t)||e.isDeleted(t))return;const o=Object.create(null);for(const[s,a]of Object.entries(e.change(t))){const c=Object.getOwnPropertyDescriptor(this.#e,s);s!=="id"&&s!=="version"&&c&&"value"in c&&c.value!==void 0&&yt(c.value,a)&&(o[s]=a)}e.discardFields(t,o),Object.keys(o).length&&i?.(N(o))}}function yt(n,e,t={nodes:4096},i=0){if(--t.nodes<0||i>64||typeof n!=typeof e)return!1;if(typeof n=="number")return Number.isFinite(n)&&Number.isFinite(e)&&Object.is(n,e);if(n===null||e===null||typeof n!="object")return Object.is(n,e);if(n instanceof Date||e instanceof Date)return n instanceof Date&&e instanceof Date&&Number.isFinite(n.getTime())&&n.getTime()===e.getTime();if(n instanceof Uint8Array||e instanceof Uint8Array)return n instanceof Uint8Array&&e instanceof Uint8Array&&n.length===e.length&&n.every((a,c)=>a===e[c]);if(Array.isArray(n)!==Array.isArray(e)||!Array.isArray(n)&&(Object.getPrototypeOf(n)!==Object.prototype&&Object.getPrototypeOf(n)!==null||Object.getPrototypeOf(e)!==Object.prototype&&Object.getPrototypeOf(e)!==null)||Array.isArray(n)&&n.length!==e.length)return!1;const r=Object.getOwnPropertyDescriptors(n),o=Object.getOwnPropertyDescriptors(e),s=Object.keys(r).filter(a=>r[a].enumerable);return s.length!==Object.keys(o).filter(a=>o[a].enumerable).length?!1:s.every(a=>Object.prototype.hasOwnProperty.call(o,a)&&o[a].enumerable&&"value"in r[a]&&"value"in o[a]&&yt(r[a].value,o[a].value,t,i+1))}const Ae=new WeakMap;class Dt{static run(e,t,i,r){const o=new Map(Object.entries(i?.columns??{}).map(([l,d])=>[d.modelName??l,{...d}])),s=()=>t.action==="Create"||t.action==="Update"&&Object.entries(t.payload??{}).some(([l,d])=>{if(l==="id"||l==="version"||l.startsWith("_"))return!1;const h=o.get(l);return h?.createFunction||h?.updateFunction?!1:Object.prototype.hasOwnProperty.call(t.loadedValues??{},l)?new $({[l]:t.loadedValues[l]}).changedField({[l]:d})!==void 0:!0}),a=s(),c=[...o].filter(([,l])=>l.createFunction||l.updateFunction).map(([l])=>({field:l,present:Object.prototype.hasOwnProperty.call(t.payload??{},l),value:N(t.payload?.[l])})),u=Ae.get(t);Ae.set(t,{context:e,eligible:a,columns:o,now:e.getResource("fixTime")});try{const l=r();if(t.action==="Update"&&!s())for(const d of c)d.present?t.payload[d.field]=N(d.value):delete t.payload[d.field];return l}finally{u?Ae.set(t,u):Ae.delete(t)}}static apply(e,t,i,r,o=[]){const s=Ae.get(t),a=()=>new G([{ruleId:"invalid_type",entityType:String(t.entity),location:F.property(i),message:`Context Fix failed at ${t.entity}.${i}`}]);if(!s||s.context!==e)throw a();if(!s.eligible)return;const c=s.columns.get(i),u=t.action==="Create"?c?.createFunction:c?.updateFunction;if(!c||!u||u!==r)throw a();try{const l=e.getResource("contextFixResolver");let d;if(l)d=l(e,Object.freeze({entity:String(t.entity),field:i,function:r,arguments:Object.freeze([...o]),action:t.action,now:new Date(s.now.getTime())}));else if(r==="now")d=new Date(s.now.getTime());else if(r==="uniStr"){const h=new Uint8Array(16);globalThis.crypto.getRandomValues(h),d=(o[0]??"")+Array.from(h,f=>f.toString(16).padStart(2,"0")).join("")}else throw a();if(d instanceof Promise)throw d.catch(()=>{}),a();if(!this.validValue(c,d))throw a();t.payload[i]=N(d),e.recordFixEvidence({entityType:String(t.entity),modelPath:i,source:r==="now"?"clock":"context",sourceLabel:r==="now"?"graphClock":`contextFunction:${r}`})}catch{throw a()}}static captureUndo(e,t){if(!(e.ledgerRoot instanceof wn)||!e.ledgerKey)return;const i=Object.entries(t?.columns??{}).filter(([,r])=>r.createFunction||r.updateFunction).map(([r,o])=>o.modelName??r);return i.length?e.ledgerRoot.captureFields(e.ledgerKey,i):void 0}static validValue(e,t){if(t===null)return!0;switch(e.logicalType){case"text":return typeof t=="string";case"datetime":case"date":return t instanceof Date&&Number.isFinite(t.getTime());case"boolean":return typeof t=="boolean";case"double":return typeof t=="number"&&Number.isFinite(t);case"integer":return typeof t=="number"&&Number.isSafeInteger(t);case"decimal":return typeof t=="string"&&ue(t)===t;case"long":return typeof t=="string"&&be(t)===t;case"time":return typeof t=="string"&&Ce(t)===t;case"json":return t!==void 0&&!(t instanceof Promise);default:return!1}}}var vn={};const Sn="TEAQL_ALLOW_SENSITIVE_PLAINTEXT_LOGS",En="I_UNDERSTAND_SENSITIVE_DATA_MAY_BE_WRITTEN_TO_DISK",bt="[REDACTED]";let Ft=!1;function On(n){const e=Array.from(n);return e.length<8||/^[0-9]+$/.test(n)?"*".repeat(e.length):e.slice(0,2).join("")+"*".repeat(e.length-4)+e.slice(-2).join("")}function gi(){const e=vn?.[Sn]===En;return e&&!Ft&&(Ft=!0,console.warn("TeaQL: sensitive plaintext logging enabled; application data may be written to disk. Authentication secrets remain redacted.")),e}function fe(n){const e=n.toLowerCase().replace(/[^a-z0-9]/g,"");return["password","passwd","passphrase","privatekey","secret","accesstoken","refreshtoken","idtoken","apikey","authorization","credential","sessiontoken","magiclinktoken"].some(t=>e.includes(t))}function ot(n){return!!n&&typeof n=="object"&&wt(n,new WeakSet)}function wt(n,e){if(!n||typeof n!="object"||e.has(n))return!1;e.add(n);try{return Array.isArray(n)?n.some(t=>wt(t,e)):Object.entries(n).some(([t,i])=>fe(t)||wt(i,e))}finally{e.delete(n)}}function J(n){return n==null||n===""?[]:typeof n=="object"?vt(n,new WeakSet):[String(n)]}function vt(n,e){if(n==null||n==="")return[];if(typeof n=="object"){if(e.has(n))return[];e.add(n);try{return Array.isArray(n)?n.flatMap(t=>vt(t,e)):n instanceof Date?[n.toISOString()]:Object.values(n).flatMap(t=>vt(t,e))}finally{e.delete(n)}}return[String(n)]}function re(n,e){return[...new Set(e)].sort((t,i)=>i.length-t.length).reduce((t,i)=>t?.split(i).join(bt),n)}function Xe(n,e=new WeakSet){if(n==null)return null;if(typeof n=="object"){if(e.has(n))return bt;e.add(n);try{if(Array.isArray(n))return n.map(t=>Xe(t,e));if("type"in n)return Xe(n.value,e);if(!(n instanceof Date))return bt}finally{e.delete(n)}}return On(n instanceof Date?n.toISOString():String(n))}const yi=Symbol("TeaQL.CheckerPresentation"),bi=new WeakMap,we=new WeakMap,at=n=>{const e=n[yi];return e&&bi.get(e)};function St(n,e){const t=Object.freeze({});bi.set(t,e),Object.defineProperty(n,yi,{value:t,enumerable:!0,configurable:!0})}function _t(n){const e=at(n);return e?.masked&&Object.is(e.value,n.inputValue)&&e.length!==void 0?e.length:typeof n.inputValue=="string"?Array.from(n.inputValue).length:0}function jn(n,e,t,i){const r=n.location.segments.filter(a=>a.kind==="property").map(a=>a.name),o=r[r.length-1]??"",s=t?.(n.entityType?.trim()?n.entityType:e,o);return r.some(fe)||s==="credential"||ot(n.inputValue)?"credential":!i&&(s==="masked"||o.startsWith("#"))?"masked":void 0}function kn(n,e){const t=n.systemValue;return t==null||typeof t=="number"||typeof t=="bigint"||typeof t=="boolean"?t:e==="credential"||ot(t)?"[REDACTED]":t}function Tn(n){const e=Xe(n),t=i=>Array.isArray(i)?Object.freeze(i.map(t)):i;return t(e)}function zt(n,e,t,i){const r={...n},o=at(n),s=jn(n,e,t,i);e&&!r.entityType?.trim()&&(r.entityType=e);const a=o?.masked&&Object.is(o.value,n.inputValue)&&(o.kind==="credential"||s!=="credential");let c=n.inputValue;!a&&c!==null&&c!==void 0&&(s==="credential"?c="[REDACTED]":s==="masked"&&(c=Tn(c)));const u=kn(n,s),l=!Object.is(c,n.inputValue)||!Object.is(u,n.systemValue);Object.prototype.hasOwnProperty.call(n,"inputValue")&&(r.inputValue=c),Object.prototype.hasOwnProperty.call(n,"systemValue")&&(r.systemValue=u);const d=[...Object.is(c,n.inputValue)?[]:J(n.inputValue),...Object.is(u,n.systemValue)?[]:J(n.systemValue)],f=!!a||!Object.is(c,n.inputValue)?{masked:!0,value:c,length:_t(n),kind:a?o.kind:s}:{};return!l&&o?.message!==void 0&&o.message===n.message&&(f.message=o.message,f.automatic=o.automatic),{value:r,state:f,changed:l,secrets:d}}function Vt(n){return[...new Set(n.flatMap(e=>e?[e,JSON.stringify(e).slice(1,-1)]:[]))].sort((e,t)=>t.length-e.length)}function Ye(n,e,t,i=[]){const r=gi(),o=n.map(l=>zt(l,e,t,r)),s=n.flatMap(l=>we.get(l)?.redactions??[]),a=i.flatMap(l=>Object.entries(l).flatMap(([d,h])=>{const f=t?.(e,d);return fe(d)||ot(h)||f==="credential"||!r&&(f==="masked"||d.startsWith("#"))?J(h):[]})),c=Vt([...s,...a,...o.flatMap(l=>l.secrets)]),u=o.map(l=>(l.value.message!==void 0&&(l.value.message=re(l.value.message,c)),St(l.value,{...l.state,message:l.value.message}),we.set(l.value,{redactions:c,length:l.state.length??_t(l.value),input:l.value.inputValue,system:l.value.systemValue}),l.value));return{values:u,finish(l){const d=l.map(f=>zt(f,e,t,r)),h=Vt([...c,...d.flatMap(f=>f.secrets)]);return d.map(f=>(f.state.message===void 0&&(f.value.message=re(f.value.message,h)),St(f.value,{...f.state,message:f.value.message}),f.value))},close(){for(const l of u)we.delete(l)}}}function wi(n){return we.get(n)?.length??_t(n)}function Je(n,e){return re(e,we.get(n)?.redactions??[])??""}function vi(n){const e=we.get(n);e&&Object.is(e.input,n.inputValue)&&Object.is(e.system,n.systemValue)&&St(n,{...at(n),message:n.message,automatic:!0})}function Ln(n){const e=at(n);return e?.automatic===!0&&e.message===n.message}function Si(n,e,t,i,r=[]){if(!e.length){const s=n.translateCheckResults(e,t);if(!s.length)return;const a=Ye(s,t,i,r);try{e.splice(0,e.length,...a.finish(a.values))}finally{a.close()}return}const o=Ye(e,t,i,r);try{const s=n.translateCheckResults(o.values,t);e.splice(0,e.length,...o.finish(s))}finally{o.close()}}const In="teaql.i18n/v1",Pn="en",_n={en:{messages:{"checker.required":"The {location} is required","checker.min":"The {location} should be equal or greater than {system}, but input is {input}","checker.max":"The {location} should be equal or less than {system}, but input is {input}","checker.minLength":"The length of {location} should be equal or greater than {system}, but the length of {input} is {input_len}","checker.maxLength":"The length of {location} should be equal or less than {system}, but the length of {input} is {input_len}"},vocabulary:{}},"zh-CN":{messages:{"checker.required":"{location} 是必填项","checker.min":"{location} 应该大于等于 {system},但输入值为 {input}","checker.max":"{location} 应该小于等于 {system},但输入值为 {input}","checker.minLength":"{location} 的长度应大于等于 {system},但实际长度为 {input_len}","checker.maxLength":"{location} 的长度应小于等于 {system},但实际长度为 {input_len}"},vocabulary:{}},"zh-TW":{messages:{"checker.required":"{location} 是必填的","checker.min":"{location} 應該等於或大於 {system},但輸入為 {input}","checker.max":"{location} 應該等於或小於 {system},但輸入為 {input}","checker.minLength":"{location} 的長度應該等於或大於 {system},但 {input} 的長度是 {input_len}","checker.maxLength":"{location} 的長度應該等於或小於 {system},但 {input} 的長度是 {input_len}"},vocabulary:{}},ja:{messages:{"checker.required":"{location} は必須です","checker.min":"{location} は {system} 以上である必要があります。入力値は {input} です","checker.max":"{location} は {system} 以下である必要があります。入力値は {input} です","checker.minLength":"{location} の長さは {system} 以上である必要があります。実際の長さは {input_len} です","checker.maxLength":"{location} の長さは {system} 以下である必要があります。実際の長さは {input_len} です"},vocabulary:{}},ko:{messages:{"checker.required":"{location}은(는) 필수입니다","checker.min":"{location}은(는) {system} 이상이어야 하지만 입력값은 {input}입니다","checker.max":"{location}은(는) {system} 이하여야 하지만 입력값은 {input}입니다","checker.minLength":"{location}의 길이는 {system} 이상이어야 하지만 실제 길이는 {input_len}입니다","checker.maxLength":"{location}의 길이는 {system} 이하여야 하지만 실제 길이는 {input_len}입니다"},vocabulary:{}},de:{messages:{"checker.required":"{location} ist erforderlich","checker.min":"{location} muss mindestens {system} sein, aber die Eingabe ist {input}","checker.max":"{location} darf höchstens {system} sein, aber die Eingabe ist {input}","checker.minLength":"Die Länge von {location} muss mindestens {system} sein, ist aber {input_len}","checker.maxLength":"Die Länge von {location} darf höchstens {system} sein, ist aber {input_len}"},vocabulary:{}},fr:{messages:{"checker.required":"{location} est obligatoire","checker.min":"{location} doit être supérieur ou égal à {system}, mais la valeur saisie est {input}","checker.max":"{location} doit être inférieur ou égal à {system}, mais la valeur saisie est {input}","checker.minLength":"La longueur de {location} doit être supérieure ou égale à {system}, mais elle est {input_len}","checker.maxLength":"La longueur de {location} doit être inférieure ou égale à {system}, mais elle est {input_len}"},vocabulary:{}},es:{messages:{"checker.required":"{location} es requerido/a","checker.min":"{location} debe ser mayor o igual que {system}, pero el valor ingresado es {input}","checker.max":"{location} debe ser menor o igual que {system}, pero el valor ingresado es {input}","checker.minLength":"La longitud de {location} debe ser mayor o igual que {system}, pero es {input_len}","checker.maxLength":"La longitud de {location} debe ser menor o igual que {system}, pero es {input_len}"},vocabulary:{}},pt:{messages:{"checker.required":"{location} é obrigatório","checker.min":"{location} deve ser maior ou igual a {system}, mas a entrada é {input}","checker.max":"{location} deve ser menor ou igual a {system}, mas a entrada é {input}","checker.minLength":"O comprimento de {location} deve ser maior ou igual a {system}, mas é {input_len}","checker.maxLength":"O comprimento de {location} deve ser menor ou igual a {system}, mas é {input_len}"},vocabulary:{}},ar:{messages:{"checker.required":"{location} مطلوب","checker.min":"يجب أن يكون {location} مساويًا أو أكبر من {system}، لكن المُدخل هو {input}","checker.max":"يجب أن يكون {location} مساويًا أو أصغر من {system}، لكن المُدخل هو {input}","checker.minLength":"يجب أن يكون طول {location} مساويًا أو أكبر من {system}، لكن الطول هو {input_len}","checker.maxLength":"يجب أن يكون طول {location} مساويًا أو أصغر من {system}، لكن الطول هو {input_len}"},vocabulary:{}},th:{messages:{"checker.required":"{location} เป็นสิ่งจำเป็น","checker.min":"{location} ควรจะเท่ากับหรือมากกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.max":"{location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ข้อมูลที่ป้อนคือ {input}","checker.minLength":"ความยาวของ {location} ควรจะเท่ากับหรือมากกว่า {system} แต่ความยาวคือ {input_len}","checker.maxLength":"ความยาวของ {location} ควรจะเท่ากับหรือน้อยกว่า {system} แต่ความยาวคือ {input_len}"},vocabulary:{}},id:{messages:{"checker.required":"{location} wajib diisi","checker.min":"{location} harus sama dengan atau lebih besar dari {system}, tetapi input adalah {input}","checker.max":"{location} harus sama dengan atau lebih kecil dari {system}, tetapi input adalah {input}","checker.minLength":"Panjang {location} harus sama dengan atau lebih besar dari {system}, tetapi panjangnya {input_len}","checker.maxLength":"Panjang {location} harus sama dengan atau lebih kecil dari {system}, tetapi panjangnya {input_len}"},vocabulary:{}},fil:{messages:{"checker.required":"Ang {location} ay kinakailangan","checker.min":"Ang {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang input ay {input}","checker.max":"Ang {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang input ay {input}","checker.minLength":"Ang haba ng {location} ay dapat katumbas o mas malaki kaysa {system}, ngunit ang haba ay {input_len}","checker.maxLength":"Ang haba ng {location} ay dapat katumbas o mas maliit kaysa {system}, ngunit ang haba ay {input_len}"},vocabulary:{}},uk:{messages:{"checker.required":"{location} є обов'язковим","checker.min":"{location} повинен бути рівним або більшим за {system}, але ввідне значення {input}","checker.max":"{location} повинен бути рівним або меншим за {system}, але ввідне значення {input}","checker.minLength":"Довжина {location} повинна бути рівною або більшою за {system}, але довжина становить {input_len}","checker.maxLength":"Довжина {location} повинна бути рівною або меншою за {system}, але довжина становить {input_len}"},vocabulary:{}},vi:{messages:{"checker.required":"{location} là bắt buộc","checker.min":"{location} phải lớn hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.max":"{location} phải nhỏ hơn hoặc bằng {system}, nhưng giá trị nhập là {input}","checker.minLength":"Độ dài của {location} phải lớn hơn hoặc bằng {system}, nhưng độ dài là {input_len}","checker.maxLength":"Độ dài của {location} phải nhỏ hơn hoặc bằng {system}, nhưng độ dài là {input_len}"},vocabulary:{}}},An={schema:In,defaultLocale:Pn,locales:_n},pe=["en","zh-CN","zh-TW","ja","ko","de","fr","es","pt","ar","th","id","fil","uk","vi"];class Ut extends Error{constructor(e){super(`Unsupported locale: ${e}`),this.localeCode=e}}const Rn={"en-us":"en","en-gb":"en",zh:"zh-CN","zh-hans":"zh-CN","zh-sg":"zh-CN",cn:"zh-CN","zh-hant":"zh-TW","zh-hk":"zh-TW","zh-mo":"zh-TW",tw:"zh-TW","ja-jp":"ja","ko-kr":"ko","de-de":"de","fr-fr":"fr","es-mx":"es","pt-br":"pt","pt-pt":"pt","ar-sa":"ar","th-th":"th","id-id":"id",tl:"fil","fil-ph":"fil","uk-ua":"uk","vi-vn":"vi"};function ke(n){if(typeof n!="string"||!n.trim())throw new Ut(n);const e=n.trim().replace(/_/g,"-").toLowerCase(),t=pe.find(r=>r.toLowerCase()===e);if(t)return t;const i=Rn[e];if(!i)throw new Ut(n);return i}const ye=class ye{constructor(e,t){if(this.data=e,this.fallback=t,e.schema!=="teaql.i18n/v1")throw new Error("Unsupported i18n schema");Object.keys(e.locales).forEach(ke)}message(e,t){return this.data.locales[e]?.messages[t]??this.fallback?.data.locales[e]?.messages[t]??this.data.locales.en?.messages[t]??this.fallback?.data.locales.en?.messages[t]??t}applicationMessage(e,t){return this===ye.builtin?void 0:this.data.locales[e]?.messages[t]}translate(e,t){const r={required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"}[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,o=this.message(t,r);if(o===r&&e.message?.trim())return e;const s=String(e.inputValue),a={"{location}":e.location.nativePath(),"{system}":String(e.systemValue),"{input}":s,"{input_len}":String(wi(e))},c=o===ye.builtin.message(t,r);return e.message=o.split(/(\{(?:location|system|input|input_len)\})/g).map(u=>Object.prototype.hasOwnProperty.call(a,u)?a[u]:c?u:Je(e,u)).join(""),vi(e),e}};ye.builtin=new ye(An);let $e=ye;const Cn="teaql.checker-messages/v1",$n="en",Nn=JSON.parse('{"en":{"rules":{"checker.required":{"one":"The {field} is required.","two":"The {field} of {object} is required.","deep":"The {field} is required.\\nLocation: {objectPath}"},"checker.min":{"one":"The {field} must be at least {system}.","two":"The {field} of {object} must be at least {system}.","deep":"The {field} must be at least {system}.\\nLocation: {objectPath}"},"checker.max":{"one":"The {field} must not exceed {system}.","two":"The {field} of {object} must not exceed {system}.","deep":"The {field} must not exceed {system}.\\nLocation: {objectPath}"},"checker.minLength":{"one":"The {field} must contain at least {system} {unit}; its current length is {input_len}.","two":"The {field} of {object} must contain at least {system} {unit}; its current length is {input_len}.","deep":"The {field} must contain at least {system} {unit}; its current length is {input_len}.\\nLocation: {objectPath}"},"checker.maxLength":{"one":"The {field} must not exceed {system} {unit}; its current length is {input_len}.","two":"The {field} of {object} must not exceed {system} {unit}; its current length is {input_len}.","deep":"The {field} must not exceed {system} {unit}; its current length is {input_len}.\\nLocation: {objectPath}"},"checker.invalid":{"one":"The {field} is invalid.","two":"The {field} of {object} is invalid.","deep":"The {field} is invalid.\\nLocation: {objectPath}"}},"locationPatterns":{"reference":"the {relation}","item":"the {ordinal} {relation}","separator":" → "}},"zh-CN":{"rules":{"checker.required":{"one":"请填写{field}。","two":"请填写{object}的{field}。","deep":"请填写{field}。\\n位置:{objectPath}"},"checker.min":{"one":"{field}不得小于{system}。","two":"{object}的{field}不得小于{system}。","deep":"{field}不得小于{system}。\\n位置:{objectPath}"},"checker.max":{"one":"{field}不得大于{system}。","two":"{object}的{field}不得大于{system}。","deep":"{field}不得大于{system}。\\n位置:{objectPath}"},"checker.minLength":{"one":"{field}至少需要{system}{unit},当前长度为{input_len}。","two":"{object}的{field}至少需要{system}{unit},当前长度为{input_len}。","deep":"{field}至少需要{system}{unit},当前长度为{input_len}。\\n位置:{objectPath}"},"checker.maxLength":{"one":"{field}最多允许{system}{unit},当前长度为{input_len}。","two":"{object}的{field}最多允许{system}{unit},当前长度为{input_len}。","deep":"{field}最多允许{system}{unit},当前长度为{input_len}。\\n位置:{objectPath}"},"checker.invalid":{"one":"{field}无效。","two":"{object}的{field}无效。","deep":"{field}无效。\\n位置:{objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"第{position}{classifier}{relation}","separator":" → "}},"zh-TW":{"rules":{"checker.required":{"one":"請填寫{field}。","two":"請填寫{object}的{field}。","deep":"請填寫{field}。\\n位置:{objectPath}"},"checker.min":{"one":"{field}不得小於{system}。","two":"{object}的{field}不得小於{system}。","deep":"{field}不得小於{system}。\\n位置:{objectPath}"},"checker.max":{"one":"{field}不得大於{system}。","two":"{object}的{field}不得大於{system}。","deep":"{field}不得大於{system}。\\n位置:{objectPath}"},"checker.minLength":{"one":"{field}至少需要{system}{unit},目前長度為{input_len}。","two":"{object}的{field}至少需要{system}{unit},目前長度為{input_len}。","deep":"{field}至少需要{system}{unit},目前長度為{input_len}。\\n位置:{objectPath}"},"checker.maxLength":{"one":"{field}最多允許{system}{unit},目前長度為{input_len}。","two":"{object}的{field}最多允許{system}{unit},目前長度為{input_len}。","deep":"{field}最多允許{system}{unit},目前長度為{input_len}。\\n位置:{objectPath}"},"checker.invalid":{"one":"{field}無效。","two":"{object}的{field}無效。","deep":"{field}無效。\\n位置:{objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"第{position}{classifier}{relation}","separator":" → "}},"ja":{"rules":{"checker.required":{"one":"{field}は必須です。","two":"{object}の{field}は必須です。","deep":"{field}は必須です。\\n場所: {objectPath}"},"checker.min":{"one":"{field}は{system}以上である必要があります。","two":"{object}の{field}は{system}以上である必要があります。","deep":"{field}は{system}以上である必要があります。\\n場所: {objectPath}"},"checker.max":{"one":"{field}は{system}以下である必要があります。","two":"{object}の{field}は{system}以下である必要があります。","deep":"{field}は{system}以下である必要があります。\\n場所: {objectPath}"},"checker.minLength":{"one":"{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。","two":"{object}の{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。","deep":"{field}には少なくとも{system}{unit}が必要です。現在の長さは{input_len}です。\\n場所: {objectPath}"},"checker.maxLength":{"one":"{field}は最大{system}{unit}です。現在の長さは{input_len}です。","two":"{object}の{field}は最大{system}{unit}です。現在の長さは{input_len}です。","deep":"{field}は最大{system}{unit}です。現在の長さは{input_len}です。\\n場所: {objectPath}"},"checker.invalid":{"one":"{field}が無効です。","two":"{object}の{field}が無効です。","deep":"{field}が無効です。\\n場所: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{position}番目の{relation}","separator":" → "}},"ko":{"rules":{"checker.required":{"one":"{field} 항목은 필수입니다.","two":"{object}의 {field} 항목은 필수입니다.","deep":"{field} 항목은 필수입니다.\\n위치: {objectPath}"},"checker.min":{"one":"{field} 값은 {system} 이상이어야 합니다.","two":"{object}의 {field} 값은 {system} 이상이어야 합니다.","deep":"{field} 값은 {system} 이상이어야 합니다.\\n위치: {objectPath}"},"checker.max":{"one":"{field} 값은 {system} 이하여야 합니다.","two":"{object}의 {field} 값은 {system} 이하여야 합니다.","deep":"{field} 값은 {system} 이하여야 합니다.\\n위치: {objectPath}"},"checker.minLength":{"one":"{field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","two":"{object}의 {field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","deep":"{field} 길이는 최소 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.\\n위치: {objectPath}"},"checker.maxLength":{"one":"{field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","two":"{object}의 {field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.","deep":"{field} 길이는 최대 {system} {unit}이어야 합니다. 현재 길이는 {input_len}입니다.\\n위치: {objectPath}"},"checker.invalid":{"one":"{field} 항목이 유효하지 않습니다.","two":"{object}의 {field} 항목이 유효하지 않습니다.","deep":"{field} 항목이 유효하지 않습니다.\\n위치: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{position}번째 {relation}","separator":" → "}},"de":{"rules":{"checker.required":{"one":"Das Feld {field} ist erforderlich.","two":"Das Feld {field} bei {object} ist erforderlich.","deep":"Das Feld {field} ist erforderlich.\\nPosition: {objectPath}"},"checker.min":{"one":"Das Feld {field} muss mindestens {system} betragen.","two":"Das Feld {field} bei {object} muss mindestens {system} betragen.","deep":"Das Feld {field} muss mindestens {system} betragen.\\nPosition: {objectPath}"},"checker.max":{"one":"Das Feld {field} darf höchstens {system} betragen.","two":"Das Feld {field} bei {object} darf höchstens {system} betragen.","deep":"Das Feld {field} darf höchstens {system} betragen.\\nPosition: {objectPath}"},"checker.minLength":{"one":"Das Feld {field} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","two":"Das Feld {field} bei {object} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","deep":"Das Feld {field} muss mindestens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.\\nPosition: {objectPath}"},"checker.maxLength":{"one":"Das Feld {field} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","two":"Das Feld {field} bei {object} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.","deep":"Das Feld {field} darf höchstens {system} {unit} enthalten; die aktuelle Länge ist {input_len}.\\nPosition: {objectPath}"},"checker.invalid":{"one":"Das Feld {field} ist ungültig.","two":"Das Feld {field} bei {object} ist ungültig.","deep":"Das Feld {field} ist ungültig.\\nPosition: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} Nr. {position}","separator":" → "}},"fr":{"rules":{"checker.required":{"one":"Le champ {field} est obligatoire.","two":"Le champ {field} de {object} est obligatoire.","deep":"Le champ {field} est obligatoire.\\nEmplacement: {objectPath}"},"checker.min":{"one":"Le champ {field} doit être au moins égal à {system}.","two":"Le champ {field} de {object} doit être au moins égal à {system}.","deep":"Le champ {field} doit être au moins égal à {system}.\\nEmplacement: {objectPath}"},"checker.max":{"one":"Le champ {field} ne doit pas dépasser {system}.","two":"Le champ {field} de {object} ne doit pas dépasser {system}.","deep":"Le champ {field} ne doit pas dépasser {system}.\\nEmplacement: {objectPath}"},"checker.minLength":{"one":"Le champ {field} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.","two":"Le champ {field} de {object} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.","deep":"Le champ {field} doit contenir au moins {system} {unit} ; sa longueur actuelle est {input_len}.\\nEmplacement: {objectPath}"},"checker.maxLength":{"one":"Le champ {field} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.","two":"Le champ {field} de {object} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.","deep":"Le champ {field} ne doit pas dépasser {system} {unit} ; sa longueur actuelle est {input_len}.\\nEmplacement: {objectPath}"},"checker.invalid":{"one":"Le champ {field} est invalide.","two":"Le champ {field} de {object} est invalide.","deep":"Le champ {field} est invalide.\\nEmplacement: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} n° {position}","separator":" → "}},"es":{"rules":{"checker.required":{"one":"El campo {field} es obligatorio.","two":"El campo {field} de {object} es obligatorio.","deep":"El campo {field} es obligatorio.\\nUbicación: {objectPath}"},"checker.min":{"one":"El campo {field} debe ser al menos {system}.","two":"El campo {field} de {object} debe ser al menos {system}.","deep":"El campo {field} debe ser al menos {system}.\\nUbicación: {objectPath}"},"checker.max":{"one":"El campo {field} no debe superar {system}.","two":"El campo {field} de {object} no debe superar {system}.","deep":"El campo {field} no debe superar {system}.\\nUbicación: {objectPath}"},"checker.minLength":{"one":"El campo {field} debe contener al menos {system} {unit}; su longitud actual es {input_len}.","two":"El campo {field} de {object} debe contener al menos {system} {unit}; su longitud actual es {input_len}.","deep":"El campo {field} debe contener al menos {system} {unit}; su longitud actual es {input_len}.\\nUbicación: {objectPath}"},"checker.maxLength":{"one":"El campo {field} no debe superar {system} {unit}; su longitud actual es {input_len}.","two":"El campo {field} de {object} no debe superar {system} {unit}; su longitud actual es {input_len}.","deep":"El campo {field} no debe superar {system} {unit}; su longitud actual es {input_len}.\\nUbicación: {objectPath}"},"checker.invalid":{"one":"El campo {field} no es válido.","two":"El campo {field} de {object} no es válido.","deep":"El campo {field} no es válido.\\nUbicación: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} n.º {position}","separator":" → "}},"pt":{"rules":{"checker.required":{"one":"O campo {field} é obrigatório.","two":"O campo {field} de {object} é obrigatório.","deep":"O campo {field} é obrigatório.\\nLocalização: {objectPath}"},"checker.min":{"one":"O campo {field} deve ser pelo menos {system}.","two":"O campo {field} de {object} deve ser pelo menos {system}.","deep":"O campo {field} deve ser pelo menos {system}.\\nLocalização: {objectPath}"},"checker.max":{"one":"O campo {field} não deve exceder {system}.","two":"O campo {field} de {object} não deve exceder {system}.","deep":"O campo {field} não deve exceder {system}.\\nLocalização: {objectPath}"},"checker.minLength":{"one":"O campo {field} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.","two":"O campo {field} de {object} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.","deep":"O campo {field} deve conter pelo menos {system} {unit}; o comprimento atual é {input_len}.\\nLocalização: {objectPath}"},"checker.maxLength":{"one":"O campo {field} não deve exceder {system} {unit}; o comprimento atual é {input_len}.","two":"O campo {field} de {object} não deve exceder {system} {unit}; o comprimento atual é {input_len}.","deep":"O campo {field} não deve exceder {system} {unit}; o comprimento atual é {input_len}.\\nLocalização: {objectPath}"},"checker.invalid":{"one":"O campo {field} é inválido.","two":"O campo {field} de {object} é inválido.","deep":"O campo {field} é inválido.\\nLocalização: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} n.º {position}","separator":" → "}},"ar":{"rules":{"checker.required":{"one":"الحقل {field} مطلوب.","two":"الحقل {field} في {object} مطلوب.","deep":"الحقل {field} مطلوب.\\nالموقع: {objectPath}"},"checker.min":{"one":"يجب ألا تقل قيمة الحقل {field} عن {system}.","two":"يجب ألا تقل قيمة الحقل {field} في {object} عن {system}.","deep":"يجب ألا تقل قيمة الحقل {field} عن {system}.\\nالموقع: {objectPath}"},"checker.max":{"one":"يجب ألا تزيد قيمة الحقل {field} عن {system}.","two":"يجب ألا تزيد قيمة الحقل {field} في {object} عن {system}.","deep":"يجب ألا تزيد قيمة الحقل {field} عن {system}.\\nالموقع: {objectPath}"},"checker.minLength":{"one":"يجب ألا يقل طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.","two":"يجب ألا يقل طول الحقل {field} في {object} عن {system} {unit}؛ الطول الحالي هو {input_len}.","deep":"يجب ألا يقل طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.\\nالموقع: {objectPath}"},"checker.maxLength":{"one":"يجب ألا يزيد طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.","two":"يجب ألا يزيد طول الحقل {field} في {object} عن {system} {unit}؛ الطول الحالي هو {input_len}.","deep":"يجب ألا يزيد طول الحقل {field} عن {system} {unit}؛ الطول الحالي هو {input_len}.\\nالموقع: {objectPath}"},"checker.invalid":{"one":"الحقل {field} غير صالح.","two":"الحقل {field} في {object} غير صالح.","deep":"الحقل {field} غير صالح.\\nالموقع: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} رقم {position}","separator":" → "}},"th":{"rules":{"checker.required":{"one":"ต้องระบุ{field}","two":"ต้องระบุ{field}ของ{object}","deep":"ต้องระบุ{field}\\nตำแหน่ง: {objectPath}"},"checker.min":{"one":"{field}ต้องมีค่าอย่างน้อย {system}","two":"{field}ของ{object}ต้องมีค่าอย่างน้อย {system}","deep":"{field}ต้องมีค่าอย่างน้อย {system}\\nตำแหน่ง: {objectPath}"},"checker.max":{"one":"{field}ต้องมีค่าไม่เกิน {system}","two":"{field}ของ{object}ต้องมีค่าไม่เกิน {system}","deep":"{field}ต้องมีค่าไม่เกิน {system}\\nตำแหน่ง: {objectPath}"},"checker.minLength":{"one":"{field}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}","two":"{field}ของ{object}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}","deep":"{field}ต้องมีความยาวอย่างน้อย {system} {unit} ความยาวปัจจุบันคือ {input_len}\\nตำแหน่ง: {objectPath}"},"checker.maxLength":{"one":"{field}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}","two":"{field}ของ{object}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}","deep":"{field}ต้องมีความยาวไม่เกิน {system} {unit} ความยาวปัจจุบันคือ {input_len}\\nตำแหน่ง: {objectPath}"},"checker.invalid":{"one":"{field}ไม่ถูกต้อง","two":"{field}ของ{object}ไม่ถูกต้อง","deep":"{field}ไม่ถูกต้อง\\nตำแหน่ง: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation}ลำดับที่ {position}","separator":" → "}},"id":{"rules":{"checker.required":{"one":"Kolom {field} wajib diisi.","two":"Kolom {field} pada {object} wajib diisi.","deep":"Kolom {field} wajib diisi.\\nLokasi: {objectPath}"},"checker.min":{"one":"Nilai {field} minimal {system}.","two":"Nilai {field} pada {object} minimal {system}.","deep":"Nilai {field} minimal {system}.\\nLokasi: {objectPath}"},"checker.max":{"one":"Nilai {field} maksimal {system}.","two":"Nilai {field} pada {object} maksimal {system}.","deep":"Nilai {field} maksimal {system}.\\nLokasi: {objectPath}"},"checker.minLength":{"one":"Panjang {field} minimal {system} {unit}; panjang saat ini {input_len}.","two":"Panjang {field} pada {object} minimal {system} {unit}; panjang saat ini {input_len}.","deep":"Panjang {field} minimal {system} {unit}; panjang saat ini {input_len}.\\nLokasi: {objectPath}"},"checker.maxLength":{"one":"Panjang {field} maksimal {system} {unit}; panjang saat ini {input_len}.","two":"Panjang {field} pada {object} maksimal {system} {unit}; panjang saat ini {input_len}.","deep":"Panjang {field} maksimal {system} {unit}; panjang saat ini {input_len}.\\nLokasi: {objectPath}"},"checker.invalid":{"one":"Kolom {field} tidak valid.","two":"Kolom {field} pada {object} tidak valid.","deep":"Kolom {field} tidak valid.\\nLokasi: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} ke-{position}","separator":" → "}},"fil":{"rules":{"checker.required":{"one":"Kinakailangan ang {field}.","two":"Kinakailangan ang {field} ng {object}.","deep":"Kinakailangan ang {field}.\\nLokasyon: {objectPath}"},"checker.min":{"one":"Ang {field} ay dapat hindi bababa sa {system}.","two":"Ang {field} ng {object} ay dapat hindi bababa sa {system}.","deep":"Ang {field} ay dapat hindi bababa sa {system}.\\nLokasyon: {objectPath}"},"checker.max":{"one":"Ang {field} ay dapat hindi lumampas sa {system}.","two":"Ang {field} ng {object} ay dapat hindi lumampas sa {system}.","deep":"Ang {field} ay dapat hindi lumampas sa {system}.\\nLokasyon: {objectPath}"},"checker.minLength":{"one":"Ang {field} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","two":"Ang {field} ng {object} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","deep":"Ang {field} ay dapat may hindi bababa sa {system} {unit}; ang kasalukuyang haba ay {input_len}.\\nLokasyon: {objectPath}"},"checker.maxLength":{"one":"Ang {field} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","two":"Ang {field} ng {object} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.","deep":"Ang {field} ay dapat may hindi hihigit sa {system} {unit}; ang kasalukuyang haba ay {input_len}.\\nLokasyon: {objectPath}"},"checker.invalid":{"one":"Hindi wasto ang {field}.","two":"Hindi wasto ang {field} ng {object}.","deep":"Hindi wasto ang {field}.\\nLokasyon: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} bilang {position}","separator":" → "}},"uk":{"rules":{"checker.required":{"one":"Поле {field} є обов’язковим.","two":"Поле {field} для {object} є обов’язковим.","deep":"Поле {field} є обов’язковим.\\nРозташування: {objectPath}"},"checker.min":{"one":"Значення поля {field} має бути не менше {system}.","two":"Значення поля {field} для {object} має бути не менше {system}.","deep":"Значення поля {field} має бути не менше {system}.\\nРозташування: {objectPath}"},"checker.max":{"one":"Значення поля {field} має бути не більше {system}.","two":"Значення поля {field} для {object} має бути не більше {system}.","deep":"Значення поля {field} має бути не більше {system}.\\nРозташування: {objectPath}"},"checker.minLength":{"one":"Поле {field} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.","two":"Поле {field} для {object} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.","deep":"Поле {field} має містити щонайменше {system} {unit}; поточна довжина — {input_len}.\\nРозташування: {objectPath}"},"checker.maxLength":{"one":"Поле {field} має містити не більше {system} {unit}; поточна довжина — {input_len}.","two":"Поле {field} для {object} має містити не більше {system} {unit}; поточна довжина — {input_len}.","deep":"Поле {field} має містити не більше {system} {unit}; поточна довжина — {input_len}.\\nРозташування: {objectPath}"},"checker.invalid":{"one":"Поле {field} є недійсним.","two":"Поле {field} для {object} є недійсним.","deep":"Поле {field} є недійсним.\\nРозташування: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} № {position}","separator":" → "}},"vi":{"rules":{"checker.required":{"one":"Trường {field} là bắt buộc.","two":"Trường {field} của {object} là bắt buộc.","deep":"Trường {field} là bắt buộc.\\nVị trí: {objectPath}"},"checker.min":{"one":"Giá trị {field} phải ít nhất là {system}.","two":"Giá trị {field} của {object} phải ít nhất là {system}.","deep":"Giá trị {field} phải ít nhất là {system}.\\nVị trí: {objectPath}"},"checker.max":{"one":"Giá trị {field} không được vượt quá {system}.","two":"Giá trị {field} của {object} không được vượt quá {system}.","deep":"Giá trị {field} không được vượt quá {system}.\\nVị trí: {objectPath}"},"checker.minLength":{"one":"Độ dài {field} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.","two":"Độ dài {field} của {object} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.","deep":"Độ dài {field} phải ít nhất là {system} {unit}; độ dài hiện tại là {input_len}.\\nVị trí: {objectPath}"},"checker.maxLength":{"one":"Độ dài {field} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.","two":"Độ dài {field} của {object} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.","deep":"Độ dài {field} không được vượt quá {system} {unit}; độ dài hiện tại là {input_len}.\\nVị trí: {objectPath}"},"checker.invalid":{"one":"Trường {field} không hợp lệ.","two":"Trường {field} của {object} không hợp lệ.","deep":"Trường {field} không hợp lệ.\\nVị trí: {objectPath}"}},"locationPatterns":{"reference":"{relation}","item":"{relation} thứ {position}","separator":" → "}}}'),xn={schema:Cn,defaultLocale:$n,locales:Nn},Ei=new WeakMap;function Oi(n,e){const t=Object.freeze({locale:n,render:(i,r)=>Et(e,i,r)});return Ei.set(t,e),t}function ji(n,e){const t=Ei.get(n);return t?Oi(n.locale,Object.freeze(t.map(i=>typeof i=="string"?e(i):i))):P()}const P=()=>{throw new TypeError("Invalid Checker message catalog")},qn=(n,e)=>Object.prototype.hasOwnProperty.call(n,e);function Q(n){return!n||typeof n!="object"||Array.isArray(n)?P():n}function se(n){return typeof n!="string"||!n.trim()?P():n}function ve(n,e){Object.keys(n).some(t=>!e.includes(t))&&P()}function ki(n){if(typeof n!="string")return P();let e=0;const t=()=>{for(;/[\t\n\r ]/.test(n[e]??"x");)e++};function i(){if(n[e]!=='"')return P();const s=e++;for(;e!o.has(a))?P():Object.freeze(r)}function Et(n,e,t){return n.map(i=>typeof i=="string"?t?t(i):i:e[i.argument]??"-").join("")}function Mn(n){const e=n%100n,t=e>=11n&&e<=13n?"th":n%10n===1n?"st":n%10n===2n?"nd":n%10n===3n?"rd":"th";return String(n)+t}var ne,ze;const K=class K{constructor(e,t){Pe(this,ne);Pe(this,ze);_e(this,ne,e),_e(this,ze,t),Object.freeze(this)}static fromJson(e){return this.parse(e,!1)}static parse(e,t){const i=Q(ki(e));if(ve(i,["schema","defaultLocale","locales"]),i.schema!=="teaql.checker-messages/v1"||i.defaultLocale!=="en")return P();const r=Object.create(null);for(const[o,s]of Object.entries(Q(i.locales))){const a=ke(o);if(qn(r,a))return P();const c=Q(s);ve(c,["rules","locationPatterns"]);const u=Object.create(null);for(const[d,h]of Object.entries(c.rules===void 0?{}:Q(c.rules))){if(!d.startsWith("checker.")||d.length===8)return P();const f=Object.create(null);for(const[p,m]of Object.entries(Q(h))){if(!["one","two","deep"].includes(p))return P();let b=["field","system","input","input_len","unit"];const g=["field"];if(["checker.required","checker.invalid"].includes(d)?b=["field"]:["checker.min","checker.max"].includes(d)?(b=["field","system","input"],g.push("system")):["checker.minLength","checker.maxLength"].includes(d)&&(b=["field","system","input_len","unit"],g.push("system","input_len","unit")),p!=="one"){const y=p==="two"?"object":"objectPath";b.push(y),g.push(y)}f[p]=ut(m,b,g)}u[d]=Object.freeze(f)}let l;if(c.locationPatterns!==void 0){const d=Q(c.locationPatterns);ve(d,["reference","item","separator"]);const h=ut(d.reference,["relation"],["relation"]),f=ut(d.item,["relation","position","ordinal","classifier"],["relation"]);if(!f.some(m=>typeof m!="string"&&["position","ordinal"].includes(m.argument)))return P();const p=se(d.separator);if(/[{}\r\n\u0000-\u001f\u007f-\u009f]/u.test(p))return P();l=Object.freeze({reference:h,item:f,separator:p})}r[a]=Object.freeze({rules:Object.freeze(u),patterns:l})}if(t)for(const o of pe){const s=r[o];if(!s?.patterns)return P();for(const a of["checker.required","checker.min","checker.max","checker.minLength","checker.maxLength","checker.invalid"])for(const c of["one","two","deep"])if(!s.rules[a]?.[c])return P()}return new K(Object.freeze(r),!t)}lookup(e,t,i){const r=x(this,ne)[e]?.rules[t]?.[i];return r&&Oi(e,r)}override(e,t,i){return x(this,ze)?this.lookup(e,t,i):void 0}select(e,t,i){for(const r of[e,"en"]){const o=this.lookup(r,t,i)??K.builtin.lookup(r,t,i);if(o)return o}return K.builtin.lookup(e,"checker.invalid",i)}patterns(e){return x(this,ne)[e]?.patterns??x(K.builtin,ne)[e].patterns}projectPatterns(e,t){const i=x(this,ne)[e]?.patterns;if(this===K.builtin||!i)return K.builtin;const r=o=>Object.freeze(o.map(s=>typeof s=="string"?t(s):s));return new K(Object.freeze({[e]:Object.freeze({rules:Object.freeze({}),patterns:Object.freeze({reference:r(i.reference),item:r(i.item),separator:t(i.separator)})})}),!1)}reference(e,t){return Et(this.patterns(e).reference,{relation:t})}item(e,t,i,r){if(!Number.isSafeInteger(i)||i<0)return P();const o=BigInt(i)+1n;return Et(this.patterns(e).item,{relation:t,position:String(o),ordinal:Mn(o),classifier:r})}separator(e){return this.patterns(e).separator}};ne=new WeakMap,ze=new WeakMap,K.builtin=K.parse(JSON.stringify(xn),!0);let oe=K;const Dn={en:{currentObject:"current object",utf16:"UTF-16 code units",scalar:"Unicode scalar values",byte:"bytes"},"zh-CN":{currentObject:"当前对象",utf16:"个 UTF-16 代码单元",scalar:"个 Unicode 标量值",byte:"字节"},"zh-TW":{currentObject:"目前物件",utf16:"個 UTF-16 程式碼單元",scalar:"個 Unicode 純量值",byte:"位元組"},ja:{currentObject:"現在のオブジェクト",utf16:"UTF-16コード単位",scalar:"Unicodeスカラー値",byte:"バイト"},ko:{currentObject:"현재 객체",utf16:"UTF-16 코드 단위",scalar:"유니코드 스칼라 값",byte:"바이트"},de:{currentObject:"aktuelles Objekt",utf16:"UTF-16-Codeeinheiten",scalar:"Unicode-Skalarwerte",byte:"Bytes"},fr:{currentObject:"objet actuel",utf16:"unités de code UTF-16",scalar:"valeurs scalaires Unicode",byte:"octets"},es:{currentObject:"objeto actual",utf16:"unidades de código UTF-16",scalar:"valores escalares Unicode",byte:"bytes"},pt:{currentObject:"objeto atual",utf16:"unidades de código UTF-16",scalar:"valores escalares Unicode",byte:"bytes"},ar:{currentObject:"الكائن الحالي",utf16:"وحدات ترميز UTF-16",scalar:"قيم Unicode القياسية",byte:"بايت"},th:{currentObject:"ออบเจ็กต์ปัจจุบัน",utf16:"หน่วยรหัส UTF-16",scalar:"ค่าสเกลาร์ Unicode",byte:"ไบต์"},id:{currentObject:"objek saat ini",utf16:"unit kode UTF-16",scalar:"nilai skalar Unicode",byte:"bita"},fil:{currentObject:"kasalukuyang bagay",utf16:"yunit ng code na UTF-16",scalar:"scalar na halaga ng Unicode",byte:"byte"},uk:{currentObject:"поточний об’єкт",utf16:"кодових одиниць UTF-16",scalar:"скалярних значень Unicode",byte:"байтів"},vi:{currentObject:"đối tượng hiện tại",utf16:"đơn vị mã UTF-16",scalar:"giá trị vô hướng Unicode",byte:"byte"}},Fn={locales:Dn},Se=()=>{throw new TypeError("Invalid Checker presentation metadata")};function Ze(n){return n.replace(/[\p{Cc}\p{Cf}\u2028\u2029]/gu," ").trim()}function Qe(n){const e=Object.create(null);for(const[t,i]of Object.entries(Q(n))){const r=ke(t);if(Object.prototype.hasOwnProperty.call(e,r))return Se();e[r]=se(i)}return Object.freeze(e)}const Te=Fn.locales;for(const n of pe){for(const e of Object.values(Te[n]))(!e||Ze(e)!==e)&&Se();Object.freeze(Te[n])}Object.freeze(Te);function zn(n,e){return Te[n][e]}class Vn{#e;constructor(e){const t=Q(e);if(ve(t,["labels","fields"]),this.labels=Qe(t.labels??{}),!Array.isArray(t.fields))throw new TypeError("Invalid Checker presentation fields");const i=new Map,r=[];for(const s of t.fields){const a=Q(s);ve(a,["name","targetType","labels","classifiers","aliases"]);const c=se(a.name),u=a.targetType===void 0?void 0:se(a.targetType);if(a.aliases!==void 0&&!Array.isArray(a.aliases))throw new TypeError("Invalid Checker presentation aliases");const l=Object.freeze((a.aliases??[]).map(se)),d=Object.freeze({name:c,targetType:u,labels:Qe(a.labels??{}),classifiers:Qe(a.classifiers??{}),aliases:l});for(const h of[c,...l]){if(i.has(h))throw new TypeError("Ambiguous Checker presentation identity");i.set(h,d)}r.push(d)}this.#e=i;const o=s=>Object.entries(s).sort(([a],[c])=>a.localeCompare(c));this.fingerprint=JSON.stringify([o(this.labels),r.sort((s,a)=>s.name.localeCompare(a.name)).map(s=>[s.name,s.targetType,o(s.labels),o(s.classifiers),[...s.aliases].sort()])]),Object.freeze(this)}field(e){return this.#e.get(e)}}var de,Z;const ie=class ie{constructor(e,t,i){Pe(this,de);Pe(this,Z);this.revision=e,_e(this,de,t),_e(this,Z,i),Object.freeze(this)}static fromJson(e){const t=Q(ki(e));if(ve(t,["schema","revision","entities","currentObject"]),t.schema!=="teaql.checker-model/v1")return Se();const i=se(t.revision),r=new Map;for(const[o,s]of Object.entries(Q(t.entities)))se(o),r.set(o,new Vn(s));return new ie(i,r,Object.freeze({...x(this.empty,Z),...Qe(t.currentObject??{})}))}entity(e){return e===void 0?void 0:x(this,de).get(e)}currentLabels(){return x(this,Z)}merge(e){if(this===ie.empty)return e;if(e===ie.empty||this===e)return this;const t=new Map(x(this,de));let i=!1;for(const[r,o]of x(e,de)){const s=t.get(r);if(s&&s.fingerprint!==o.fingerprint)return Se();s||(t.set(r,o),i=!0)}for(const r of pe)if(x(this,Z)[r]!==x(e,Z)[r])return Se();return i?new ie(this.revision+"+"+e.revision,t,x(this,Z)):this}};de=new WeakMap,Z=new WeakMap,ie.empty=new ie("unconfigured",new Map,Object.freeze(Object.fromEntries(pe.map(e=>[e,Te[e].currentObject]))));let te=ie;class Le{constructor(e,t,i,r){this.model=e,this.origin=t,this.shape=i,this.#e=r,Object.freeze(this)}#e;static capture(e,t,i){let r=e.entity(t),o=!r;const s=[];for(const c of i.segments)if(c.kind==="property"){const u=r?.field(c.name);r=e.entity(u?.targetType),s.push({identity:c.name,field:u,indices:[]})}else{if(!Number.isSafeInteger(c.index)||c.index<0)return Se();s.length||(s.push({indices:[]}),o=!0);const u=s[s.length-1];u.indices.push(c.index),u.indices.length>1&&(o=!0)}(!s.length||s[s.length-1].indices.length)&&(o=!0);const a=o||s.length>2?"deep":s.length===1?"one":"two";return new Le(e,t,a,Object.freeze(s.map(c=>Object.freeze({...c,indices:Object.freeze(c.indices)}))))}relocate(e){return Le.capture(this.model,this.origin,e)}render(e,t,i){const r=new Set,o=t.locale,s=(m,b)=>{let g=m[o];g?.trim()||(r.add("CHECKER_MESSAGE_LABEL_FALLBACK"),g=m.en);const y=Ze(g?.trim()?g:b.replace(/_/g," "));return y||(r.add("CHECKER_MESSAGE_LABEL_FALLBACK"),Te[o].currentObject)},a=()=>s(this.model.currentLabels(),"current object"),c=this.model.entity(this.origin),u=c?s(c.labels,this.origin):a(),l=m=>s(m.field?.labels??{},m.field?.name??m.identity??"current object"),d=this.#e[this.#e.length-1],h=Object.fromEntries(["system","input","input_len","unit"].filter(m=>Object.prototype.hasOwnProperty.call(i,m)).map(m=>[m,i[m]]));h.field=d?.identity?l(d):u;const f=this.#e.length-(d?.identity&&!d.indices.length?1:0),p=[];for(const m of this.#e.slice(0,f)){const b=m.identity?l(m):u;if(!m.indices.length)p.push(e.reference(o,b));else for(let g=0;gn.presentation.render(n.catalog,n.selection,n.arguments),Li=Symbol("TeaQL.NaturalCheckerPresentation"),Ii=new WeakMap,At=n=>{const e=n[Li];return e&&Ii.get(e)};function Pi(n,e,t,i){const r=Object.freeze({});Ii.set(r,Object.freeze({presentation:e,automaticMessage:t,plan:i})),Object.defineProperty(n,Li,{value:r,enumerable:!0,configurable:!0})}function Ot(n){const e=At(n);return e?.automaticMessage!==void 0&&e.automaticMessage===n.message||Ln(n)}function _i(n,e){return n.map(t=>{const i={...t},r=Ot(t);return Pi(i,Le.capture(e.model,e.entity,t.location),r?t.message:void 0,r?At(t)?.plan:void 0),i})}const Un=Object.freeze({required:"checker.required",min:"checker.min",max:"checker.max",min_str_len:"checker.minLength",min_length:"checker.minLength",max_str_len:"checker.maxLength",max_length:"checker.maxLength"});function Bt(n){return n===null?"null":n===void 0?"undefined":typeof n=="string"?Ze(n):typeof n=="number"||typeof n=="bigint"||typeof n=="boolean"?String(n):n instanceof Date&&Object.getPrototypeOf(n)===Date.prototype&&Number.isFinite(n.getTime())?n.toISOString():"[value omitted]"}const Bn=["CHECKER_MESSAGE_LABEL_FALLBACK","CHECKER_MESSAGE_GENERIC_RULE","CHECKER_MESSAGE_RENDER_FALLBACK"];function Kn(n,e,t){const i=s=>Je(e,s),r=new Map,o=Object.fromEntries(pe.map(s=>[s,Object.freeze(Object.fromEntries(["one","two","deep"].map(a=>{let c,u,l=!1;for(const f of[s,"en"]){if(c=n.catalog.override(f,t,a),c){l=!0;break}const p=n.legacy.applicationMessage(f,t);if(p!==void 0){u=Object.freeze(p.split(/(\{(?:location|system|input|input_len)\})/g).map(m=>/^\{(?:location|system|input|input_len)\}$/.test(m)?Object.freeze({argument:m.slice(1,-1)}):i(m)));break}if(c=oe.builtin.lookup(f,t,a),c)break}const d=!c&&!u;d&&(c=oe.builtin.select(s,"checker.invalid",a)),c&&l&&(c=ji(c,i));const h=c?.locale??s;return r.has(h)||r.set(h,n.catalog.projectPatterns(h,i)),[a,Object.freeze({selection:c,legacy:u,catalog:r.get(h),generic:d,application:l})]})))]));return Object.freeze({locales:Object.freeze(o)})}function Qn(n,e){if(n.literal!==void 0)return Object.freeze({literal:e(n.literal)});const t={};for(const i of pe){const r={};for(const o of["one","two","deep"]){const s=n.locales[i][o];r[o]=Object.freeze({...s,selection:s.application&&s.selection?ji(s.selection,e):s.selection,legacy:s.legacy&&Object.freeze(s.legacy.map(a=>typeof a=="string"?e(a):a)),catalog:s.catalog.projectPatterns(s.selection?.locale??i,e)})}t[i]=Object.freeze(r)}return Object.freeze({locales:Object.freeze(t)})}function Ai(n,e){return Object.freeze({system:Bt(n.systemValue),input:Bt(n.inputValue),input_len:String(wi(n)),unit:zn(e,"scalar")})}function Kt(n,e,t,i){if(n.literal!==void 0)return Object.freeze({message:n.literal,warnings:Object.freeze([])});const r=n.locales[i][e.shape],o=Ai(t,r.selection?.locale??i);if(r.legacy){const a={...o,location:t.location.nativePath()};return Object.freeze({message:r.legacy.map(c=>typeof c=="string"?c:a[c.argument]??"-").join(""),warnings:Object.freeze([])})}const s=e.render(r.catalog,r.selection,o);return r.generic?Object.freeze({...s,warnings:Object.freeze([...s.warnings,"CHECKER_MESSAGE_GENERIC_RULE"])}):s}function Qt(n,e,t=new Set,i){if(e.message?.trim()&&!Ot(e))return e;const r=h=>{const f=Bn.includes(h)?h:"CHECKER_MESSAGE_RENDER_FALLBACK";if(!t.has(f)){t.add(f);try{n.warning(f)}catch{}}},o=At(e),s=i?.model??o?.presentation.model??n.model,a=i?.entity??o?.presentation.origin;let c;try{c=Le.capture(s,a,e.location)}catch{r("CHECKER_MESSAGE_RENDER_FALLBACK"),c=Le.capture(te.empty,void 0,F.root())}const u=Un[e.ruleId.toLowerCase()]??`checker.${e.ruleId.toLowerCase()}`,l=ke(n.locale);let d=Ot(e)?o?.plan:void 0;d&&(d=Qn(d,h=>Je(e,h)));try{let h;if(d)h=Kt(d,c,e,l);else{d=Kn(n,e,u);const f=d.locales[l][c.shape];if(n.renderer===Ti||f.legacy)h=Kt(d,c,e,l);else{const p=Object.freeze({presentation:c,catalog:f.catalog,selection:f.selection,arguments:Ai(e,f.selection.locale)}),m=n.renderer(p);h=Object.freeze({...m,message:Je(e,m.message)}),d=Object.freeze({literal:h.message})}}if(!h||typeof h.message!="string"||!h.message.trim())throw new Error("Empty rendered message");for(const f of h.warnings)r(f);e.message=h.message}catch{r("CHECKER_MESSAGE_RENDER_FALLBACK");const h=c.render(oe.builtin,oe.builtin.select(l,"checker.invalid",c.shape),{});e.message=h.message;for(const f of h.warnings)r(f);d=Object.freeze({literal:e.message})}return Pi(e,c,e.message,d),vi(e),e}class Gn{constructor(e,t,i={}){this.entity=e,this.#e=new Set(t),this.#t=Object.freeze({...i}),Object.freeze(this)}#e;#t;validate(e,t=!1){const i=Object.keys(e).flatMap(r=>{const o=this.#e.has(r)?t&&Object.prototype.hasOwnProperty.call(this.#t,r)?this.#t[r]:void 0:"unknown_field";return o?[{ruleId:o,location:F.property(r),message:o==="unknown_field"?"Expected a canonical model field name":"Field is immutable after create"}]:[]});if(i.length)throw new G(i)}}var Wn={};class V extends Error{constructor(){super("Runtime logging initialization failed"),this.name="RuntimeLoggingError"}}const Ri=new TextEncoder,Gt=new Map,Hn=["TEAQL_DOMAIN","TEAQL_LOG_ENDPOINT","TEAQL_LOG_MAX_SIZE","TEAQL_LOG_MAX_FILES","TEAQL_LOG_FORMAT"],Ci=new Set(["timestamp","level","log_name","runtime","event","message"]),Xn=/^\d{4}-\d\d-\d\dT\S+(?:Z|\+00:00) \[TeaQL\]\[.*\]\[(?:INFO|WARN|ERROR)\] .+ runtime=\S+$/u;function $i(){return typeof process<"u"&&!!process.versions?.node&&!(typeof window<"u"&&typeof window.document<"u")}function Ni(){const n=typeof require=="function"?require:typeof process<"u"&&typeof process.getBuiltinModule=="function"?e=>process.getBuiltinModule(e):void 0;if(!n)throw new V;return{fs:n("node:fs"),path:n("node:path"),url:n("node:url")}}function xi(){const n={};for(const e of Hn)n[e]=Wn[e];return n}function Yn(n){return typeof n=="string"&&n.length>0&&n!=="."&&n!==".."&&!/[<>:"/\\|?*\u0000-\u001f\u007f]/u.test(n)&&!/[. ]$/u.test(n)&&!/^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\.|$)/iu.test(n)&&!/[\uD800-\uDFFF]/u.test(n)&&Ri.encode(n).byteLength<=255}function Jn(n){const e=/^([0-9]+)\s*(K|KB|M|MB|G|GB)?$/u.exec(n.trim().toUpperCase());if(!e)throw new V;const t={K:1024n,KB:1024n,M:1048576n,MB:1048576n,G:1073741824n,GB:1073741824n}[e[2]]??1n,i=BigInt(e[1])*t;if(i<=0n||i>9223372036854775807n)throw new V;return i}function Me(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?t.toString():t)}function le(n,e){return n.replace(/[\\\u0000-\u001f\u007f-\u009f\u2028\u2029\ud800-\udfff]/gu,t=>t==="\\"?e?"\\\\":t:"\\u"+t.charCodeAt(0).toString(16).padStart(4,"0"))}function qi(n){return`[TeaQL][${le(n.log_name,!0)}][${n.level}] ${le(n.event,!0)}`}function Wt(n){let e=`${le(n.timestamp,!0)} ${qi(n)} runtime=${n.runtime} + ${le(n.message,!0)} +`;for(const t of Object.keys(n).filter(i=>!Ci.has(i)).sort()){const i=n[t];t==="sql"&&typeof i=="string"?e+=` sql: +`+i.split(` +`).map(r=>" "+le(r,!0)+` +`).join(""):e+=" "+le(t,!0)+"="+le(Me(i),!1)+` +`}return e}function Ht(n,e,t){const i={timestamp:new Date().toISOString(),level:"ERROR",log_name:n,runtime:"typescript",event:"logging.failure",message:"Runtime logging failed",error_code:e};try{t?Ni().fs.writeSync(2,Me(i)+` +`):console.error(`[TeaQL][${n}][ERROR] logging.failure`,i)}catch{}}class Zn{constructor(e={}){this.server=e.platform==="server"||e.platform!=="browser"&&$i();let t="teaql";try{const i=this.server?e.environment??xi():{},r=e.logName!==void 0?e.logName:i.TEAQL_DOMAIN||(e.modelNames?.length===1?e.modelNames[0]:"teaql");if(!Yn(r))throw new V;this.logName=t=r;const o=e.logFormat!==void 0?e.logFormat:i.TEAQL_LOG_FORMAT??"json";if(o!=="json"&&o!=="human")throw new V;this.logFormat=o,this.maxSize=Jn(i.TEAQL_LOG_MAX_SIZE??"50M");const s=i.TEAQL_LOG_MAX_FILES??"7";if(!/^[0-9]+$/u.test(s)||BigInt(s)>2147483647n)throw new V;if(this.maxFiles=Number(s),this.server){this.native=Ni();const{fs:a,path:c,url:u}=this.native;let l=i.TEAQL_LOG_ENDPOINT||`./logs/${r}.log`;if(["stdout","stderr","-"].includes(l))this.stream=l;else{if(l.startsWith("file:")){const h=new URL(l);if(h.hostname&&h.hostname!=="localhost"||h.search||h.hash)throw new V;l=u.fileURLToPath(h)}else if(l.includes("://"))throw new V;let d=c.resolve(e.workingDirectory??process.cwd(),l);a.mkdirSync(c.dirname(d),{recursive:!0}),d=c.join(a.realpathSync(c.dirname(d)),c.basename(d));try{d=a.realpathSync(d)}catch(h){if(h.code!=="ENOENT")throw h}this.path=d}}this.emit(this.record("INFO","runtime.start","TeaQL runtime started",{}))}catch{throw Ht(t,"log_destination_unavailable",this.server),new V}}record(e,t,i,r){return Object.freeze({...r,timestamp:new Date().toISOString(),level:e,log_name:this.logName,runtime:"typescript",event:t,message:i})}write(e,t,i,r={}){try{if(!["INFO","WARN","ERROR"].includes(e))throw new Error;return this.emit(this.record(e,t,i,r)),!0}catch{return Ht(this.logName,"log_write_failed",this.server),!1}}archives(){const{fs:e,path:t}=this.native,i=t.basename(this.path)+".";return e.readdirSync(t.dirname(this.path)).filter(r=>r.startsWith(i)&&/^[1-9][0-9]*$/u.test(r.slice(i.length))).map(r=>{const o=Number(r.slice(i.length)),s=t.join(t.dirname(this.path),r);if(!Number.isSafeInteger(o)||!e.lstatSync(s).isFile())throw new Error;return{number:o,path:s}}).sort((r,o)=>o.number-r.number)}emit(e){if(!this.server){const c=e.level==="WARN"?"warn":e.level==="ERROR"?"error":"info";console[c](this.logFormat==="human"?Wt(JSON.parse(Me(e))):qi(e),e);return}const{fs:t}=this.native,i=Me(e),r=Ri.encode(this.logFormat==="human"?Wt(JSON.parse(i)):i+` +`);if(this.stream){t.writeSync(this.stream==="stderr"?2:1,r);return}const o=this.path+".lock",s=Date.now()+3e4;let a;for(;;)try{a=t.openSync(o,"wx",384);break}catch(c){if(c.code!=="EEXIST"||Date.now()>=s)throw c;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,5)}try{this.checkPresentation();const c=this.archives();for(const d of c)d.number>this.maxFiles&&t.unlinkSync(d.path);let u;try{u=t.statSync(this.path,{bigint:!0})}catch(d){if(d.code!=="ENOENT")throw d}if(u){if(!u.isFile())throw new Error;if(u.size>0n&&(u.size+BigInt(r.byteLength)>this.maxSize||u.mtime.toISOString().slice(0,10)!==new Date().toISOString().slice(0,10))){for(const d of c.filter(h=>h.number<=this.maxFiles))d.number===this.maxFiles?t.unlinkSync(d.path):t.renameSync(d.path,this.path+"."+(d.number+1));this.maxFiles===0?t.unlinkSync(this.path):t.renameSync(this.path,this.path+".1")}}const l=t.openSync(this.path,"a",384);try{let d=0;for(;d=0)break}const a=new Uint8Array(s);let c=0;for(const u of o)a.set(u,c),c+=u.length;r=new TextDecoder("utf-8",{fatal:!0}).decode(a)}finally{e.closeSync(i)}if(!(this.logFormat==="human"&&Xn.test(r))){if(this.logFormat==="json")try{const o=JSON.parse(r);if(o&&!Array.isArray(o)&&[...Ci].every(s=>typeof o[s]=="string")&&["INFO","WARN","ERROR"].includes(o.level))return}catch{}throw new V}}}function er(){const n=$i(),e=n?xi():{},t=n?process.cwd():"",i=Me([n,t,e]);let r=Gt.get(i);return r||(r=new Zn({environment:e,workingDirectory:t}),Gt.set(i,r)),r}function tr(n,e){return{start(t){const i=H(n,t);let r=!1;function o(s){if(r)return!1;r=!0;const a=s===void 0?void 0:s instanceof Error&&/^(CheckException|RequestIntentError|MutationIntentError)$/u.test(s.constructor.name)?"validation":s instanceof Error&&s.constructor.name==="MutationPolicyError"?"authorization":ln(s),c=s===void 0?"success":"failure",u=s===void 0?"INFO":["validation","authorization","conflict"].includes(a)?"WARN":"ERROR";return e.write(u,`operation.${c}`,`TeaQL operation ${c}`,{category:t.family.toUpperCase(),outcome:c,error_code:a,trace_id:i.correlation?.()?.traceId}),!0}return{...i,success(s){o()&&i.success(s)},failure(s){o(s)&&i.failure(s)}}},recordsSQLDiagnostics:()=>n?.recordsSQLDiagnostics?.()??!1,recordDiagnostic:t=>n?.recordDiagnostic?.(t),inject:t=>n?.inject?.(t),flush:()=>n?.flush?.(),shutdown:()=>n?.shutdown?.()}}class ir{now(){return new Date}}class U extends Error{constructor(e){super(`Object storage: ${e}`),this.code=e,this.name="StorageError"}}const Mi=Symbol.for("nodejs.util.inspect.custom"),De=()=>{throw new U("InvalidInput")};function nr(n){return(typeof n!="string"||!n||/[^\x20-\x7e]/.test(n))&&De(),n}class rr{#e;#t;constructor(e=300,t,i){(!Number.isInteger(e)||e<=0||e>604800||t!==void 0&&!["inline","attachment"].includes(t))&&De(),i!==void 0&&(nr(i),(!t||/[\/\\"]/.test(i))&&De()),this.#e=e,this.#t=t+(i===void 0?"":`; filename="${i}"`),t===void 0&&(this.#t=void 0)}get seconds(){return this.#e}get contentDisposition(){return this.#t}toString(){return"ObjectReadUrlOptions[details=masked]"}[Mi](){return this.toString()}}function Xt(n){return n instanceof U?n:new U("Unavailable")}const Yt=n=>String(n??"").replace(/[\x00-\x1f\x7f-\x9f]/g," ");class Jt{constructor(e,t){this.invocation=e,this.operation=t,this.scope=H(e.context.getResource("runtimeTelemetry"),{family:"object_storage",name:t})}#e=!1;#t=performance.now();finish(e){if(this.#e)return;this.#e=!0,e==="success"?this.scope.success():this.scope.failure(new U(e==="cancelled"?"Io":e));const t=Object.freeze({operation:this.operation,comment:Yt(this.invocation.comment),traceId:Yt(this.invocation.context.getResource("traceId")),outcome:e,elapsedMs:performance.now()-this.#t});try{const i=this.invocation.context.getResource("objectStorageObserver");i?i(t):console.info(`ObjectStorage operation=${t.operation} comment=${t.comment} trace=${t.traceId} outcome=${t.outcome} elapsedMs=${t.elapsedMs.toFixed(3)}`)}catch{}}}class sr{#e;#t;#n;constructor(e,t,i){this.#e=e,this.#t=t,this.#n=i}get metadata(){return this.#e}get stream(){return this.#t}close(){return this.#n()}toString(){return"ObjectContent[masked]"}[Mi](){return this.toString()}}class or{#e;#t;constructor(e,t){(typeof t!="string"||!t.trim())&&De();const i=e.getResource("objectStorageProvider");if(!i)throw new U("NotConfigured");this.#e=Object.freeze({context:e,comment:t}),this.#t=i}async#n(e,t){const i=new Jt(this.#e,e);try{const r=await(i.scope.run?i.scope.run(t):t());return i.finish("success"),r}catch(r){const o=Xt(r);throw i.finish(o.code),o}}async put(e,t,i){const r=t[Symbol.asyncIterator]();let o=!1;const s={next:async()=>{const a=await r.next();return a.done&&(o=!0),a},return:async()=>(o||(o=!0,await r.return?.()),{done:!0,value:void 0}),[Symbol.asyncIterator](){return this}};return this.#n("put",async()=>{try{return await this.#t.put(this.#e,e,s,i)}finally{await s.return()}})}async putBytes(e,t,i){return this.put(e,(async function*(){yield t})(),i)}async get(e){const t=new Jt(this.#e,"get");let i;try{i=await(t.scope.run?t.scope.run(()=>this.#t.get(this.#e,e)):this.#t.get(this.#e,e))}catch(c){const u=Xt(c);throw t.finish(u.code),u}let r=!1,o=!1;const s=async()=>{if(!r){r=!0;try{await i.close(),t.finish("cancelled")}catch{throw t.finish("Io"),new U("Io")}}},a={[Symbol.asyncIterator]:async function*(){if(o||r)throw new U("Io");o=!0;let c=i.metadata.size;try{for await(const u of i.stream){if(!(u instanceof Uint8Array)||u.byteLength>c)throw new U("Io");c-=u.byteLength,yield u}if(c!==0)throw new U("Io");t.finish("success")}catch{throw t.finish("Io"),new U("Io")}finally{await s()}}};return new sr(i.metadata,a,s)}async getBytes(e,t){(!Number.isSafeInteger(t)||t<0)&&De();const i=await this.get(e);try{if(i.metadata.size>t)throw new U("TooLarge");const r=[];let o=0;for await(const c of i.stream){if(c.byteLength>t-o)throw new U("TooLarge");o+=c.byteLength,r.push(c)}const s=new Uint8Array(o);let a=0;for(const c of r)s.set(c,a),a+=c.byteLength;return s}finally{await i.close()}}head(e){return this.#n("head",()=>this.#t.head(this.#e,e))}async exists(e){return await this.head(e)!==void 0}delete(e){return this.#n("delete",()=>this.#t.delete(this.#e,e))}getReadUrl(e,t=new rr){return this.#n("read_url",()=>this.#t.getReadUrl(this.#e,e,t))}}function jt(n){if(typeof n=="number"&&(!Number.isSafeInteger(n)||n<=0))throw new RangeError("Internal ID must be a positive safe integer when supplied as a number");if(typeof n!="string"&&typeof n!="number"&&typeof n!="bigint")throw new TypeError("Internal ID must be an exact positive integer");const e=String(n);if(!/^[1-9][0-9]*$/.test(e))throw new TypeError("Internal ID must be a canonical positive integer");if(BigInt(e)>(1n<<63n)-1n)throw new RangeError("Internal ID exceeds signed 64-bit range");return e}const Di=Symbol("teaql.context.schema-capability");function ar(n,e,t,i){if(i&&!n.trim())throw new Error("Missing SQL template");let r=0;const o=new Set,s=u=>{if(u<0||u>=e.length)throw new Error("SQL bind count mismatch");return o.add(u),i?i(u):Fi(e[u],t)};let a="",c="sql";for(let u=0;u=0&&f=0&&ft.toString(16).padStart(2,"0")).join("")}'`:W(typeof n=="object"?JSON.stringify(n):String(n))}function W(n){return`'${n.replace(/'/g,"''")}'`}const Zt="[REDACTED]",dt="[REDACTED SQL; NOT REPLAYABLE]",cr=`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN +`,Ne=new WeakMap,kt=new WeakMap,zi=new WeakMap;function ei(n,e,t=[]){zi.set(n,{bindings:e?q(e):void 0,intentValues:Object.freeze(t.map(Fe))})}function et(n){const e=n.parameterLogPolicies,t=!!e&&e.length===n.parameters.length,i=fe(n.parameterizedSQL)&&(n.sqlOrigin!=="generated"||!t);return n.parameters.map((r,o)=>{if(i||ot(r))return"credential";const s=t?e[o]:void 0;return s==="plain"||s==="masked"||s==="credential"?s:"unknown"})}function Tt(n,e){return n==="credential"||n==="unknown"||!e&&n!=="plain"}function ti(n){if(!n)return[];const e=et(n);return n.parameters.flatMap((t,i)=>Tt(e[i],!1)?J(t):[])}function Fe(n){return n instanceof Date?new Date(n.getTime()):n instanceof Uint8Array?new Uint8Array(n):Array.isArray(n)?Object.freeze(n.map(Fe)):n&&typeof n=="object"?Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Fe(t)]))):n}function q(n,e){const t=e?[e,n]:[n];return Object.freeze({parameterizedSQL:"",sqlOrigin:"generated",parameters:Object.freeze(t.flatMap(i=>i.parameters.map(Fe))),parameterLogPolicies:Object.freeze(t.flatMap(et))})}function Vi(n,e,t=[]){const i=gi()&&n.logMode!=="masked",r=Ne.get(n);if(r!==void 0&&(!r||i))return n;const o=kt.get(n);if(!i&&o)return o;const s=tt(n,i,e,t);if(Ne.set(s,i),i){const a=tt(n,!1,e,t);Ne.set(a,!1),kt.set(s,a)}return s}function lr(n){const e=kt.get(n);if(e)return e;if(Ne.get(n)===!1)return n;const t=tt(n,!1);return Ne.set(t,!1),t}function tt(n,e,t,i=[]){const r=zi.get(n);r?.bindings&&(t=q(r.bindings,t)),r&&(i=[...i,...r.intentValues]);const o=n.parameterLogPolicies,s=!o||o.length===n.parameters.length,a=fe(n.parameterizedSQL)&&(n.sqlOrigin!=="generated"||!o||!s),c=et(n),u=c.map(E=>Tt(E,e)),l=n.parameters.flatMap((E,k)=>u[k]?J(E):[]);if(t){const E=et(t);l.push(...t.parameters.flatMap((k,j)=>Tt(E[j],e)?J(k):[]))}const d=[...l,...i.flatMap(J)],h=!e&&n.logMode==="debug-plaintext"&&!t,f=E=>h&&E?Zt:re(E,d),p=n.parameters.map((E,k)=>u[k]?c[k]==="masked"?Xe(E):Zt:Fe(E)),m=n.parameterizedSQL.replace(/\$[0-9]+|@p[0-9]+/gi,"?"),b=(!e||a)&&n.sqlOrigin!=="generated"&&/['"`$]|--|\/\*|\b\d+\b|:[A-Za-z_]/.test(m),g=n.databaseKind??"sqlite";let y=dt,O=b?"untrusted-literal-sql":s?void 0:"policy-count-mismatch";if(!b&&s)try{y=ar(n.parameterizedSQL,p,g,E=>Fi(p[E],g)+(u[E]?" /* masked */":"")),y=(e?u.some(Boolean)?`-- TeaQL DEBUG PLAINTEXT; EXPLICIT OPT-IN; PARTIALLY MASKED; NOT REPLAYABLE +`:cr:`-- TeaQL MASKED; NOT REPLAYABLE +`)+y}catch{y=dt,O="unsupported-or-mismatched-bindings"}return Object.freeze({...n,...n.statements?{statements:Object.freeze(n.statements.map(E=>tt(E,e,q(n,t),i)))}:{},parameterizedSQL:b?dt:n.sqlOrigin==="generated"?n.parameterizedSQL:re(n.parameterizedSQL,l),parameters:Object.freeze(p),parameterLogPolicies:Object.freeze(c),maskedParameters:Object.freeze(u),logMode:e?"debug-plaintext":"masked",omissionReason:O,debugSQL:y,comment:f(n.comment),purpose:f(n.purpose),auditReason:f(n.auditReason),...n.traceChain?{traceChain:Object.freeze(n.traceChain.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j])))))}:{},resultSummary:n.resultCount!==void 0?`${n.resultCount} rows returned`:n.affectedRows!==void 0?`${n.affectedRows} rows affected`:re(n.resultSummary,l),tracePath:Object.freeze(n.tracePath.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j]))))),...n.traceChain?{traceChain:Object.freeze(n.traceChain.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j])))))}:{},...n.mutationLineage?{mutationLineage:Object.freeze(n.mutationLineage.map(E=>Object.freeze(Object.fromEntries(Object.entries(E).map(([k,j])=>[k,k!=="entityId"&&typeof j=="string"?f(j):j])))))}:{}})}const ii="__teaql_prepared_reference",A=n=>`${n.entity}\0${typeof n.id}:${String(n.id)}`;class I extends G{constructor(e=""){super([{ruleId:"mutation_changed_after_preparation",location:e?F.property(e):F.root(),message:"Mutation differs from its prepared and reviewed state; prepare and review it again"}]),this.code="MUTATION_CHANGED_AFTER_PREPARATION",this.name="PreparedMutationError"}}class ur{constructor(){this.sources=[],this.objects=new WeakMap,this.tokens=new Map,this.entries=[],this.aliases=new Map,this.bindings=[],this.metadata=[],this.sealed=!1}get rootEntity(){return this.sources[0]?.key.entity??this.entries[0]?.key.entity}get size(){return this.entries.length}register(e,t,i,r,o){if(this.sealed)throw new I;if(this.objects.has(e))return;const s={object:e,token:Symbol("prepared entity"),root:t,key:{...i},origin:{...i},references:r,read:o};this.objects.set(e,s),this.tokens.set(s.token,s),this.sources.push(s)}members(e){return e.map(t=>{const i=this.objects.get(t);if(!i)throw new I;return i.token})}bind(e){this.bindings.push({read:e,value:e()})}bindMetadata(e){this.metadata.push({read:e,value:new $(e())})}captureInput(){for(const e of this.sources)e.native=new $(this.canonical(e.read(),e.references))}resolved(e){return this.aliases.get(A(e))??e}canonical(e,t){const i={...e};for(const[r,o]of Object.entries(t)){const s=i[r];if(!s||typeof s!="object")continue;const a=this.objects.get(s);if(a){if(a.key.entity!==o)throw new I(r);i[r]={[ii]:a.token}}else if(s.id!==void 0&&s.id!==null)i[r]=s.id;else throw new I(r)}return i}materialize(e,t=!1){return Object.fromEntries(Object.entries(e).map(([i,r])=>{const o=r&&typeof r=="object"?r[ii]:void 0;if(typeof o!="symbol")return[i,r];const s=this.tokens.get(o);if(!s)throw new I(i);const a=this.resolved(s.origin);if(!t&&!this.aliases.has(A(s.origin))&&s.root.isNew(s.key))throw new I(i);return[i,a.id]}))}difference(e,t){return new $(this.materialize(e.values(),!0)).changedField(this.materialize(t,!0))}rootState(e,t,i){return{values:new $(this.canonical(e.change(t),i)),version:e.originalVersion(t),fresh:e.isNew(t),deleted:e.isDeleted(t),trace:new $({trace:e.traceChain(t)})}}assertRoot(e,t,i,r){if(e.originalVersion(t)!==r.version)throw new I("version");if(e.isNew(t)!==r.fresh||e.isDeleted(t)!==r.deleted)throw new I;const o=this.difference(r.values,this.canonical(e.change(t),i));if(o!==void 0)throw new I(o);if(r.trace.changedField({trace:e.traceChain(t)})!==void 0)throw new I("comment")}assertNative(e){if(!e.native)throw new I;const t=this.difference(e.native,this.canonical(e.read(),e.references));if(t!==void 0)throw new I(t==="__teaql_comment"?"comment":t==="__teaql_key"?"id":t.startsWith("__teaql_")?"":t)}remember(e,t,i){if(this.sealed)throw new I;const r=t.ledgerRoot,o=t.ledgerKey??{entity:String(t.entity),id:t.id??Symbol("unassigned")};if(this.entries.some(c=>r&&c.root===r&&A(c.key)===A(o)))throw new I("id");const s=new $(this.canonical(t.payload??{},i)),a={request:e,root:r,key:{...o},mutation:{...t,payload:void 0},references:i,values:s,input:new $(this.canonical(e.mutation.payload??{},i)),loaded:new $(this.canonical(e.loadedValues(),i)),state:r?this.rootState(r,o,i):void 0,status:"prepared"};return this.entries.push(a),{...t,id:t.id??t.ledgerKey?.id,payload:this.materialize(s.values(),!0)}}normalizeRestored(e){if(this.sealed)throw new I;const t=e.ledgerRoot,i=e.ledgerKey;if(e.action!=="Update"||!t||!i)return;const r=this.sources.find(l=>l.root===t&&A(l.key)===A(i)),o=r?.object,s=o?.teaqlRestoreFixedValues;if(!r||typeof s!="function")return;const a=$.forEntity(r.object);let c;if(a?.discardRestoredFields(t,i,l=>{c=l}),!c)return;e.payload={...t.change(i)};const u=c;return{empty:!t.hasPending(i),restore:()=>{this.assertNative(r);const l=new $({...r.native.values(),...this.canonical(u,r.references)});s.call(o,N(u));const d=this.difference(l,this.canonical(r.read(),r.references));if(d!==void 0)throw new I(d);r.native=l}}}seal(){if(!this.sealed){for(const e of this.sources)this.assertNative(e);for(const e of this.entries)e.root&&e.state&&this.assertRoot(e.root,e.key,e.references,e.state);for(const e of this.sources)e.state=this.rootState(e.root,e.key,e.references);this.sealed=!0,this.validate()}}validate(){for(const e of this.bindings)if(e.read()!==e.value)throw new I("context");for(const e of this.metadata)if(e.value.changedField(e.read())!==void 0)throw new I("metadata");for(const e of this.sources)this.assertNative(e),e.state&&this.assertRoot(e.root,e.key,e.references,e.state);for(const e of this.entries)e.root&&e.state&&this.assertRoot(e.root,this.resolved(e.key),e.references,e.state)}entry(e){const t=e.mutation,i=this.entries.find(r=>r.request===e||t.ledgerRoot&&r.root===t.ledgerRoot&&t.ledgerKey&&A(this.resolved(r.key))===A(t.ledgerKey))??this.entries.find(r=>!r.root&&r.status==="prepared"&&r.mutation.entity===t.entity&&r.mutation.action===t.action&&r.mutation.id===t.id&&this.difference(r.root&&t.action==="Update"?r.values:r.input,this.canonical(t.payload??{},r.references))===void 0);if(!i)throw new I;return i}replay(e){if(!this.sealed)return;this.validate();const t=this.entry(e),i=e.mutation,r=t.mutation;if(t.status!=="prepared")throw new I;if(i.entity!==r.entity||i.action!==r.action)throw new I;if(i.id!==r.id)throw new I("id");if(i.action!=="Create"&&M(i.version!==void 0?i.version:i.expectedVersion)!==(r.version??r.expectedVersion))throw new I("version");if(e.comment!==r.comment)throw new I("comment");let o=this.difference(t.root&&i.action==="Update"?t.values:t.input,this.canonical(i.payload??{},t.references));if(o!==void 0)throw new I(o);if(o=this.difference(t.loaded,this.canonical(e.loadedValues(),t.references)),o!==void 0)throw new I(o);return{...r,ledgerKey:i.ledgerKey,ledgerRoot:i.ledgerRoot,payload:N(this.materialize(t.values.values()))}}providerResult(e,t){if(!this.sealed)return;this.validate();const i=this.entry(e);if(i.status!=="prepared")throw new I;i.result={id:t.id,version:t.version},i.status="executed",this.sources.some(r=>r.root===i.root&&A(r.key)===A(i.key))||(i.status="applied")}applied(e,t,i){if(!this.sealed)return;const r=this.entries.find(o=>o.root===e&&A(this.resolved(o.key))===A(t));if(!r||r.status!=="executed"||r.result?.id!==i.id||t.entity!==i.entity)throw new I("id");if(A(t)!==A(i)){if(r.mutation.action!=="Create"||this.aliases.has(A(r.key)))throw new I("id");this.aliases.set(A(r.key),{...i})}r.status="applied",r.state=this.rootState(e,i,r.references);for(const o of this.sources)o.root===e&&A(o.key)===A(t)&&(o.key={...i},o.native=new $(this.canonical(o.read(),o.references)),o.state=this.rootState(e,i,o.references))}committed(e,t){for(const i of this.entries)i.root===e&&A(this.resolved(i.key))===A(t)&&(i.status="committed",i.state=this.rootState(e,t,i.references));for(const i of this.sources)i.root===e&&A(i.key)===A(t)&&(i.state=this.rootState(e,t,i.references))}complete(){if(this.sealed&&(this.validate(),this.entries.some(e=>e.status!=="applied"&&e.status!=="committed")))throw new I}}const ni=new WeakMap,ht=new WeakMap,Lt=new WeakMap,Ui=new WeakMap;function Bi(n){if(!["named-count","facet","relation-count","relation-select","aggregate","pagination"].includes(n.kind)||n.method!==void 0&&!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n.method)||n.alias!==void 0&&typeof n.alias!="string"||n.relation!==void 0&&typeof n.relation!="string")throw new Error("QUERY_OPERATION_INVALID: invalid generated operation descriptor");return Object.freeze({kind:n.kind,method:n.method,alias:n.alias,relation:n.relation})}function dr(n){const e=Bi(n),t=i=>"'"+i.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\t/g,"\\t").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+"'";return e.method?e.method+"("+(e.alias!==void 0?t(e.alias):e.kind==="relation-select"?"...":"")+")":"framework: "+e.kind+(e.relation?" "+e.relation:"")+(e.alias!==void 0?" "+t(e.alias):"")}const ge=Symbol("runtime request binding");class hr extends Error{constructor(e,t,i){super(`${e}: ${i} request requires a non-blank ${t}; supply it at the request entry point`),this.code=e,this.field=t,this.requestKind=i,this.name="RequestIntentError"}}function Ee(n,e,t){if(typeof n!="string"||new RegExp("^\\p{White_Space}*$","u").test(n))throw new hr(e==="comment"?"REQUEST_COMMENT_REQUIRED":"QUERY_PURPOSE_REQUIRED",e,t);return n}class it{#e;#t;constructor(e,t){this.#e=Ee(e,"comment","query"),this.#t=Ee(t,"purpose","query"),Object.freeze(this)}get comment(){return this.#e}get purpose(){return this.#t}}class Ie{#e;constructor(e){this.#e=Ee(e,"comment","mutation"),Object.freeze(this)}get comment(){return this.#e}get auditReason(){return this.#e}readbackIntent(){return new it(this.#e,"verify persisted mutation result")}}class L{#e;#t;#n;#r;#i;#o;#s;constructor(e,t,i){const r=e,o=Mt(e),s=o instanceof L?o:void 0;if(this.#e=t===void 0?s?.intent??new it(r?._comment??r?.commentText,r?._purpose??r?.purposeText):new it(t?.comment,t?.purpose),i&&i[ge]!==!0)throw new Error("QUERY_REQUEST_OWNERSHIP_INVALID: request binding is runtime-owned");const a=s&&s.intent.comment===this.#e.comment&&s.purpose===this.#e.purpose?s:void 0;this.#s=i?.invocation??(i?.parent?i.parent.#s:void 0)??(a?a.#s:void 0)??Object.freeze({}),this.#n=i?i.parent:a?.parentRequest,this.#r=Ee(i?.comment??a?.comment??this.#e.comment,"comment","query"),this.#i=i?.name??a?.requestName??String(r.entity??"query"),this.#o=i?.operation??a?.operation,this.#t=N(e);const c=this.#t;for(const[u,l]of[["commentText",this.comment],["purposeText",this.purpose],["_comment",this.comment],["_purpose",this.purpose]])Object.defineProperty(c,u,{value:l,enumerable:!u.startsWith("_"),configurable:!0,writable:!1});ht.set(c,B(i?.source??a?.traceSource??ht.get(e)??mi(String(r.entity),this.intent.comment,this.purpose))),pn(c,this),Object.freeze(this)}get intent(){return this.#e}get query(){return this.#t}get comment(){return this.#r}get purpose(){return this.#e.purpose}get traceSource(){return ht.get(this.#t)}get parentRequest(){return this.#n}get rootRequest(){let e=this;for(;e.parentRequest;)e=e.parentRequest;return e}get requestName(){return this.#i}get operation(){return this.#o}get traceChain(){const e=[];for(let t=this;t;t=t.parentRequest)e.push({kind:"comment",name:t.requestName,detail:t.comment});return B([{kind:"purpose",name:this.rootRequest.requestName,detail:this.purpose},...e.reverse()])}withQuery(e){const t=Mt(e);if(t instanceof L&&t.#s!==this.#s)throw new Error("QUERY_SCOPE_OWNER_MISMATCH: replacement belongs to another query invocation");return new L(e,this.intent,{[ge]:!0,parent:this.parentRequest,comment:this.comment,name:this.requestName,operation:this.operation,source:this.traceSource,invocation:this.#s})}deriveOperation(e,t){const i=Bi(t);return new L(e,this.intent,{[ge]:!0,parent:this,comment:dr(i),name:String(e.entity??this.requestName),operation:i,source:this.traceSource})}deriveHelper(e,t){return new L(e,this.intent,{[ge]:!0,parent:this,comment:Ee(t,"comment","query"),name:String(e.entity??this.requestName),source:this.traceSource})}derive(e,t,i){if(i)return this.deriveOperation(this.query,i).deriveChild(e,t);const r=`${String(this.query.entity)}.${t}`;return this.deriveChild(e,t,void 0,r)}deriveAggregate(e,t,i){const r=this.parentRequest?.operation?.kind==="facet"?this.parentRequest:void 0,o=r?r.deriveHelper(e,"aggregate "+r.operation.relation):this.deriveOperation(e,i),s=[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}],a=new L(e,this.intent,{[ge]:!0,parent:o.parentRequest,comment:o.comment,name:o.requestName,operation:o.operation,source:s});return(e._comment??e.commentText)===void 0?a:a.deriveChild(e)}deriveChild(e,t,i,r){const o=e,s=o._comment??o.commentText;return new L(e,this.intent,{[ge]:!0,parent:this,comment:s===void 0?i??`load ${String(o.entity)}`:Ee(s,"comment","query"),name:r??String(o.entity),source:t===void 0?this.traceSource:[...this.traceSource,{kind:"relation",name:t,detail:`${String(this.query.entity)}.${t}`}]})}}class ce{#e;#t;constructor(e,t){this.#e=new Ie(t===void 0?e?.comment:t?.comment),this.#t={...e},e.payload&&typeof e.payload=="object"&&(this.#t.payload={...e.payload}),Object.defineProperty(this.#t,"comment",{value:this.#e.comment,enumerable:!0,writable:!1,configurable:!1}),Object.freeze(this)}get intent(){return this.#e}get mutation(){return this.#t}get comment(){return this.#e.comment}withLoadedSnapshot(e){return ni.set(this,new $(e.values())),this}loadedValues(){return ni.get(this)?.values()??{}}bindCheckerLoadedValues(e){return Object.defineProperty(e,"loadedValues",{value:Object.freeze({...this.loadedValues()}),enumerable:!1,writable:!1,configurable:!1}),e}get graphSession(){return Lt.get(this)?.session}scopeFor(e){const t=Lt.get(this),i=yn(t?.parent,e.entity,e.id,this.comment,t?.localComment);return t&&Ui.set(i,t.session),i}traceFor(e){const t=this.#t,i=t.ledgerRoot?.traceChain(t.ledgerKey??e);return i?.length?B(i):this.scopeFor(e).recover()}auditProjection(e,t,i){const r=[...J(t),...J(this.#t.id),...i?ti(i):J(this.loadedValues()),...ti(this.graphSession?.logBindings)];return Object.freeze({reason:re(this.comment,r),mutationLineage:B(this.traceFor(e).map(o=>({...o,detail:re(o.detail,r)})))})}}class fr{#e;#t;#n=0;#r=!1;#i=new ur;constructor(e){this.#e=new Ie(e?.comment),Object.freeze(this)}get intent(){return this.#e}sealPreparedGraph(){this.#i.seal(),this.#r=!0}get isPreparedSealed(){return this.#r}get preparedRootEntity(){return this.#i.rootEntity}registerSource(e,t,i,r,o){this.#i.register(e,t,i,r,o)}sourceMembers(e){return this.#i.members(e)}captureInputSources(){this.#i.captureInput()}bindExecutionReference(e){this.#i.bind(e)}bindExecutionMetadata(e){this.#i.bindMetadata(e)}capturePreparedMutation(e,t,i){return this.#i.remember(e,t,i)}normalizePreparedMutation(e){return this.#i.normalizeRestored(e)}replayPreparedMutation(e){return this.#i.replay(e)}validatePreparedSources(){this.#i.validate()}recordPreparedResult(e,t){this.#i.providerResult(e,t)}acceptPreparedResult(e,t,i){this.#i.applied(e,t,i)}finishPreparedCommit(e,t){this.#i.committed(e,t)}requirePreparedComplete(){this.#i.complete()}get isPreparedEmpty(){return this.#r&&this.#n===0}recordPreparedMutation(){if(this.#r)throw new Error("GRAPH_PREPARATION_SEALED: cannot add mutations after complete preparation");this.#n++}requireMutationAllowed(){if(this.isPreparedEmpty)throw new Error("GRAPH_PREPARATION_EMPTY: complete graph has no admitted mutations")}discardRestoredFields(e,t,i,r){if(e.entity!==i.entity)throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");e.validate(t.change(i),!t.isNew(i)),r?.discardRestoredFields(t,i)}request(e,t,i){if(t&&Ui.get(t)!==this)throw new Error("GRAPH_TRACE_SCOPE_MISMATCH: parent scope belongs to another graph invocation");const r=new ce(e,this.#e);return Lt.set(r,{session:this,parent:t,localComment:i}),r}captureLogBindings(e){this.#t=q(e,this.#t)}get logBindings(){return this.#t}}class ri extends Error{constructor(e){super("GRAPH_ALREADY_COMMITTED: post-commit processing failed; do not retry as an uncommitted mutation"),this.cause=e,this.committed=!0,this.name="GraphCommittedError"}}const pr="MUTATION-POLICY-001",mr="MUTATION-POLICY-002";class D extends Error{constructor(e){super(e),this.name="MutationPolicyError"}}class Wr{constructor(e){this.resolver=e}resolve(e){return this.resolver(e)}}class Hr{constructor(e){this.finder=e}findApproval(e){return this.finder(e)}}class gr{onWarning(e,t){!t.firstOccurrence||typeof console>"u"||console.warn(`TeaQL mutation policy warning code=${t.warningCode} requestKey=${t.snapshot.requestKey} source=${t.snapshot.source} approval=${t.snapshot.approvalStatus}`)}}let si=0;class yr{constructor(){this.profile={warningSink:new gr},this.emittedWarnings=new Set,this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.remaining=new Map}setRegistry(e){this.profile.registry=e}setApprovalProvider(e){this.profile.approvalProvider=e}setWarningSink(e){this.profile.warningSink=e}beginGraph(){if(this.graphActive)throw new D("mutation policy graph is already active");this.graphActive=!0,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}endGraph(){this.graphActive=!1,this.graphReviewed=!1,this.preflight=[],this.preflightKeys=[],this.rootEntity=void 0,this.auditReason=void 0,this.remaining.clear(),this.graphSnapshot=void 0}recordPreflight(e){if(!this.graphActive)return;if(this.graphReviewed)throw new D("mutation preflight cannot change after policy review");const t=oi(e);this.rootEntity??=t.entity,this.auditReason??=Be(e),this.preflight.push(t),this.preflightKeys.push(ci(e,t))}enterMutation(e,t){const i=oi(t);if(!this.graphActive)return{snapshot:this.review(e,this.plan(i.entity,Be(t),[i]))};if(!this.graphReviewed){if(this.profile.registry&&this.preflight.length===0)throw new D("customer mutation policy requires complete graph preflight before provider mutation");if(!this.profile.registry&&this.preflight.length===0)return{snapshot:this.review(e,this.plan(i.entity,Be(t),[i]))};const r=this.preflight.length?this.preflight:[i];this.graphSnapshot=this.review(e,this.plan(this.rootEntity??r[0].entity,this.auditReason??Be(t),r)),this.remaining.clear();const o=this.preflight.length?this.preflightKeys:r.map(Qi);for(const s of o)this.remaining.set(s,(this.remaining.get(s)??0)+1);this.graphReviewed=!0}return this.consume(ci(t,i)),{snapshot:this.graphSnapshot}}prepareGraphReview(e,t){if(!this.graphActive||this.graphReviewed||this.preflight.length===0)return;const i=this.preflight;this.graphSnapshot=this.review(e,this.plan(t??this.rootEntity??i[0].entity,this.auditReason,i)),this.remaining.clear();for(const r of this.preflightKeys)this.remaining.set(r,(this.remaining.get(r)??0)+1);this.graphReviewed=!0}ensureGraphComplete(){if(this.graphReviewed&&this.remaining.size)throw new D("reviewed mutation plan contains operations that were not executed")}review(e,t){br(t);const i=ai(t),r=this.profile.registry?.resolve(i.requestKey);let o,s,a,c;if(!r)o="generated_default",a="not_applicable",c=[pr];else{s=wr(r.identity);const l=r.review(e,i);if(!l||l.verdict!=="allow"&&l.verdict!=="deny")throw new D("customer mutation policy returned an invalid decision");if(l.verdict==="deny")throw new D(`[MUTATION POLICY DENIED] ${l.code||"MUTATION-POLICY-DENIED"}: ${l.message||"mutation rejected"}`);o="customer";const d=this.profile.approvalProvider?.findApproval(s);a=vr(d,s)?"approved":"missing",c=a==="approved"?[]:[mr]}const u=Object.freeze({executionId:i.executionId,requestKey:i.requestKey,source:o,policy:s,approvalStatus:a,warningCodes:Object.freeze([...c]),operations:Object.freeze(i.operations.map(l=>Object.freeze({kind:l.kind,entity:l.entity,entityId:he(l.entityId),changedFields:Object.freeze(Object.keys(l.changedValues).sort())})))});for(const l of c)this.emitWarning(e,u,l);return u}plan(e,t,i){return si+=1,ai({executionId:`teaql-mutation-${si}`,requestKey:`${e}.saveGraph`,rootEntityType:e,auditReason:new Ie(t).comment,operations:i})}consume(e){const t=this.remaining.get(e)??0;if(t<1)throw new D("provider mutation is not present in the reviewed graph plan");t===1?this.remaining.delete(e):this.remaining.set(e,t-1)}emitWarning(e,t,i){const r=t.policy?`${t.policy.policyId}:${t.policy.version}:${t.policy.fingerprint}`:"none",o=`${t.requestKey}|${r}|${i}`,s=!this.emittedWarnings.has(o);this.emittedWarnings.add(o);try{this.profile.warningSink.onWarning(e,Object.freeze({snapshot:t,warningCode:i,firstOccurrence:s}))}catch{}}}function oi(n){const e=String(n?.entity??"").trim(),t=String(n?.action??"").toLowerCase(),i={create:"create",update:"update",delete:"delete",recover:"recover"};if(!e||!i[t])throw new D("mutation must contain a supported entity operation");const r=n?.payload&&typeof n.payload=="object"?n.payload:{};return Object.freeze({kind:i[t],entity:e,entityId:he(n?.id??r.id),originalVersion:n?.version??n?.expectedVersion,changedValues:Ki(r)})}function Be(n){return new Ie(n?.comment).comment}function br(n){if(new Ie(n?.auditReason),!n.executionId?.trim())throw new D("execution id is required");if(!n.requestKey?.trim())throw new D("request key is required");if(!n.rootEntityType?.trim())throw new D("root entity type is required");if(!n.operations.length)throw new D("mutation plan is empty")}function wr(n){if(!n||!n.policyId?.trim()||!n.version?.trim()||!n.fingerprint?.trim())throw new D("customer mutation policy identity is invalid");return Object.freeze({policyId:n.policyId.trim(),version:n.version.trim(),fingerprint:n.fingerprint.trim()})}function vr(n,e){return!!n&&Sr(n.policy,e)&&!!n.approvedBy?.trim()&&n.approvedAt instanceof Date&&Number.isFinite(n.approvedAt.getTime())&&n.approvedAt.getTime()!==0}function Sr(n,e){return n.policyId===e.policyId&&n.version===e.version&&n.fingerprint===e.fingerprint}function ai(n){return Object.freeze({executionId:n.executionId,requestKey:n.requestKey,rootEntityType:n.rootEntityType,auditReason:n.auditReason,operations:Object.freeze(n.operations.map(e=>Object.freeze({kind:e.kind,entity:e.entity,entityId:he(e.entityId),originalVersion:e.originalVersion,changedValues:Ki(e.changedValues)})))})}function he(n,e=new WeakSet){if(n==null||typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="bigint")return n;if(n instanceof Date)return n.toISOString();if(typeof n=="object"){if(e.has(n))throw new D("mutation policy values must not contain cycles");e.add(n);try{if(Array.isArray(n))return Object.freeze(n.map(i=>he(i,e)));const t=n;return"id"in t&&Object.keys(t).some(i=>i!=="id")?he(t.id,e):Object.freeze(Object.fromEntries(Object.entries(t).map(([i,r])=>[i,he(r,e)])))}finally{e.delete(n)}}return String(n)}function Ki(n){return Object.freeze(Object.fromEntries(Object.entries(n).map(([e,t])=>[e,he(t)])))}function Qi(n){return nt({kind:n.kind,entity:n.entity,entityId:n.entityId,originalVersion:n.originalVersion,changedValues:n.changedValues})}function ci(n,e){const t=n?.ledgerKey;return t&&typeof t=="object"&&String(t.entity??"").trim()&&t.id!==void 0&&t.id!==null?`ledger:${String(t.entity).trim()}:${nt(t.id)}`:`operation:${Qi(e)}`}function nt(n){return typeof n=="bigint"?JSON.stringify(`${n.toString()}n`):n===void 0?'""':n===null||typeof n!="object"?JSON.stringify(n):Array.isArray(n)?`[${n.map(nt).join(",")}]`:`{${Object.entries(n).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${nt(t)}`).join(",")}}`}const li=new WeakMap;let Er=1;function Or(n){if(!n||typeof n!="object"&&typeof n!="function")return String(n);const e=n;let t=li.get(e);return t||(t=Er++,li.set(e,t)),String(t)}class ft extends Error{constructor(e,t,i){super(`context root ${e}: expected ${t}`),this.reason=e,this.expectedType=t,this.activeRoot=i,this.name="ContextRootError"}}class rt{constructor(e=er()){this.businessClock=new ir,this.mutationPolicy=new yr,this.resources=new Map,this.continuousPageCursors=new Map,this.retainedIdSets=new Map,this.idSetBuilds=new Map,this.continuousPageRuntime={owner:"",get:(t,i)=>this.getContinuousPageCursor(t,i),put:(t,i,r)=>this.putContinuousPageCursor(t,i,r),observe:(t,i)=>{this.continuousPagePlan=t,this.continuousPageCursorId=i}},this.idSetPaginationRuntime={owner:"",scope:"",get:t=>this.idSetStore().get(t),put:(t,i)=>this.idSetStore().put(t,i),build:(t,i)=>this.singleFlightIdSetBuild(t,i),observe:(t,i)=>{this.idSetPaginationPlan=t,this.idSetPaginationCount=i,this.idSetPaginationCountAccuracy=t==="ID_SET_BUILD"||t==="ID_SET_HIT"?"EXACT":t==="ID_SET_FALLBACK_LIMIT_EXCEEDED"?"LOWER_BOUND":"UNKNOWN"}},this.userIdentifier="",this.continuousPagePlan="DISABLED",this.idSetPaginationPlan="ID_SET_DISABLED",this.idSetPaginationCountAccuracy="UNKNOWN",this.locale="en",this.i18nCatalog=$e.builtin,this.naturalCatalog=oe.builtin,this.naturalModel=te.empty,this.naturalRenderer=Ti,this.naturalWarning=t=>{this.runtimeLogger.write("WARN","checker.warning","TeaQL checker warning",{category:"VALIDATION",error_code:t})},this.runtimeLogger=e}withInternalIdGenerator(e){if(!e||typeof e.generateId!="function")throw new TypeError("Internal ID generator must provide generateId(entity, context)");return this.insertResource("idGenerator",e)}async generateInternalId(e){if(typeof e!="string"||!e.trim()||e!==e.trim())throw new TypeError("Internal ID entity type is required");if(this.resources.has("idGenerator")){const i=this.getResource("idGenerator");if(!i||typeof i.generateId!="function")throw new TypeError("Configured internal ID generator must provide generateId(entity, context)");return jt(await i.generateId(e,this))}const t=this.requireResource("dataService");if(typeof t.reserveInternalId!="function")throw new TypeError("Configured data service must provide reserveInternalId(entity, context)");return jt(await t.reserveInternalId(e,this))}withBusinessClock(e){if(!e||typeof e.now!="function")throw new TypeError("Business clock must provide now()");return this.businessClock=e,this}businessTime(){const e=this.businessClock.now();if(!(e instanceof Date)||!Number.isFinite(e.getTime()))throw new TypeError("Business clock returned an invalid Date");return new Date(e.getTime())}businessDate(){return this.businessTime().toISOString().slice(0,10)}withObjectStorage(e){return this.insertResource("objectStorageProvider",e)}withObjectStorageObserver(e){return this.insertResource("objectStorageObserver",e)}objectStorage(e){return new or(this,e)}async withQueryRequest(e,t){const i=this.requireResource("dataService");return i.withQueryRequest?i.withQueryRequest(e,t):t()}get checkerPresentationModel(){return this.naturalModel}installCheckerPresentationModel(e){if(!(e instanceof te))throw new TypeError("Checker presentation model required");return this.naturalModel=e,this}installCheckerMessageCatalog(e){const t=oe.fromJson(e);return this.naturalCatalog=t,this}installCheckerMessageRenderer(e){if(typeof e!="function")throw new TypeError("Checker renderer required");return this.naturalRenderer=e,this}installCheckerMessageWarning(e){if(typeof e!="function")throw new TypeError("Checker warning sink required");return this.naturalWarning=e,this}captureCheckerMessages(e=te.empty){return Object.freeze({model:this.naturalModel===te.empty?e:this.naturalModel,catalog:this.naturalCatalog,legacy:this.i18nCatalog,locale:ke(this.locale),renderer:this.naturalRenderer,warning:this.naturalWarning})}translateCheckResultsFrom(e,t,i={}){const r=this.captureCheckerMessages(i.defaultModel).model,o=_i(t,Object.freeze({model:r,entity:e}));return t.splice(0,t.length,...o),Si(this,t,e,i.privacyPolicy??(()=>{}),i.checkedValues??[]),t}renderCheckerGraphResults(e,t,i){if(t.legacy.translate!==$e.prototype.translate||this.translateCheckResults!==rt.prototype.translateCheckResults)return[...e];const r=Ye(e),o=new Set;try{return r.finish(r.values.map(s=>Qt(t,s,o,i)))}finally{r.close()}}setLocaleCode(e){const t=ke(e);return this.locale=t,this}setLanguageCode(e){return this.setLocaleCode(e)}installI18nCatalog(e){if(!e)throw new Error("catalog is required");return this.i18nCatalog=e,this}installIdSetPaginationStore(e){if(!e)throw new Error("ID set pagination store is required");return this.insertResource("idSetPaginationStore",e)}translateCheckResults(e,t){if(!e.length)return e;const i=Ye(e,t);try{const r=this.i18nCatalog.translate!==$e.prototype.translate,o=this.captureCheckerMessages(),s=new Set,a=i.values.map(c=>r?this.i18nCatalog.translate(c,this.locale):Qt(o,c,s));return e.splice(0,e.length,...i.finish(a)),e}finally{i.close()}}withMutationPolicyRegistry(e){if(!e||typeof e.resolve!="function")throw new TypeError("mutation policy registry must expose resolve(requestKey)");return this.mutationPolicy.setRegistry(e),this}withMutationPolicyApprovalProvider(e){if(!e||typeof e.findApproval!="function")throw new TypeError("mutation policy approval provider must expose findApproval(identity)");return this.mutationPolicy.setApprovalProvider(e),this}withMutationGovernanceSink(e){if(!e||typeof e.onWarning!="function")throw new TypeError("mutation governance sink must expose onWarning(context, warning)");return this.mutationPolicy.setWarningSink(e),this}reviewMutationPlan(e){return this.mutationPolicy.review(this,e)}beginMutationPolicyGraph(){this.mutationPolicy.beginGraph()}prepareMutationPolicyGraph(e){this.mutationPolicy.prepareGraphReview(this,e)}recordMutationPolicyPreflight(e){this.mutationPolicy.recordPreflight(e)}enterMutationPolicy(e){return this.mutationPolicy.enterMutation(this,e).snapshot}ensureMutationPolicyGraphComplete(){this.mutationPolicy.ensureGraphComplete()}endMutationPolicyGraph(){this.mutationPolicy.endGraph()}beginFixEvidence(){return this.insertResource("fixEvidenceCurrent",[])}recordFixEvidence(e){const t=String(e.sourceLabel||""),i=t.toLowerCase();if(!e.entityType||!e.modelPath||!t||i.includes("authorization")||i.includes("cookie")||i.includes("token="))throw new TypeError("Fix evidence must contain only safe framework provenance labels");const r=this.getResource("fixEvidenceCurrent")??[];return this.getResource("fixEvidenceCurrent")||this.insertResource("fixEvidenceCurrent",r),r.push(Object.freeze({...e})),this}finishFixEvidence(){const e=this.getResource("fixEvidenceCurrent")??[];return this.insertResource("fixEvidenceLast",Object.freeze([...e])),this.removeResource("fixEvidenceCurrent")}lastFixEvidence(){return this.getResource("fixEvidenceLast")??[]}insertResource(e,t){return this.resources.set(e,t),this}getResource(e){return this.resources.get(e)}removeResource(e){return this.resources.delete(e),this}requireResource(e){const t=this.getResource(e);if(t===void 0)throw new Error(`Required UserContext resource is missing: ${e}`);return t}ensureSchema(){const e=this.requireResource("dataService"),t=e[Di];if(!t)throw new Error("Configured dataService is not a schema-aware TeaQL provider");return t.call(e,this)}withActiveRoot(e){if(!e||!e.entity||e.id===void 0||e.id===null)throw new TypeError("active root must be a typed entity reference");return this.insertResource("activeRoot",Object.freeze({...e}))}requireActiveRoot(e){const t=this.getResource("activeRoot");if(!t)throw new ft("missing",e);if(t.entity!==e)throw new ft("type_mismatch",e,t);const i=t.id;if(!(typeof i=="number"?Number.isSafeInteger(i)&&i>0:typeof i=="bigint"?i>0n:typeof i=="string"&&/^[1-9][0-9]*$/.test(i)))throw new ft("invalid_id",e,t);return t}prepareQuery(e){this.continuousPageRuntime.owner=this.userIdentifier,this.idSetPaginationRuntime.owner=this.userIdentifier;const t=this.getResource("activeRoot");return this.idSetPaginationRuntime.scope=[this.userIdentifier,t?`${t.entity}:${String(t.id)}`:"-",Or(this.getResource("dataService"))].join("|"),e.bindContinuousPageRuntime(this.continuousPageRuntime).bindIdSetPaginationRuntime(this.idSetPaginationRuntime)}getContinuousPageCursor(e,t){const i=`${e}:${t}`,r=this.continuousPageCursors.get(i);if(r&&r.expiresAt<=Date.now()){this.continuousPageCursors.delete(i);return}return r}putContinuousPageCursor(e,t,i){if(this.continuousPageCursors.size>=4096){const r=[...this.continuousPageCursors.entries()].sort((o,s)=>o[1].expiresAt-s[1].expiresAt)[0];r&&this.continuousPageCursors.delete(r[0])}this.continuousPageCursors.set(`${e}:${t}`,i)}getRetainedIdSet(e){const t=this.retainedIdSets.get(e);if(t&&t.expiresAt<=Date.now()){this.retainedIdSets.delete(e);return}return t}idSetStore(){return this.getResource("idSetPaginationStore")??{get:e=>this.getRetainedIdSet(e),put:(e,t)=>this.putRetainedIdSet(e,t),invalidate:e=>{this.retainedIdSets.delete(e)}}}putRetainedIdSet(e,t){if(t.ids.byteLength>268435456)throw new Error("ID set exceeds the process-local store memory ceiling");const r=()=>[...this.retainedIdSets.values()].reduce((o,s)=>o+s.ids.byteLength,0);for(;this.retainedIdSets.size>=64||r()+t.ids.byteLength>268435456;){const o=[...this.retainedIdSets.entries()].sort((s,a)=>s[1].expiresAt-a[1].expiresAt)[0];if(!o)break;this.retainedIdSets.delete(o[0])}this.retainedIdSets.set(e,t)}async singleFlightIdSetBuild(e,t){const i=this.idSetBuilds.get(e);if(i)return{value:await i,built:!1};const r=t();this.idSetBuilds.set(e,r);try{return{value:await r,built:!0}}finally{this.idSetBuilds.delete(e)}}}function ui(n,e,t){if(!(n==null||typeof n=="number"&&Number.isInteger(n)&&n>=-2147483648&&n<=2147483647))return new G([{ruleId:"invalid_type",entityType:e,location:F.property(t),message:`Invalid field ${t}: expected an exact signed 32-bit Integer`}])}class Ge{constructor(e,t){this.entityType=e;const i=[];for(const[r,o]of Object.entries(t?.columns??{})){if(o.integer32!==void 0&&typeof o.integer32!="boolean")throw new TypeError("INVALID_INTEGER32_METADATA");if(!o.integer32)continue;const s=o.modelName??r;if(o.logicalType!=="integer"||o.decode!=="number"||["id","version"].includes(r)||["id","version"].includes(s)||Object.values(t?.relations??{}).some(a=>!a.many&&a.localKey===r))throw new TypeError(`INVALID_INTEGER32_METADATA: ${e}.${s}`);i.push(Object.freeze({native:r,canonical:s,column:o.columnName}))}this.fields=Object.freeze(i),Object.freeze(this)}checkMutation(e,t=[]){for(const i of this.fields){const r=ui(e[i.canonical],this.entityType,i.canonical);r&&!t.some(o=>o.ruleId==="invalid_type"&&o.location.modelPath()===i.canonical)&&t.push(...r.violations)}return t}read(e,t){const i=this.fields.find(o=>o.native===e);if(!i||t==null)return t;if(typeof t=="bigint"&&t>=-2147483648n&&t<=2147483647n)return Number(t);const r=ui(t,this.entityType,i.canonical);if(r)throw r;return t}}function Gi(n){for(const[e,t]of Object.entries(n))new Ge(e,t)}function Wi(n,e){const t=n.defaultDomainRoot,i=e.defaultDomainRoot;if(t&&i&&(t.entity!==i.entity||t.id!==i.id))throw new Error("Cannot compose Runtime Modules with different Default Domain Roots");const r=new Map;for(const o of[...n.constants??[],...e.constants??[]])r.set(`${o.entity}:${o.id}`,o);return{defaultDomainRoot:i??t,constants:[...r.values()],ensure:n.ensure&&e.ensure?async o=>{await n.ensure(o),await e.ensure(o)}:e.ensure??n.ensure}}class It{constructor(e={},t={},i={},r=te.empty){Gi(e),this.schemas=Object.freeze({...e}),this.checkers=Object.freeze({...t}),this.checkerPresentationModel=r,this.bootstrap=Object.freeze({defaultDomainRoot:i.defaultDomainRoot,constants:Object.freeze([...i.constants??[]]),ensure:i.ensure})}and(e){return new It({...this.schemas,...e.schemas},{...this.checkers,...e.checkers},Wi(this.bootstrap,e.bootstrap),this.checkerPresentationModel.merge(e.checkerPresentationModel))}withCheckerPresentation(e){return new It({...this.schemas},{...this.checkers},this.bootstrap,this.checkerPresentationModel.merge(e))}}class Y{constructor(e,t,i){this.field=e,this.expr=t,this.direction=i}static new(e,t){return new Y(e,null,t)}static expr(e,t){return new Y("",e,t)}static asc(e){return Y.new(e,"Asc")}static desc(e){return Y.new(e,"Desc")}}class st{constructor(e,t,i,r){this.enabledValue=e,this.cacheExpiredMillis=t,this.propagateValue=i,this.propagateCacheExpiredMillis=r}static enabled(e){return new st(!0,e,!1,0)}propagate(e){return this.propagateValue=!0,this.propagateCacheExpiredMillis=e,this}}let jr=class Hi{constructor(e){this.hardLimitValue=1e4,this.filterCondition=null,this.limitValue=0,this.offsetValue=0,this.orderItems=[],this.selectItems=[],this.properties=[],this.joins=[],this.groupByItems=[],this.aggregateItems=[],this.facets=[],this.relations=[],this.relationAggregates=[],this.deletionVisibility="live",this.entity=e,Object.defineProperty(this,"hardLimitValue",{enumerable:!1,writable:!0,value:1e4}),Object.defineProperty(this,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationOptions",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"idSetPaginationRuntimeContext",{enumerable:!1,writable:!0,value:void 0}),Object.defineProperty(this,"topNProbeThreshold",{enumerable:!1,writable:!0,value:void 0})}comment(e){return this.commentText=e,this}purpose(e){return this.purposeText=e,this}facetBy(e,t,i,r=!0,o){return this.facets.push({facetName:e,relationName:t,query:i.toQuery(),includeAllFacets:r,operation:o}),this}clone(){const e=N(this);for(const t of["commentText","purposeText","_comment","_purpose"]){const i=Object.getOwnPropertyDescriptor(e,t);i&&"value"in i&&i.configurable&&Object.defineProperty(e,t,{...i,writable:!0})}return e}filter(e){return this.filterCondition=e,this}withDeletedRows(){return this.deletionVisibility="all",this}deletedRowsOnly(){return this.deletionVisibility="deleted",this}limit(e){if(!Number.isSafeInteger(e)||e<1)throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.limitValue=e,this}optimizeForContinuousPageFetch(){return this.optimizeForContinuousPageFetchWith("default",600)}optimizeForContinuousPageFetchWith(e,t){if(!e?.trim())throw new Error("continuous page namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("continuous page ttlSeconds must be a positive integer");return this.continuousPageFetchOptions={namespace:e,ttlSeconds:t},this}bindContinuousPageRuntime(e){return this.continuousPageRuntimeContext=e,this}localContinuousPageOptions(){return this.continuousPageFetchOptions}localContinuousPageRuntime(){return this.continuousPageRuntimeContext}clearContinuousPageRuntime(){return this.continuousPageRuntimeContext=void 0,this}optimizePaginationWithIdSet(){return this.optimizePaginationWithIdSetConfig("default",600,3e6)}optimizePaginationWithIdSetConfig(e,t,i){if(!e?.trim())throw new Error("ID set namespace must not be empty");if(!Number.isSafeInteger(t)||t<=0)throw new Error("ID set ttlSeconds must be a positive integer");if(!Number.isSafeInteger(i)||i<=0)throw new Error("ID set maxIds must be a positive integer");return this.idSetPaginationOptions={namespace:e,ttlSeconds:t,maxIds:i},this}bindIdSetPaginationRuntime(e){return this.idSetPaginationRuntimeContext=e,this}localIdSetPaginationOptions(){return this.idSetPaginationOptions}localIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext}clearIdSetPaginationRuntime(){return this.idSetPaginationRuntimeContext=void 0,this}topNProbeParentThreshold(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("topNProbeParentThreshold must be a non-negative safe integer");return this.topNProbeThreshold=e,this}localTopNProbeParentThreshold(){return this.topNProbeThreshold}prepareForList(){if(!Number.isSafeInteger(this.offsetValue)||this.offsetValue<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");if(this.limitValue&&(!Number.isSafeInteger(this.limitValue)||this.limitValue<1))throw new Error("QUERY_INVALID_LIMIT: limit must be a positive safe integer");return this.applyListLimit(this.hardLimitValue),this}forExactCount(e="__teaql_total"){const t=new Hi(this.entity);return t.filterCondition=N(this.filterCondition),t.commentText=this.commentText,t.purposeText=this.purposeText,t.deletionVisibility=this.deletionVisibility,t.aggregate("Count","id",e),je(this,t),t}applyListLimit(e){if(this.limitValue||(this.limitValue=e),this.limitValue>e)throw new Error(`QUERY_HARD_LIMIT_EXCEEDED: requested limit ${this.limitValue} exceeds hard limit ${e}`)}offset(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("QUERY_INVALID_OFFSET: offset must be a non-negative safe integer");return this.offsetValue=e,this}relation(e){return this.relations.push({name:e}),this}relationQuery(e,t,i="id",r="id",o=!0,s){return this.relations.push({name:e,query:t,localKey:i,foreignKey:r,many:o,operation:s}),this}relationAggregate(e,t,i,r=!0,o){return this.relationAggregates.push({relationName:e,alias:t,query:i,singleResult:r,operation:o}),this}order(e){return this.orderItems.push(e),this}select(e){return this.selectItems.push(...e),this}enableAggregationCacheFor(e){return this.aggregationCache=st.enabled(e),this}propagateAggregationCache(e){return this.aggregationCache||(this.aggregationCache=st.enabled(0)),this.aggregationCache.propagate(e),this}aggregate(e,t,i){return this.aggregateItems.push({function:e,field:t,alias:i}),this}groupBy(e,t){if(t!==void 0){if(typeof t!="string"||!t.trim())throw new TypeError("Group alias must be a non-empty string");const i=this.groupByAliases?.[e];if(i!==void 0&&i!==t)throw new Error("Grouping field already has a different alias");this.groupByAliases??=Object.create(null),this.groupByAliases[e]=t}return this.groupByItems.push(e),this}};function kr(n,e){if(n.logMode!=="masked")throw new Error("Telemetry requires safe SQL projection");const t=(i=[])=>JSON.stringify(i.map(r=>({kind:r.kind,name:r.name,detail:r.detail??""})));return Object.freeze({body:"TeaQL SQL execution",correlation:e,attributes:Object.freeze({"teaql.trace_chain":t(n.traceChain),"teaql.trace_path":t(n.tracePath),"teaql.mutation_lineage":t(n.mutationLineage),"teaql.intent.comment":n.comment??n.auditReason??"","teaql.intent.purpose":n.purpose??"","teaql.sql.debug":n.debugSQL,"teaql.sql.log_mode":n.logMode,"teaql.sql.operation":n.operation,"teaql.sql.outcome":n.executionOutcome??"unknown","teaql.sql.elapsed_us":n.elapsedMicros,...n.resultCount===void 0?{}:{"teaql.sql.result_count":n.resultCount},...n.affectedRows===void 0?{}:{"teaql.sql.affected_rows":n.affectedRows}})})}function pt(n,e=!1){try{e?console.warn(n):console.info(n)}catch{}}class ee extends Array{static get[Symbol.species](){return Array}constructor(e=[],t={}){if(super(),typeof e=="number")this.length=e;else for(const i of e)super.push(i);Object.setPrototypeOf(this,ee.prototype),t.totalCount!==void 0&&di(t.totalCount),this.totalCount=t.totalCount,this.aggregations=Oe(t.aggregations??{}),this.summary=Oe(t.summary??{}),this.facets=Oe(t.facets??{}),this.isLoaded=t.isLoaded??!0}static empty(){return new ee([],{isLoaded:!1})}get data(){return this}withTotalCount(e){return di(e),this.totalCount=e,this}withFacet(e,t){return this.facets[e]=t,this}facet(e){return this.facets[e]}totalCountOrLength(){return this.totalCount??this.length}mapSmart(e){return new ee(Array.from(this,e),{totalCount:this.totalCount,aggregations:this.aggregations,summary:this.summary,facets:this.facets,isLoaded:this.isLoaded})}filterSmart(e){return new ee(this.filter(e),{isLoaded:this.isLoaded})}flatMapSmart(e){return new ee(this.flatMap((t,i)=>Array.from(e(t,i))),{isLoaded:this.isLoaded})}get(e){return Number.isInteger(e)&&e>=0&&e=this.length?!1:(this[e]=t,!0)}first(){return this.get(0)}last(){return this.get(this.length-1)}mergeBy(e,t){const i=new Map;this.forEach((r,o)=>i.set(t(r),o));for(const r of e){const o=t(r),s=i.get(o);s!==void 0?this[s]=r:(i.set(o,this.length),this.push(r))}}identityMap(e){return new Map(Array.from(this,t=>[e(t),t]))}groupBy(e){const t=new Map;for(const i of this){const r=e(i),o=t.get(r)??[];o.push(i),t.set(r,o)}return t}ids(){return Array.from(this,e=>e.id??null)}mapById(){const e=new Map;for(const t of this)t.id!==void 0&&t.id!==null&&e.set(t.id,t);return e}versions(){return Array.from(this,e=>e.version??null)}removeFacet(e){const t=this.facets[e];return delete this.facets[e],t}takeFacets(){const e=this.facets;return this.facets={},e}}function di(n){if(!Number.isSafeInteger(n)||n<0)throw new RangeError("totalCount must be an exact non-negative safe integer")}function Oe(n){return n instanceof ee?n.mapSmart(Oe):n instanceof Date?new Date(n.getTime()):Array.isArray(n)?n.map(Oe):n!==null&&typeof n=="object"?Object.fromEntries(Object.entries(n).map(([e,t])=>[e,Oe(t)])):n}function Tr(n){return n.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}function Pt(n){if(n&&typeof n=="object"){const e=n;return e.id??e.Id}return n}function Lr(n,e){const t=Tr(e);for(const i of[e,`${e}Id`,t,`${t}_id`]){const r=Pt(n[i]);if(r!=null)return r}}function Ir(n){return n.function.toLowerCase()==="count"?0:null}function Pr(n,e){return typeof n=="number"&&typeof e=="number"?n-e:n instanceof Date&&e instanceof Date?n.getTime()-e.getTime():String(n).localeCompare(String(e))}async function _r(n,e,t,i,r,o){const s=i.clone();s.facets=[],s.relations=[],s.relationAggregates=[],s.orderItems=[],s.aggregateItems=[],s.groupByItems=[],s.groupByAliases=void 0,s.offsetValue=0,s.limitValue=0,s.selectItems=[...new Set([r,...o.map(l=>l.field)])],s.comment(`aggregate ${r}`),je(i,s);const a=await n.executeQuery(t.deriveHelper(e(s),`aggregate ${r}`).query),c=new Map,u=new Map;for(const l of a){const d=Lr(l,r);if(d==null)continue;const h=String(d),f=c.get(h)??{},p=u.get(h)??{};for(const m of o){const b=m.function.toLowerCase(),g=l[m.field];if(b==="count")g!=null&&(f[m.alias]=Number(f[m.alias]??0)+1);else if(b==="sum"||b==="avg"){if(g!=null){const y=Number(g);if(!Number.isFinite(y))throw new Error(`Facet aggregate ${m.alias} requires numeric values`);f[m.alias]=Number(f[m.alias]??0)+y,b==="avg"&&(p[m.alias]=(p[m.alias]??0)+1)}}else if(b==="min"||b==="max"){if(g!=null){const y=f[m.alias],O=y==null?0:Pr(g,y);(y==null||b==="min"&&O<0||b==="max"&&O>0)&&(f[m.alias]=g)}}else throw new Error(`Unsupported facet aggregate: ${m.function}`)}c.set(h,f),u.set(h,p)}for(const[l,d]of c){const h=u.get(l)??{};for(const f of o){if(f.function.toLowerCase()!=="avg")continue;const p=h[f.alias]??0;d[f.alias]=p?Number(d[f.alias]??0)/p:null}}return c}async function Xi(n,e,t,i){const r=new L(t);t=r.query;const o={};for(const s of i){const a=r.deriveOperation(t,s.operation??{kind:"facet",relation:s.relationName,alias:s.facetName}),c=a.deriveChild(s.query.clone(),s.relationName),u=c.query,l=u.facets;u.facets=[];const d=u.aggregateItems.map(g=>({function:String(g.function),field:String(g.field),alias:String(g.alias)})),h=d.length?d:[{function:"Count",field:"id",alias:"__teaql_facet_membership_count"}];let f;if(n.executeFacetAggregates)f=await n.executeFacetAggregates(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName,h);else if(n.executeFacetMembership&&h.every(g=>g.function.toLowerCase()==="count")){const g=await n.executeFacetMembership(a.deriveHelper(e(t.clone()),`aggregate ${s.relationName}`).query,s.relationName);f=new Map([...g].map(([y,O])=>[y,Object.fromEntries(h.map(w=>[w.alias,O]))]))}else f=await _r(n,e,a,t,s.relationName,h);u.aggregateItems=[],u.groupByItems=[],u.groupByAliases=void 0;for(const g of u.relationAggregates){if(g.query.entity!==t.entity)continue;const y=t.clone();y.selectItems=["id"],y.properties=[],y.relations=[],y.relationAggregates=[],y.facets=[],y.aggregateItems=[],y.groupByItems=[],y.groupByAliases=void 0,y.orderItems=[],y.offsetValue=0,y.limitValue=0;const O={id:{$inSubquery:{query:y,field:"id"}}};g.query.filterCondition=g.query.filterCondition?{$and:[g.query.filterCondition,O]}:O,je(t,g.query)}if(!s.includeAllFacets){const g={id:{$in:[...f.keys()]}};u.filterCondition=u.filterCondition?{$and:[u.filterCondition,g]}:g}je(t,u);const m=(await n.executeQuery(c.withQuery(e(u)).query)).map(g=>{const y=String(Pt(g.id??g.Id)),O=f.get(y),w={...g};for(const E of d)w[E.alias]=O?.[E.alias]??Ir(E);return w}).filter(g=>s.includeAllFacets||f.has(String(Pt(g.id??g.Id)))),b=new ee(m);l.length&&(b.facets=await Xi(n,e,c.withQuery(u).query,l)),o[s.facetName]=b}return o}function Ar(n){const e=new Map;for(const t of Object.values(n))for(const i of Object.values(t.relations||{})){if(!i.many)continue;const r=n[i.targetEntity],o=r?.columns[i.foreignKey]?.columnName,s=r?.columns.id?.columnName;if(!r||!o||!s)continue;const a=`idx_${r.table}_${o}_${s}`;let c=2166136261;for(let d=0;d>>0).toString(36),l=a.length<=30?a:`${a.slice(0,Math.max(1,29-u.length))}_${u}`;e.set(l,{name:l,table:r.table,foreignColumn:o,idColumn:s})}return[...e.values()]}async function Rr(n,e,t,i){const r=Number(i);if(!Number.isSafeInteger(r)||r<0)throw new Error(`Invalid ID space floor ${i} for ${t}`);for(let o=1;o<=100;o+=1){const s=await n.query(`SELECT current_level AS id FROM teaql_id_space WHERE type_name = ${e(1)}`,[t]);if(!s.rowCount){try{if((await n.query(`INSERT INTO teaql_id_space(type_name, current_level) VALUES (${e(1)}, ${e(2)})`,[t,r])).rowCount===1)return}catch(u){if(!(await n.query(`SELECT current_level FROM teaql_id_space WHERE type_name = ${e(1)}`,[t])).rowCount)throw u}continue}const a=Number(s.rows[0].id);if(a>=r)return;const c=await n.query(`UPDATE teaql_id_space SET current_level = ${e(1)} WHERE type_name = ${e(2)} AND current_level = ${e(3)}`,[r,t,a]);if(c.rowCount===1)return;if(c.rowCount!==0)throw new Error(`ID space floor update for ${t} changed ${c.rowCount} rows on attempt ${o}`)}throw new Error(`Unable to synchronize ID space floor for ${t} after 100 optimistic-lock attempts`)}function Cr(n,e){return n===e?!0:(n instanceof Date&&(n=n.getTime()),e instanceof Date&&(e=e.getTime()),n!=null&&e!==null&&e!==void 0&&String(n)===String(e))}function We(n){return Object.freeze(n.map((e,t)=>Object.freeze({...e,level:t})))}function mt(n,e,t,i,r,o){const s=n.traceFor({entity:String(e.entity),id:r}),a=gt([...s,{kind:"entity",name:String(e.entity),entityId:r,detail:""}],t,i);return{auditReason:n.comment,tracePath:We(a.tracePath),mutationLineage:s,targetID:r,inheritedBindings:q(o,n.graphSession?.logBindings)}}class $r{constructor(e){this.logger=e}write(e){const t=Vi(e),i=t.executionOutcome??"unknown";this.logger().write(i==="failure"||i==="cancelled"?"ERROR":i==="retrying"?"WARN":"INFO",i==="retrying"?"sql.retry":`sql.${i}`,"TeaQL SQL execution",{category:"SQL",outcome:i,sql:t.debugSQL,comment:t.comment,purpose:t.purpose,audit_reason:t.auditReason,trace_chain:t.traceChain,trace_path:t.tracePath,mutation_lineage:t.mutationLineage,elapsed_us:t.elapsedMicros,result_count:t.resultCount,affected_rows:t.affectedRows,omission_reason:t.omissionReason,trace_id:t.telemetryCorrelation?.traceId})}}class Xr{constructor(){this.mode="all",this.entries=[]}record(e){const t=e.operation==="select";this.mode==="disabled"||this.mode==="select"&&!t||this.mode==="mutation"&&t||this.entries.push(Object.freeze({...e,...e.traceChain?{traceChain:B(e.traceChain)}:{},parameters:Object.freeze([...e.parameters])}))}setMode(e){return this.mode=e,this.entries=[],this}enableAll(){return this.setMode("all")}enableSelect(){return this.setMode("select")}enableMutation(){return this.setMode("mutation")}disable(){return this.setMode("disabled")}snapshot(){return[...this.entries]}}class Nr{constructor(e,t){this.driver=e,this.bootstrapTail=Promise.resolve(),this.sqlTrace=[],this.internalQueryToken=Symbol("teaql-internal-query"),this.bindLogPolicies=new WeakMap,this.bindOperandSources=new WeakMap,this.derivedQueryBindings=new WeakMap,this.derivedRelationAssembly=new WeakMap,this.checkerPrivacyPolicy=(i,r)=>{const o=i?this.schemas[i]:void 0;if(!o)return;const s=Object.keys(o.columns).find(c=>c===r||o.columns[c].modelName===r||o.columns[c].columnName===r)??r,a=this.fieldLogPolicy(o,s);return a==="masked"||a==="credential"?a:void 0},this.auditEvents=[],this.diagnosticSQLLogSink=new $r(()=>this.userContext.runtimeLogger),this.queryLoggingEnabled=!0,this.mutationLoggingEnabled=!0,this.customTelemetry=!1,this.checkers={},this.checkerPresentationModel=te.empty,this.userContext=new rt,this.bootstrap={},this.graphAuditActions=[],this.graphCommitActions=[],this.graphRollbackActions=[],this.graphSaveTail=Promise.resolve(),Gi(t),this.schemas={...t}}fieldLogPolicy(e,t){const i=e.columns[t],r=i?.modelName??i?.columnName??t;return fe(r)||fe(t)?"credential":e.auditMaskFields?e.auditMaskFields?.includes(r)||e.auditMaskFields?.includes(t)?"masked":i?.logPolicy??"unknown":"unknown"}bindValue(e,t,i,r){const o=this.bindLogPolicies.get(e)??e.map(()=>"unknown");e.push(t),o.push(i),this.bindLogPolicies.set(e,o),r!==void 0&&this.bindOperandSources.set(e,q({parameterizedSQL:"",parameters:[r],parameterLogPolicies:[i],sqlOrigin:"generated"},this.bindOperandSources.get(e)))}queryLogBindings(e,t){return q({parameterizedSQL:e,parameters:t,parameterLogPolicies:this.bindLogPolicies.get(t),sqlOrigin:"generated"},this.bindOperandSources.get(t))}install(e){const t=this.checkerPresentationModel.merge(e.checkerPresentationModel);return Object.assign(this.schemas,e.schemas),Object.assign(this.checkers,e.checkers),this.bootstrap=Wi(this.bootstrap,e.bootstrap),this.checkerPresentationModel=t,this}setUserContext(e){return this.userContext=e,this}async reserveInternalId(e,t){if(!(t instanceof rt))throw new TypeError("UserContext is required for ID reservation");if(this.schema(e),this.activeGraph)throw new Error("Internal ID reservation is not allowed inside an active graph save");const i=this.graphSaveTail;let r;this.graphSaveTail=new Promise(o=>{r=o}),await i;try{return await this.driver.transaction(async o=>{const s=jt(await this.driver.nextId(o,e));if(!Number.isSafeInteger(Number(s)))throw new RangeError("SQL internal ID space exhausted its exact integer range");return s})}finally{r()}}schema(e){const t=this.schemas[e];if(!t)throw new Error(`Unknown TeaQL entity: ${e}`);return t}toRuntimeMutationRecord(e,t){const i={};for(const[r,o]of Object.entries(t)){const s=e.columns[r]?r:Object.keys(e.columns).find(a=>e.columns[a].modelName===r||e.columns[a].columnName===r);s&&(i[s]=o)}return i}encode(e,t){const i=e?.id??e;if(i!==void 0){if(this.requireFiniteFloatingPoint(i,t),t?.logicalType==="decimal"&&i!==null){if(t.decode!=="decimal"){if(typeof i=="number"&&(!Number.isFinite(i)||Number.isInteger(i)&&!Number.isSafeInteger(i)))throw new TypeError("Legacy Decimal requires a finite JSON-safe number");return this.driver.encode(i,t)}return this.driver.encode(ue(i),t)}return t?.logicalType==="long"&&i!==null?this.driver.encode(be(i),t):t?.logicalType==="time"&&i!==null?this.driver.encode(Ce(i),t):this.driver.encode(i,t)}}requireFiniteFloatingPoint(e,t){if(!(t?.logicalType!=="double"||e===null||e===void 0)&&(typeof e!="number"||!Number.isFinite(e)))throw new TypeError(`Invalid numeric field ${t.modelName??t.columnName}: expected a finite Float/Double number`)}validateFloatingMutation(e){const t=this.schemas[e.entity];if(!t)return;const i=this.toRuntimeMutationRecord(t,e.payload||{});for(const[r,o]of Object.entries(i))this.requireFiniteFloatingPoint(o,t.columns[r])}decodeRow(e,t,i=[],r){const o=this.schema(e),s={...t},a=new Ge(e,o);for(const[c,u]of Object.entries(o.columns)){if(r&&!Object.prototype.hasOwnProperty.call(r,c))continue;const l=r?.[c]??c;if(i.some(h=>h.name===l))continue;const d=s[l];if(d!=null){if(c==="version"){s[l]=M(d);continue}if(u.decode==="number"&&(s[l]=Number(a.read(c,d))),this.requireFiniteFloatingPoint(s[l],u),u.decode==="string"&&(s[l]=String(d)),u.decode==="decimal"){if(typeof d!="string")throw new TypeError(`Inexact Decimal readback for ${c}`);s[l]=ue(d)}if(u.decode==="long"){if(typeof d!="string"&&typeof d!="bigint")throw new TypeError(`Inexact Long readback for ${c}`);s[l]=be(d)}u.decode==="time"&&(s[l]=Ce(d)),u.decode==="date"&&(d instanceof Date?s[l]=u.logicalType==="date"?d.toISOString().slice(0,10):d.toISOString():u.logicalType==="datetime"&&typeof d=="number"&&(s[l]=new Date(d).toISOString())),u.logicalType==="boolean"&&(s[l]=!!d)}}for(const c of i){const u=s[c.name];if(u!=null)if(c.exactDecimal){if(typeof u!="string")throw new TypeError(`Inexact Decimal aggregate ${c.name}`);s[c.name]=ue(u)}else s[c.name]=Number(u)}return s}get auditTrace(){return[...this.auditEvents]}setAuditSink(e){return this.auditSink=e,this}setRuntimeTelemetrySink(e){return this.telemetrySink=e,this}setDiagnosticSQLLogSink(e){return this.diagnosticSQLLogSink=e,this}setQueryLoggingEnabled(e){return this.queryLoggingEnabled=e,this}setMutationLoggingEnabled(e){return this.mutationLoggingEnabled=e,this}setRuntimeTelemetry(e){return this.customTelemetry=!0,this.runtimeTelemetry=e,this}operationTelemetry(){return tr(this.runtimeTelemetry,this.userContext.runtimeLogger)}attachStandardTelemetryStartup(e){this.telemetryStartup=e.then(async t=>{if(t){if(this.customTelemetry){await t.release();return}this.standardTelemetryHandle=t,this.runtimeTelemetry=t.telemetry}}).catch(()=>{pt("TeaQL telemetry: initialization failed; business continues without export.",!0)})}async flushTelemetry(){await this.telemetryStartup;try{await this.standardTelemetryHandle?.flush()}catch{pt("TeaQL telemetry: export flush failed; business outcome unchanged.",!0)}}async withQueryRequest(e,t){try{new L(e)}catch(i){throw this.userContext.runtimeLogger.write("WARN","query.rejected","TeaQL query rejected",{category:"SQL",outcome:"rejected",error_code:"request_intent"}),i}return await this.telemetryStartup,me(this.operationTelemetry(),{family:"query",name:`${String(e.entity)}.request`,attributes:{"teaql.entity.type":String(e.entity)}},t,i=>Array.isArray(i)?{attributes:{"teaql.result.cardinality":i.length}}:{})}recordSQL(e,t,i,r,o,s,a={},c="success",u,l){const h=e==="select"?this.queryLoggingEnabled:this.mutationLoggingEnabled,{targetID:f,inheritedBindings:p,...m}=a,b=Object.freeze({operation:e,...m,executionOutcome:c,telemetryCorrelation:l?Object.freeze({traceId:l.traceId,spanId:l.spanId}):void 0,traceChain:B(a.traceChain??[]),tracePath:We(a.tracePath??[]),...a.traceChain?{traceChain:B(a.traceChain)}:{},...a.mutationLineage?{mutationLineage:B(a.mutationLineage)}:{},parameterizedSQL:t,parameters:Object.freeze([...i]),debugSQL:"",databaseKind:this.driver.databaseKind,sqlOrigin:"generated",parameterLogPolicies:Object.freeze([...this.bindLogPolicies.get(i)??i.map(()=>"unknown")]),elapsedMicros:Math.max(0,(Date.now()-r)*1e3),resultCount:o,affectedRows:s,resultSummary:o!==void 0?`${o} rows returned`:s!==void 0?`${s} rows affected`:`statement ${c}; row count unknown`}),g=p&&u?q(u,p):p??u,y=this.bindOperandSources.get(i),O=y?q(y,g):g;if(ei(b,O,f===void 0?[]:[f]),this.runtimeTelemetry?.recordDiagnostic)try{this.runtimeTelemetry.recordsSQLDiagnostics?.()!==!1&&this.runtimeTelemetry.recordDiagnostic(kr(lr(b),l))}catch{pt("TeaQL telemetry: SQL diagnostic rejected; business outcome unchanged.",!0)}if(!this.telemetrySink&&!(h&&this.diagnosticSQLLogSink))return b;try{const w=Vi(b);try{this.telemetrySink?.record(w)}catch{}if(h)try{this.diagnosticSQLLogSink?.write(w)}catch{}}catch{}return b}queryLogIntent(e){const t=new L(e),i=gt(t.traceSource,this.driver.databaseKind,"select");return{comment:t.intent.comment,purpose:t.purpose,traceChain:t.traceChain,tracePath:We(i.tracePath)}}async executeLoggedSQL(e,t,i,r,o,s,a){await this.telemetryStartup;const c=H(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.${e}`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.execution":"statement","teaql.provider.operation":e==="select"?"query":e}}),u=c.correlation?.(),l=Date.now();let d;try{d=await(c.run?c.run(o):o())}catch(f){try{const p=this.recordSQL(e,t,i,l,void 0,void 0,r,"failure",s,u);a?.push(p)}finally{throw c.failure(f),f}}const h=this.recordSQL(e,t,i,l,e==="select"?d.rowCount:void 0,e==="select"?void 0:d.rowCount,r,"success",s,u);return a?.push(h),c.success({attributes:{"teaql.result.cardinality":d.rowCount}}),d}async[Di](e){await this.telemetryStartup,this.schemaReady||(this.schemaReady=this.driver.ensureSchema(this.schemas)),await this.schemaReady;const t=this.bootstrapTail;let i;this.bootstrapTail=new Promise(s=>{i=s}),await t,this.userContext=e;const r=e.getResource("bootstrapActor"),o=e.getResource("bootstrapCategory");e.insertResource("bootstrapActor","teaql-generated-bootstrap"),e.insertResource("bootstrapCategory","runtime-bootstrap");try{if(this.bootstrap.ensure){const{runGeneratedBootstrap:s}=await cn(async()=>{const{runGeneratedBootstrap:a}=await import("./entity-creation-Bqaw1C4U.js");return{runGeneratedBootstrap:a}},[]);await s(e,this.bootstrap,()=>this.bootstrap.ensure(e))}else await this.ensureBootstrapData()}finally{r===void 0?e.removeResource("bootstrapActor"):e.insertResource("bootstrapActor",r),o===void 0?e.removeResource("bootstrapCategory"):e.insertResource("bootstrapCategory",o),i()}}invalidateSchemaState(){this.schemaReady=void 0}async ensureBootstrapData(){const e=[...this.bootstrap.defaultDomainRoot?[this.bootstrap.defaultDomainRoot]:[],...this.bootstrap.constants??[]];e.length&&await this.executeGraphSave(new Ie("reconcile model bootstrap data"),async t=>{const i=this.graphMutationSession,r=[];for(const o of e){const s=await this.planBootstrapMutation(i,o);s&&r.push({record:o,request:t.request(s)})}for(const{request:o}of r)this.preflightMutation(o);for(const{request:o}of r)await this.executeMutation(o);for(const o of e)await this.driver.ensureIdFloor(i,o.entity,o.id)})}async planBootstrapMutation(e,t){const i=this.schema(t.entity),r=Object.entries(t.values??{}).map(([p,m])=>{const b=i.columns[p];if(!b)throw new Error(`Unknown bootstrap field ${t.entity}.${p}`);return{column:b.columnName,model:b.modelName??p,original:m,value:this.driver.encode(m,b)}}),o=Object.fromEntries(r.map(p=>[p.model,p.original])),s=new jr(t.entity).filter({id:{$eq:t.id}}).limit(1).comment("inspect model bootstrap record").purpose("ensure model-defined root and constants");s.prepareForList();const a=new L(s),u=`SELECT ${Object.entries(i.columns).map(([p,m])=>this.fieldProjection(p,m,m.columnName)).join(", ")} FROM ${this.driver.identifier(i.table)} WHERE ${this.driver.identifier(i.columns.id?.columnName??"id")} = ${this.driver.placeholder(1)}`,l=[t.id];this.bindLogPolicies.set(l,[this.fieldLogPolicy(i,"id")]);const d=await this.executeLoggedSQL("select",u,l,this.queryLogIntent(a.query),()=>e.query(u,l));if(!d.rowCount)return{entity:t.entity,action:"Create",id:t.id,version:0,payload:o};const h=d.rows[0];if(r.filter(p=>!Cr(h[p.column],p.value)).length)return{entity:t.entity,action:"Update",id:t.id,version:M(h[i.columns.version?.columnName??"version"]),payload:{...Object.fromEntries(Object.entries(this.decodeRowForSchema(i,h)).map(([p,m])=>[i.columns[p]?.modelName??p,m])),...o}}}async executeGraphSave(e,t,i,r){const o=new fr(e),s=this.userContext;o.bindExecutionReference(()=>this.userContext),o.bindExecutionReference(()=>this.checkerPresentationModel),o.bindExecutionMetadata(()=>({schemas:this.schemas,checkerNames:Object.keys(this.checkers).sort()}));for(const c of Object.keys(this.checkers))o.bindExecutionReference(()=>this.checkers[c]),o.bindExecutionReference(()=>this.checkers[c]?.checkAndFix);await this.telemetryStartup;const a=async()=>{const c=this.graphSaveTail;let u;this.graphSaveTail=new Promise(m=>{u=m}),await c;let l=!1,d=!1,h=!1,f,p;try{o.validatePreparedSources(),this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[];const m=r?.(o);if(r&&typeof m!="boolean")throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED");if(p=s.captureCheckerMessages(this.checkerPresentationModel),o.preparedRootEntity&&(f=Object.freeze({model:p.model,entity:o.preparedRootEntity})),o.captureInputSources(),m===!1){o.sealPreparedGraph(),this.activeGraph=o;try{return await t(o)}finally{this.activeGraph=void 0}}s.beginMutationPolicyGraph(),d=!0,s.insertResource("fixTime",s.businessTime()),s.beginFixEvidence(),l=!0,this.activeGraph=o;try{await i?.(o)}finally{this.activeGraph=void 0}if(i&&!o.isPreparedSealed&&o.sealPreparedGraph(),s.prepareMutationPolicyGraph(o.preparedRootEntity),o.validatePreparedSources(),o.isPreparedEmpty){this.activeGraph=o;try{const O=await t(o);o.requirePreparedComplete(),s.ensureMutationPolicyGraphComplete();for(const w of this.graphCommitActions)await w();return h=!0,O}finally{this.activeGraph=void 0}}const b=await this.driver.transaction(async O=>{this.graphMutationSession=O,this.activeGraph=o;try{const w=await t(o);return o.requirePreparedComplete(),s.ensureMutationPolicyGraphComplete(),w}finally{this.graphMutationSession=void 0,this.activeGraph=void 0}});h=!0;let g,y=!1;for(const O of[...this.graphCommitActions,...this.graphAuditActions])try{await O()}catch(w){y||(g=w),y=!0}if(y)throw new ri(g);return b}catch(m){if(!h)for(const b of[...this.graphRollbackActions].reverse())try{b()}catch{}throw m instanceof G&&f&&p&&m.refreshPresentation(s.renderCheckerGraphResults(m.violations,p,f)),m}finally{this.graphCommitActions=[],this.graphRollbackActions=[],this.graphAuditActions=[],d&&s.endMutationPolicyGraph(),l&&s.removeResource("fixTime").finishFixEvidence(),u()}};return me(this.operationTelemetry(),{family:"mutation",name:"graph.save",attributes:{"teaql.entity.type":"graph","teaql.mutation.kind":"graph"}},a)}afterGraphCommit(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphCommitActions.push(e)}afterGraphRollback(e){if(!this.graphMutationSession)throw new Error("No graph save is active");this.graphRollbackActions.push(e)}requireGraphOwnership(e){if(e.graphSession!==this.activeGraph||this.graphMutationSession!==void 0&&e.graphSession===void 0)throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability")}async withMutationSession(e,t){return this.requireGraphOwnership(e),e.graphSession?t(this.graphMutationSession):this.driver.transaction(t)}preflightMutation(e){const t=e instanceof ce?e:new ce(e);this.requireGraphOwnership(t),e=this.checkAndFixMutation(t);const i=t.graphSession?.normalizePreparedMutation(e);if(i?.restore&&(this.graphCommitActions.push(i.restore),this.graphRollbackActions.push(i.restore)),i?.empty)return e;if(t.graphSession?.recordPreparedMutation(),t.graphSession){const o=this.schema(e.entity);t.graphSession.captureLogBindings(this.mutationLogBindings(t,e,o))}const r=t.graphSession?t.graphSession.capturePreparedMutation(t,e,this.preparedReferences(e.entity)):e;return this.userContext.recordMutationPolicyPreflight(r),e}mutationLogBindings(e,t,i){const r=o=>{const s=this.toRuntimeMutationRecord(i,o),a=Object.keys(s);return{parameterizedSQL:"",sqlOrigin:"generated",parameters:a.map(c=>s[c]),parameterLogPolicies:a.map(c=>this.fieldLogPolicy(i,c))}};return q(r(t.payload||{}),r(e.loadedValues()))}checkAndFixMutation(e){const t=e instanceof ce?e:new ce(e);this.requireGraphOwnership(t);const i=t.graphSession?.replayPreparedMutation(t);if(i)return i;e=t.mutation;const r=this.schemas[String(e.entity)];if(r){const d=new Gn(String(e.entity),Object.entries(r.columns).map(([h,f])=>f.modelName??h));if(d.validate(e.payload??{},e.action==="Update"),e.ledgerKey&&e.ledgerRoot){if(e.ledgerKey.entity!==e.entity)throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH");d.validate(e.ledgerRoot.change(e.ledgerKey),e.action==="Update")}}const o=r?this.checkedMutationVersion(e):void 0;e={...e,payload:{...e?.payload??{}}},t.bindCheckerLoadedValues(e),Object.defineProperty(e,"comment",{value:t.comment,enumerable:!0});const s=String(e.entity),a=new Ge(s,r),c=this.checkers[s];if(!c){const d=a.checkMutation(e.payload||{});if(d.length)throw new G(d);return this.validateFloatingMutation(e),this.sealMutationVersion(e,r?o:void 0,!!r)}const u=[],l=this.userContext.getResource("fixTime")===void 0;l&&this.userContext.insertResource("fixTime",this.userContext.businessTime()).beginFixEvidence();try{if(Dt.run(this.userContext,e,r,()=>c.checkAndFix(this.userContext,e,u)),r&&(e.action!==t.mutation.action||this.checkedMutationVersion(e)!==o))throw new X("invalid_type");a.checkMutation(e.payload||{},u);const d=Object.freeze({model:this.userContext.captureCheckerMessages(this.checkerPresentationModel).model,entity:s});if(u.splice(0,u.length,..._i(u,d)),Si(this.userContext,u,s,this.checkerPrivacyPolicy,[t.loadedValues(),t.mutation.payload??{},e.payload??{}]),u.length)throw new G(u);if(this.validateFloatingMutation(e),e.action!=="Delete"&&e.ledgerKey&&e.ledgerRoot){const h=Dt.captureUndo(e,r);t.graphSession&&h&&this.graphRollbackActions.push(h);for(const[f,p]of Object.entries(e.payload||{}))e.ledgerRoot.set(e.ledgerKey,f,p)}return this.sealMutationVersion(e,o,!!r)}finally{l&&this.userContext.removeResource("fixTime").finishFixEvidence()}}preparedReferences(e){const t=this.schemas[e];return Object.fromEntries(Object.values(t?.relations??{}).filter(i=>!i.many).map(i=>[t.columns[i.localKey]?.modelName??i.localKey,i.targetEntity]))}sealMutationVersion(e,t,i){return i&&["Create","Update","Delete","Recover"].includes(e.action)&&Object.defineProperties(e,{version:{value:t,enumerable:!0,writable:!1,configurable:!1},expectedVersion:{value:t,enumerable:e.expectedVersion!==void 0,writable:!1,configurable:!1},action:{value:e.action,enumerable:!0,writable:!1,configurable:!1}}),e}checkedMutationVersion(e){if(e.action==="Create"){ct("Create");return}if(!["Update","Delete","Recover"].includes(e.action))return;const t=e.version!==void 0,i=e.expectedVersion!==void 0;if(!t&&!i){if(e.action==="Recover")throw new X("invalid_type","Recover");return}const r=M(t?e.version:e.expectedVersion);if(t&&i&&r!==M(e.expectedVersion))throw new X("invalid_type");return ct(e.action,r),r}fieldProjection(e,t,i=e){const r=this.driver.identifier(t.columnName);return`${e==="version"?`CAST(${r} AS ${this.driver.databaseKind==="mysql"?"CHAR":"TEXT"})`:r} AS ${this.driver.identifier(i)}`}async executeMutation(e){await this.telemetryStartup;const t=e instanceof ce?e:new ce(e);if(this.requireGraphOwnership(t),t.graphSession?.requireMutationAllowed(),this.activeGraph&&!this.graphMutationSession)throw new Error("Graph preparation cannot execute mutations before its transaction");e=t.mutation;const i=H(this.operationTelemetry(),{family:"mutation",name:`${String(e?.entity||"unknown")}.${String(e?.action||"unknown").toLowerCase()}`,attributes:{"teaql.entity.type":String(e?.entity||"unknown"),"teaql.mutation.kind":String(e?.action||"unknown").toLowerCase()}}),r=async()=>{try{e=this.checkAndFixMutation(t);const o=this.userContext.enterMutationPolicy(e),s=this.schema(e.entity),a=this.toRuntimeMutationRecord(s,e.payload||{}),c=this.mutationLogBindings(t,e,s),u=this.driver.identifier(s.table),l=[],d=await me(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.mutation`,attributes:{"teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":String(e.action).toLowerCase()}},()=>this.withMutationSession(t,async b=>{if(e.action==="Create"){const g=e.id?String(e.id):await this.driver.nextId(b,e.entity);e.id&&await this.driver.ensureIdFloor(b,e.entity,g);const y=ct("Create"),O={...a,id:g,version:y},w=Object.keys(s.columns).filter(v=>O[v]!==void 0),E=w.map(v=>this.driver.identifier(s.columns[v].columnName)).join(", "),k=w.map((v,S)=>this.driver.placeholder(S+1)).join(", "),j=w.map(v=>this.encode(O[v],s.columns[v]));this.bindLogPolicies.set(j,w.map(v=>this.fieldLogPolicy(s,v)));const T=`INSERT INTO ${u} (${E}) VALUES (${k})`,R=mt(t,e,this.driver.databaseKind,"insert",g,c);return await this.executeLoggedSQL("insert",T,j,R,()=>b.query(T,j),void 0,l),{success:!0,id:g,version:y,persistedRecord:await this.readPersistedRecord(b,s,g,R,T,j,l)}}if(e.action==="Update"){const g=Object.keys(s.columns).filter(S=>S!=="id"&&S!=="version"&&a[S]!==void 0),y=g.map(S=>this.encode(a[S],s.columns[S]));this.bindLogPolicies.set(y,g.map(S=>this.fieldLogPolicy(s,S)));const O=g.map((S,_)=>`${this.driver.identifier(s.columns[S].columnName)} = `+this.driver.placeholder(_+1)),w=this.driver.identifier("version");O.push(`${w} = ${w} + 1`),this.bindValue(y,String(e.id),this.fieldLogPolicy(s,"id"));const E=[`${this.driver.identifier("id")} = ${this.driver.placeholder(y.length)}`],k=this.checkedMutationVersion(e);E.push(`${w} > 0`,`${w} < 9223372036854775807`),k!==void 0&&(this.bindValue(y,k,this.fieldLogPolicy(s,"version")),E.push(`${w} = ${this.driver.placeholder(y.length)}`));const j=`UPDATE ${u} SET ${O.join(", ")} WHERE ${E.join(" AND ")}`,T=mt(t,e,this.driver.databaseKind,"update",String(e.id),c);if((await this.executeLoggedSQL("update",j,y,T,()=>b.query(j,y),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const v=await this.readPersistedRecord(b,s,String(e.id),T,j,y,l);return{success:!0,id:String(e.id),version:M(v.version),persistedRecord:v}}if(e.action==="Delete"||e.action==="Recover"){const g=this.driver.identifier("version"),y=[String(e.id)];this.bindLogPolicies.set(y,[this.fieldLogPolicy(s,"id")]);const O=[`${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`],w=this.checkedMutationVersion(e),E=e.action==="Recover";O.push(`${g} ${E?"<":">"} 0`),w!==void 0&&(this.bindValue(y,w,this.fieldLogPolicy(s,"version")),O.push(`${this.driver.identifier("version")} = `+this.driver.placeholder(y.length)));const k=`UPDATE ${u} SET ${g} = -${g} ${E?"+":"-"} 1 WHERE ${O.join(" AND ")}`,j=E?"update":"delete",T=mt(t,e,this.driver.databaseKind,j,String(e.id),c);if((await this.executeLoggedSQL(j,k,y,T,()=>b.query(k,y),void 0,l)).rowCount!==1)throw new Error(`Optimistic lock failed or ${e.entity}(${e.id}) does not exist`);const v=await this.readPersistedRecord(b,s,String(e.id),T,k,y,l);return{success:!0,id:String(e.id),version:M(v.version),deleted:!E,persistedRecord:v}}throw new Error(`Unsupported mutation action: ${e.action}`)}));t.graphSession?.recordPreparedResult(t,d);const h=t.auditProjection({entity:String(e.entity),id:d.id},e.payload,c),f=Object.freeze({entity:e.entity,action:e.action,id:String(d.id),...h,recordedAt:new Date().toISOString(),actor:this.userContext.getResource("bootstrapActor"),category:this.userContext.getResource("bootstrapCategory"),changedFields:Object.freeze(Object.keys(e.payload||{}).sort()),version:d.version,mutationGovernance:o}),p=async()=>{this.auditEvents.push(f),this.userContext.runtimeLogger.write("INFO","audit.event","TeaQL audit event",{category:"AUDIT",outcome:"success",audit:f}),this.auditSink&&await me(this.operationTelemetry(),{family:"audit",name:`${e.entity}.audit`,attributes:{"teaql.entity.type":String(e.entity),"teaql.mutation.kind":String(e.action).toLowerCase(),"teaql.audit.changed_field_count":Object.keys(e.payload||{}).length}},async()=>this.auditSink(f))};if(t.graphSession)this.graphAuditActions.push(p);else try{await p()}catch(b){throw new ri(b)}i.success();const m=Object.freeze({...l[0],statements:Object.freeze([...l])});return ei(m,q(c,t.graphSession?.logBindings),[d.id]),{...d,metadata:m}}catch(o){throw i.failure(o),o}};return i.run?i.run(r):r()}async readPersistedRecord(e,t,i,r,o,s,a){const u=`SELECT ${Object.entries(t.columns).map(([w,E])=>this.fieldProjection(w,E)).join(", ")} FROM ${this.driver.identifier(t.table)} WHERE ${this.driver.identifier("id")} = ${this.driver.placeholder(1)}`,l=[i];this.bindLogPolicies.set(l,[this.fieldLogPolicy(t,"id")]);const d=H(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.readback`,attributes:{"teaql.provider.execution":"statement","teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}}),h=Date.now();let f;const p={parameterizedSQL:o,parameters:s,parameterLogPolicies:this.bindLogPolicies.get(s),sqlOrigin:"generated"},m=r.tracePath?.find(w=>w.kind==="operation")?.name??"unknown",b=gt([...mi(m,r.auditReason,"verify persisted mutation result"),...(r.tracePath??[]).filter(w=>w.kind==="relation")],this.driver.databaseKind,"select"),g={...r,tracePath:We(b.tracePath),comment:r.auditReason,purpose:"verify persisted mutation result"},y=w=>a.push(this.recordSQL("select",u,l,h,f?.rowCount,void 0,g,w,p,d.correlation?.()));let O;try{if(f=await(d.run?d.run(()=>e.query(u,l)):e.query(u,l)),d.success({attributes:{"teaql.result.cardinality":f.rowCount}}),f.rowCount!==1)throw new Error(`Persisted ${t.table}(${i}) could not be read back`);O=this.decodeRowForSchema(t,f.rows[0])}catch(w){f||d.failure(w);const E=f?"success":w instanceof Error&&(w.name==="AbortError"||w.name==="TimeoutError")?"cancelled":"failure";try{y(E)}finally{throw w}}return y("success"),O}decodeRowForSchema(e,t){const i={...t},r=Object.keys(this.schemas).find(s=>this.schemas[s]===e)??"Unknown",o=new Ge(r,e);for(const[s,a]of Object.entries(e.columns)){const c=i[s];if(c!=null){if(s==="version"){i[s]=M(c);continue}if(a.decode==="number"&&(i[s]=Number(o.read(s,c))),this.requireFiniteFloatingPoint(i[s],a),a.decode==="string"&&(i[s]=String(c)),a.decode==="decimal"){if(typeof c!="string")throw new TypeError(`Inexact Decimal readback for ${s}`);i[s]=ue(c)}if(a.decode==="long"){if(typeof c!="string"&&typeof c!="bigint")throw new TypeError(`Inexact Long readback for ${s}`);i[s]=be(c)}a.decode==="time"&&(i[s]=Ce(c)),a.decode==="date"&&(c instanceof Date?i[s]=a.logicalType==="date"?c.toISOString().slice(0,10):c.toISOString():a.logicalType==="datetime"&&typeof c=="number"&&(i[s]=new Date(c).toISOString())),a.logicalType==="boolean"&&(i[s]=!!c)}}return i}comparisonSql(e,t,i,r){if(e.logicalType!=="decimal"&&e.logicalType!=="long")return`${t} ${i} ${r}`;if(e.logicalType==="decimal"&&e.decode!=="decimal")return`${t} ${i} ${r}`;const o=e.logicalType==="long"?this.driver.longComparison:this.driver.decimalComparison;if(o)return o.call(this.driver,t,i,r);if(this.driver.databaseKind==="sqlite")throw new Error(`EXACT_${e.logicalType.toUpperCase()}_UNSUPPORTED: this SQLite provider has no exact comparison`);return`${t} ${i} ${r}`}compileExpression(e,t,i){if(Array.isArray(e?.$and))return`(${e.$and.map(s=>this.compileExpression(s,t,i)).join(" AND ")})`;const r=Object.entries(e||{}).map(([o,s])=>{const a=t.columns[o];if(!a)throw new Error(`Unknown field ${o} for SQL query`);const c=this.driver.identifier(a.columnName),u=this.fieldLogPolicy(t,o);if(s?.$eq!==void 0){const l=s.$eq?.id??s.$eq;return l===null?`${c} IS NULL`:(this.bindValue(i,this.encode(l,a),u),this.comparisonSql(a,c,"=",this.driver.placeholder(i.length)))}if(s?.$ne!==void 0){const l=s.$ne?.id??s.$ne;return l===null?`${c} IS NOT NULL`:(this.bindValue(i,this.encode(l,a),u),this.comparisonSql(a,c,"<>",this.driver.placeholder(i.length)))}if(s?.$soundLike!==void 0)return this.bindValue(i,String(s.$soundLike),u),`SOUNDEX(${c}) = SOUNDEX(${this.driver.placeholder(i.length)})`;if(s?.$contains!==void 0)return this.bindValue(i,String(s.$contains),u),this.driver.contains(c,this.driver.placeholder(i.length));if(s?.$notContains!==void 0)return this.bindValue(i,String(s.$notContains),u),`NOT (${this.driver.contains(c,this.driver.placeholder(i.length))})`;for(const[l,d,h,f]of[["$startsWith","","%",!1],["$notStartsWith","","%",!0],["$endsWith","%","",!1],["$notEndsWith","%","",!0]])if(s?.[l]!==void 0){const p=String(s[l]);this.bindValue(i,`${d}${p}${h}`,u,p);const m=`${c} LIKE ${this.driver.placeholder(i.length)}`;return f?`NOT (${m})`:m}if(Array.isArray(s?.$in)){if(!s.$in.length)return"FALSE";const l=s.$in.map(d=>(this.bindValue(i,this.encode(d?.id??d,a),u),this.driver.placeholder(i.length)));return a.logicalType==="decimal"||a.logicalType==="long"?`(${l.map(d=>this.comparisonSql(a,c,"=",d)).join(" OR ")})`:`${c} IN (${l.join(", ")})`}if(Array.isArray(s?.$notIn)){if(!s.$notIn.length)return"TRUE";const l=s.$notIn.map(d=>(this.bindValue(i,this.encode(d?.id??d,a),u),this.driver.placeholder(i.length)));return a.logicalType==="decimal"||a.logicalType==="long"?`(${l.map(d=>this.comparisonSql(a,c,"<>",d)).join(" AND ")})`:`${c} NOT IN (${l.join(", ")})`}for(const[l,d]of[["$inSubquery",!1],["$notInSubquery",!0]]){const h=s?.[l];if(h!==void 0){if((a.logicalType==="decimal"&&a.decode==="decimal"||a.logicalType==="long")&&this.driver.databaseKind==="sqlite")throw new Error(`EXACT_${a.logicalType.toUpperCase()}_UNSUPPORTED: subquery membership needs an exact join`);const f=h.query,p=this.schema(f?.entity),m=String(h.field),b=p.columns[m];if(!b)throw new Error(`Unknown subquery projection ${m} for ${f?.entity}`);const g=this.filters(f).map(w=>this.compileExpression(w,p,i));p.columns.version&&g.push(`${this.driver.identifier(p.columns.version.columnName)} > 0`),d&&g.push(`${this.driver.identifier(b.columnName)} IS NOT NULL`);const y=g.length?` WHERE ${g.join(" AND ")}`:"",O=`SELECT ${this.driver.identifier(b.columnName)} FROM ${this.driver.identifier(p.table)}${y}`;return`${c} ${d?"NOT IN":"IN"} (${O})`}}if(Array.isArray(s?.$between)&&s.$between.length===2){this.bindValue(i,this.encode(s.$between[0],a),u);const l=this.driver.placeholder(i.length);this.bindValue(i,this.encode(s.$between[1],a),u);const d=this.driver.placeholder(i.length);return a.logicalType==="decimal"||a.logicalType==="long"?`(${this.comparisonSql(a,c,">=",l)} AND ${this.comparisonSql(a,c,"<=",d)})`:`${c} BETWEEN ${l} AND ${d}`}if(s?.$isNull===!0)return`${c} IS NULL`;if(s?.$isNull===!1)return`${c} IS NOT NULL`;if(s?.$gte!==void 0)return this.bindValue(i,this.encode(s.$gte,a),u),this.comparisonSql(a,c,">=",this.driver.placeholder(i.length));if(s?.$lte!==void 0)return this.bindValue(i,this.encode(s.$lte,a),u),this.comparisonSql(a,c,"<=",this.driver.placeholder(i.length));if(s?.$gt!==void 0)return this.bindValue(i,this.encode(s.$gt,a),u),this.comparisonSql(a,c,">",this.driver.placeholder(i.length));if(s?.$lt!==void 0)return this.bindValue(i,this.encode(s.$lt,a),u),this.comparisonSql(a,c,"<",this.driver.placeholder(i.length));throw new Error(`Unsupported query predicate for ${o}: ${JSON.stringify(s)}`)});return r.length?`(${r.join(" AND ")})`:"TRUE"}filters(e){return Array.isArray(e._filters)&&e._filters.length?e._filters:e.filterCondition?[e.filterCondition]:[]}groupBy(e){return e._groupBy||e.groupByItems||[]}aggregates(e){return Array.isArray(e._aggregates)?e._aggregates:(e.aggregateItems||[]).map(t=>({func:t.function,field:t.field,retName:t.alias}))}orders(e){return Array.isArray(e._orderBy)?e._orderBy.map(t=>({field:t.f,direction:t.d})):(e.orderItems||[]).map(t=>({field:t.field,direction:t.direction}))}async compileQuery(e,t=!0,i=[]){new it(e?.commentText??e?._comment,e?.purposeText??e?._purpose);const r=this.schema(e.entity),o=[],s=[...new Set(this.groupBy(e))],a=this.aggregates(e),c=e.groupByAliases;if(c!==void 0){if(c===null||typeof c!="object"||Array.isArray(c))throw new Error("Invalid group aliases");for(const[v,S]of Object.entries(c)){if(!s.includes(v))throw new Error("Group alias refers to an ungrouped field");if(typeof S!="string"||!S.trim())throw new Error("Group alias must be a non-empty string")}}const u=a.length||s.length?Object.fromEntries(s.map(v=>[v,c&&Object.prototype.hasOwnProperty.call(c,v)?c[v]:v])):void 0,l=[...Object.values(u??{}),...a.map(v=>v.retName)],d=new Set;for(const v of l){if(this.driver.identifier(v),d.has(v))throw new Error("Duplicate grouped or aggregate output alias");d.add(v)}const h=s.map(v=>{if(!r.columns[v])throw new Error(`Unknown group field: ${v}`);const S=r.columns[v],_=this.driver.identifier(S.columnName);if(S.logicalType==="decimal"&&S.decode!=="decimal")return _;if((S.logicalType==="decimal"||S.logicalType==="long")&&this.driver.databaseKind==="sqlite"){const z=S.logicalType==="long"?this.driver.longOrderExpression:this.driver.decimalOrderExpression;if(z)return z.call(this.driver,_);throw new Error(`EXACT_${S.logicalType.toUpperCase()}_UNSUPPORTED: grouping`)}return _}),f=s.map(v=>`${this.driver.identifier(r.columns[v].columnName)} AS `+this.driver.identifier(u[v])),p=[],m=Array.isArray(e.selectItems)&&e.selectItems.length?[...new Set(["id","version",...e.selectItems])]:Object.keys(r.columns);if(!s.length&&!this.aggregates(e).length){for(const S of i)m.includes(S)||m.push(S);const v=[...(e.relations??[]).map(S=>S.name),...(e.relationAggregates??[]).map(S=>S.relationName)];for(const S of v){const _=r.relations?.[S];if(!_)throw new Error(`Missing relation ${e.entity}.${S}`);m.includes(_.localKey)||m.push(_.localKey)}}for(const v of m)if(!r.columns[v])throw new Error(`Unknown selected field: ${v}`);let b=m.map(v=>{const S=r.columns[v];return this.fieldProjection(v,S)}).join(", ");if(a.length||s.length){const v=a.map(S=>{if(!r.columns[S.field])throw new Error(`Unknown aggregate field: ${S.field}`);const _=r.columns[S.field];if(_.logicalType==="long"&&String(S.func).toLowerCase()!=="count")throw new Error("EXACT_LONG_AGGREGATION_UNSUPPORTED: define overflow and result type first");const z=_.logicalType==="decimal"&&_.decode==="decimal"&&String(S.func).toLowerCase()!=="count";p.push({name:S.retName,exactDecimal:z});const ae=z&&this.driver.databaseKind==="sqlite"?this.driver.decimalAggregateFunction?.(S.func):this.driver.aggregateFunction(S.func);if(!ae)throw new Error("EXACT_DECIMAL_UNSUPPORTED: decimal aggregation");return`${ae}(${this.driver.identifier(r.columns[S.field].columnName)}) AS `+this.driver.identifier(S.retName)});b=[...f,...v].join(", ")}const g=e.__teaqlPartitionBy,y=this.orders(e),O=y.map(v=>{if(!r.columns[v.field])throw new Error(`Unknown order field: ${v.field}`);const S=String(v.direction).toLowerCase()==="desc"?"DESC":"ASC",_=r.columns[v.field];let z=this.driver.identifier(_.columnName);if(_.logicalType==="decimal"&&_.decode!=="decimal")return`${z} ${S}`;if((_.logicalType==="decimal"||_.logicalType==="long")&&this.driver.databaseKind==="sqlite"){const ae=_.logicalType==="long"?this.driver.longOrderExpression:this.driver.decimalOrderExpression;if(ae)z=ae.call(this.driver,z);else throw new Error(`EXACT_${_.logicalType.toUpperCase()}_UNSUPPORTED: ordering`)}return`${z} ${S}`});if(g){const v=r.columns[g];if(!v)throw new Error(`Unknown partition field: ${g}`);const S=O.length?` ORDER BY ${O.join(", ")}`:"";b+=`, ROW_NUMBER() OVER (PARTITION BY ${this.driver.identifier(v.columnName)}${S}) AS `+this.driver.identifier("__teaql_partition_rank")}let w=`SELECT ${b} FROM ${this.driver.identifier(r.table)}`;const k=this.filters(e).map(v=>this.compileExpression(v,r,o)),j=e.deletionVisibility??"live";if(!["live","all","deleted"].includes(j))throw new Error("QUERY_INVALID_DELETION_VISIBILITY");r.columns.version&&j!=="all"&&k.push(`${this.driver.identifier(r.columns.version.columnName)} ${j==="deleted"?"<":">"} 0`),k.length&&(w+=` WHERE ${k.join(" AND ")}`),h.length&&(w+=` GROUP BY ${h.join(", ")}`);const T=e._limit!==void 0?Number(e._limit):Number(e.limitValue||0),R=e._offset!==void 0?Number(e._offset):Number(e.offsetValue||0);if(g){const v=this.driver.identifier("__teaql_partition_rank"),S=[];this.bindValue(o,R,"plain"),S.push(`${v} > ${this.driver.placeholder(o.length)}`),T>0&&(this.bindValue(o,R+T,"plain"),S.push(`${v} <= ${this.driver.placeholder(o.length)}`)),w=`SELECT * FROM (${w}) AS ${this.driver.identifier("__teaql_partitioned")} WHERE ${S.join(" AND ")} ORDER BY ${v}`}else y.length&&(w+=` ORDER BY ${O.join(", ")}`);return!g&&T>0&&(this.bindValue(o,T,"plain"),w+=` LIMIT ${this.driver.placeholder(o.length)}`),!g&&R>0&&(this.bindValue(o,R,"plain"),w+=` OFFSET ${this.driver.placeholder(o.length)}`),t&&this.sqlTrace.push(w),{sql:w,values:o,aggregateNames:p,groupAliases:u}}async executeQuery(e){const t=e instanceof L?e:new L(e);return!t.parentRequest&&!(e instanceof L)&&e?.[this.internalQueryToken]!==!0&&typeof e?.prepareForList=="function"&&e.prepareForList(),this.executeQueryWithIntent(t.query,this.derivedQueryBindings.get(e),this.derivedRelationAssembly.get(e))}async executeDerivedQuery(e,t,i,r){const o=new L(e,i).query;t&&this.derivedQueryBindings.set(o,t),r&&this.derivedRelationAssembly.set(o,r);try{return await this.executeQuery(o)}finally{this.derivedQueryBindings.delete(o),this.derivedRelationAssembly.delete(o)}}descendantBindings(e,t,i,r){if(!(!e.relations?.length&&!e.relationAggregates?.length))return q(this.queryLogBindings(t,i),r)}async queryTreeBindings(e,t,i,r){let o=q(this.queryLogBindings(t,i),r);const s=new L(e).intent,a=[e],c=new Set;for(;a.length;){const u=a.pop();if(!u||c.has(u))continue;if(c.add(u),u!==e){const d=await this.compileQuery(new L(u,s).query,!1);o=q(this.queryLogBindings(d.sql,d.values),o)}const l=mn(u);l&&a.push(l);for(const d of[...u.relations??[],...u.relationAggregates??[]])d.query&&a.push(d.query);for(const d of u.facets??[]){if(!d.query)continue;const h=d.query.clone();h.aggregateItems=[],h.groupByItems=[],h.groupByAliases=void 0,a.push(h)}}return o}async executeQueryWithIntent(e,t,i){await this.telemetryStartup;const r=H(this.operationTelemetry(),{family:"query",name:`${String(e?.entity||"unknown")}.list`,attributes:{"teaql.entity.type":String(e?.entity||"unknown")}}),o=async()=>{try{const s=e?.[this.internalQueryToken]===!0||new L(e).parentRequest!==void 0;if(!s){if(typeof e?.prepareForList!="function")throw new Error("TeaQL list execution requires the formal runtime SelectQuery");e.prepareForList()}const a=s?{query:e,execution:void 0}:await this.prepareIdSetPage(e,t),c=s?a:await this.prepareContinuousPage(a.query);e=new L(e).withQuery(c.query).query;const{sql:u,values:l,aggregateNames:d,groupAliases:h}=await this.compileQuery(e,!0,i?[i.field]:[]);t=await this.queryTreeBindings(e,u,l,t);const p=(await this.executeLoggedSQL("select",u,l,this.queryLogIntent(e),()=>this.driver.query(u,l),t)).rows.map(b=>this.decodeRow(e.entity,b,d,h));if(a.execution?.pageIds){const b=new Map(a.execution.pageIds.map((g,y)=>[String(g),y]));p.sort((g,y)=>(b.get(String(g.id))??Number.MAX_SAFE_INTEGER)-(b.get(String(y.id))??Number.MAX_SAFE_INTEGER))}const m=this.descendantBindings(e,u,l,t);if(i)for(const b of p)i.keys.set(b,b[i.field]);if(await this.enhanceQueryRows(p,e,m),i&&Array.isArray(e.selectItems)&&e.selectItems.length&&!["id","version",...e.selectItems,...this.groupBy(e)].includes(i.field)){const b=this.schema(e.entity);if(![...(e.relations??[]).map(y=>y.name),...(e.relationAggregates??[]).map(y=>y.relationName)].some(y=>b.relations?.[y]?.localKey===i.field))for(const y of p)delete y[i.field]}return s||await this.registerContinuousPage(e,c.execution,p),r.success({attributes:{"teaql.result.cardinality":p.length}}),p}catch(s){throw r.failure(s),s}};return r.run?r.run(o):o()}async prepareIdSetPage(e,t){const i=e.localIdSetPaginationOptions?.(),r=e.localIdSetPaginationRuntime?.();if(!i||!r)return r?.observe("ID_SET_DISABLED"),{query:e};const o=this.queryLimit(e);if(!o||e.localContinuousPageOptions?.()||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return r.observe("ID_SET_FALLBACK_UNSUPPORTED_SHAPE"),{query:e};if((e.orderItems||[]).some(m=>m.expr!=null))return r.observe("ID_SET_FALLBACK_NON_DETERMINISTIC_ORDER"),{query:e};this.orders(e).some(m=>m.field==="id")||(e=e.clone().order(Y.asc("id")));const s=e.clone();s.offsetValue=0,s.limitValue=0,s.selectItems=[],s.relations=[],s.commentText=void 0,s.purposeText=void 0,s.clearIdSetPaginationRuntime(),s.clearContinuousPageRuntime();const a=`${i.namespace}|${r.scope}|${JSON.stringify(s)}`;let c=2166136261;for(let m=0;m>>0).toString(16)}`;let l,d=!1;try{l=r.get(u)}catch{return r.observe("ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l)d=!0,r.observe("ID_SET_HIT",l.ids.length);else{let m;try{m=await r.build(u,async()=>{const b=r.get(u);if(b)return b;const g=e.clone();g.selectItems=["id"],g.relations=[],g.relationAggregates=[],g.facets=[],g.offsetValue=0,g.limitValue=i.maxIds+1,g.clearIdSetPaginationRuntime(),g.clearContinuousPageRuntime(),g[this.internalQueryToken]=!0;const y=new L(e).deriveHelper(g,`collect ${e.entity} IDs for pagination`),O=await this.compileQuery(e,!1),w=await this.queryTreeBindings(e,O.sql,O.values,t),E=await this.executeDerivedQuery(y.query,w,y.intent);if(E.length>i.maxIds)return;let k;try{k=BigUint64Array.from(E.map(T=>BigInt(T.id)))}catch{throw new Error("ID_SET_UNSUPPORTED_ID")}const j={ids:k,expiresAt:Date.now()+i.ttlSeconds*1e3};return r.put(u,j),j})}catch(b){return r.observe(b instanceof Error&&b.message==="ID_SET_UNSUPPORTED_ID"?"ID_SET_FALLBACK_UNSUPPORTED_SHAPE":"ID_SET_FALLBACK_STORE_UNAVAILABLE"),{query:e}}if(l=m.value,!l)return r.observe("ID_SET_FALLBACK_LIMIT_EXCEEDED",i.maxIds+1),{query:e};d=!m.built,r.observe(d?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length)}const h=Number(e.offsetValue||e._offset||0),f=Array.from(l.ids.slice(h,h+o)),p=e.clone();return p.offsetValue=0,p.limitValue=Math.max(f.length,1),p.filterCondition=p.filterCondition?{$and:[p.filterCondition,{id:{$in:f}}]}:{id:{$in:f}},p.clearIdSetPaginationRuntime(),r.observe(d?"ID_SET_HIT":"ID_SET_BUILD",l.ids.length),{query:p,execution:{pageIds:f,totalCount:l.ids.length}}}async executeFacetMembership(e,t,i=[]){const r=await this.executeFacetAggregates(e,t,[{function:"Count",field:"id",alias:"__teaql_facet_count"}]);return new Map([...r].map(([o,s])=>[o,Number(s.__teaql_facet_count??0)]))}async executeFacetAggregates(e,t,i){const r=new L(e);e=r.query;const o=r.withQuery(e.clone()).query;je(e,o),o.facets=[],o.relations=[],o.relationAggregates=[],o.orderItems=[],o.offsetValue=0,o.limitValue=0,o.selectItems=[],o.groupByItems=[t],o.groupByAliases=void 0,o.aggregateItems=i.map(a=>({...a})),o[this.internalQueryToken]=!0;const s=await this.executeQuery(o);return new Map(s.flatMap(a=>{const c=a[t];if(c==null)return[];const u={};for(const l of i)u[l.alias]=a[l.alias];return[[String(c),u]]}))}async executeCount(e,t,i){const r=e instanceof L?e:new L(e);if(e=r.query,typeof e?.forExactCount!="function")throw new Error("TeaQL exact count requires the formal runtime SelectQuery");const o=t??"__teaql_total",s=r.deriveOperation(e.forExactCount(o),i??{kind:"named-count",...t!==void 0?{alias:t}:{}}),a=await this.executeQuery(s.query),c=a[0]?.[o];if(a.length!==1||typeof c!="number"||!Number.isSafeInteger(c)||c<0)throw new Error(`TeaQL provider did not return exact count alias ${o}`);return c}async prepareContinuousPage(e){const t=e.localContinuousPageOptions?.(),i=e.localContinuousPageRuntime?.();if(!t||!i)return i?.observe("DISABLED"),{query:e};const r=this.orders(e),o=this.queryLimit(e);if(!o||r.length!==1||r[0].field!=="id"||this.aggregates(e).length||this.groupBy(e).length||e.__teaqlPartitionBy)return i.observe("OFFSET_FALLBACK:UNSUPPORTED_QUERY_SHAPE"),{query:e};const s=Object.assign(Object.create(Object.getPrototypeOf(e)),e);s.orderItems=[...e.orderItems||[]],s.relations=[...e.relations||[]],Object.defineProperty(s,"continuousPageFetchOptions",{enumerable:!1,writable:!0,value:t}),Object.defineProperty(s,"continuousPageRuntimeContext",{enumerable:!1,writable:!0,value:i});const a=Number(e.offsetValue||e._offset||0),c={...JSON.parse(JSON.stringify(s)),offsetValue:0,_offset:0,commentText:void 0,purposeText:void 0},u=`${t.namespace}|${i.owner}|${JSON.stringify(c)}`;let l=2166136261;for(let m=0;m>>0).toString(16)}`,h={queryKey:d,offset:a,limit:o,direction:String(r[0].direction).toLowerCase(),ttlSeconds:t.ttlSeconds,runtime:i,optimized:!1};if(a===0)return i.observe("OFFSET_FALLBACK:FIRST_PAGE"),{query:s,execution:h};let f;try{f=await me(this.operationTelemetry(),{family:"cache",name:"continuous_page.get",attributes:{"teaql.cache.operation":"get"}},()=>i.get(d,a))}catch{return i.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE"),{query:s,execution:h}}if(!f)return i.observe("OFFSET_FALLBACK:CACHE_MISS"),{query:s,execution:h};const p={id:{[h.direction==="desc"?"$lt":"$gt"]:f.boundary}};return s.filterCondition=s.filterCondition?{$and:[s.filterCondition,p]}:p,s.offsetValue=0,s._offset!==void 0&&(s._offset=0),h.optimized=!0,h.cursorId=f.cursorId,i.observe("CURSOR_SEEK",f.cursorId),{query:s,execution:h}}async registerContinuousPage(e,t,i){if(!(!t||i.length!==t.limit||!i.length||i[i.length-1].id===void 0)){try{await me(this.operationTelemetry(),{family:"cache",name:"continuous_page.put",attributes:{"teaql.cache.operation":"put"}},()=>t.runtime.put(t.queryKey,t.offset+i.length,{cursorId:`cpg_${Date.now().toString(16)}_${Math.random().toString(16).slice(2)}`,boundary:i[i.length-1].id,expiresAt:Date.now()+t.ttlSeconds*1e3}))}catch{t.runtime.observe("OFFSET_FALLBACK:STORE_UNAVAILABLE");return}t.optimized&&t.runtime.observe("CURSOR_SEEK",t.cursorId)}}executeForStream(e,t=1e3){try{const i=e instanceof L?new L(e.query,e.intent):new L(e);return this.executeCapturedStream(i.query,t)}catch(i){return(async function*(){throw i})()}}async*executeCapturedStream(e,t){if(await this.telemetryStartup,!Number.isInteger(t)||t<=0)throw new Error("stream chunk size must be a positive integer");if(Array.isArray(e.facets)&&e.facets.length>0)throw new Error("QRY-F01_STREAM_UNSUPPORTED: execute facets with executeForList");const{sql:i,values:r,aggregateNames:o,groupAliases:s}=await this.compileQuery(e),a=await this.queryTreeBindings(e,i,r),c=H(this.operationTelemetry(),{family:"query",name:`${String(e.entity)}.stream`,attributes:{"teaql.entity.type":String(e.entity)}});let u;const l=async()=>{u=H(this.operationTelemetry(),{family:"provider",name:`${this.driver.databaseKind}.stream`,attributes:{"teaql.provider.execution":"statement","teaql.provider.kind":this.driver.databaseKind,"teaql.provider.operation":"query"}})};await(c.run?c.run(l):l());const d=u.correlation?.(),h=this.driver.stream(i,r)[Symbol.asyncIterator](),f=Date.now();let p="cancelled",m=0,b=[];const g=this.descendantBindings(e,i,r,a);try{for(;;){const y=await(u.run?u.run(()=>h.next()):h.next());if(y.done)break;b.push(this.decodeRow(e.entity,y.value,o,s)),b.length===t&&(await this.enhanceQueryRows(b,e,g),m+=b.length,yield b,b=[])}b.length&&(await this.enhanceQueryRows(b,e,g),m+=b.length,yield b),p="success"}catch(y){throw p="failure",u.failure(y),c.failure(y),y}finally{try{await h.return?.()}catch(y){if(p!=="failure")throw p="failure",u.failure(y),c.failure(y),y}finally{if(p==="failure")try{this.recordSQL("select",i,r,f,m,void 0,this.queryLogIntent(e),p,a,d)}catch{}else this.recordSQL("select",i,r,f,m,void 0,this.queryLogIntent(e),p,a,d),u.success({attributes:{"teaql.result.cardinality":m}}),c.success({attributes:{"teaql.result.cardinality":m}})}}}async enhanceQueryRows(e,t,i){if(!e.length)return;const r=[...(t.relations??[]).map(a=>a.name),...(t.relationAggregates??[]).map(a=>a.relationName)];if(!r.length)return;const o=this.schema(t.entity),s=new Map;for(const a of r){const c=o.relations?.[a];if(!c)throw new Error(`Missing relation ${t.entity}.${a}`);s.has(c.localKey)||s.set(c.localKey,e.map(u=>u[c.localKey]))}await this.enhanceRelationAggregates(e,t,s,i),await this.enhanceRelations(e,t,s,i)}async enhanceRelations(e,t,i,r){if(!e.length||!Array.isArray(t.relations)||!t.relations.length)return;const o=this.schema(t.entity),s=new L(t).intent;for(const a of t.relations){const c=o.relations?.[a.name];if(!c)throw new Error(`Missing relation ${t.entity}.${a.name}`);const u=i.get(c.localKey),l=u.filter(w=>w!=null),d=a.query?this.queryLimit(a.query):void 0,h=a.query?.localTopNProbeParentThreshold?.(),f=c.many&&d!==void 0,p=Array.isArray(a.query?.selectItems)?a.query.selectItems:[],m=p.length>0&&!p.includes(c.foreignKey),b=this.driver.topNRelationPlanPolicy==="alwaysProbe",g=f&&(h===void 0?b:h>0&&l.length<=h),y=g?"bounded_probes":"window",O=H(this.operationTelemetry(),{family:"relation_load",name:`${t.entity}.${String(a.name)}`,attributes:{"teaql.entity.type":String(t.entity),"teaql.relation.name":String(a.name),"teaql.relation.parent_count":l.length,"teaql.relation.per_parent_limit":d??0,"teaql.relation.configured_probe_threshold":h??"provider-default","teaql.relation.selected_plan":y,"teaql.relation.probe_count":g?l.length:0}});try{if(!l.length&&!(c.many&&a.query?.facets?.length)){for(const T of e)T[a.name]=c.many?[]:null;O.success({attributes:{"teaql.result.cardinality":0}});continue}const w={...a.query||{},entity:c.targetEntity,selectItems:m?[...p,c.foreignKey]:p,_filters:[...this.filters(a.query||{})],relations:[...a.query?.relations||[]],orderItems:[...a.query?.orderItems||[]],__teaqlPartitionBy:f&&!g?c.foreignKey:void 0};if(f){const T=this.groupBy(w),R=T.length||this.aggregates(w).length?T:["id"];for(const v of R)w.orderItems.some(S=>S.field===v)||w.orderItems.push(Y.asc(v))}typeof w.clearContinuousPageRuntime=="function"&&w.clearContinuousPageRuntime(),w[this.internalQueryToken]=!0;const E=[],k={field:c.foreignKey,keys:new WeakMap};if(g)for(const T of l){const R={...w,_filters:[...w._filters,{[c.foreignKey]:{$eq:T}}],__teaqlPartitionBy:void 0};E.push(...await this.executeDerivedQuery(new L(t).derive(R,a.name,a.operation).query,r,s,k))}else w._filters.push({[c.foreignKey]:{$in:l}}),E.push(...await this.executeDerivedQuery(new L(t).derive(w,a.name,a.operation).query,r,s,k));for(const T of E)delete T.__teaql_partition_rank;const j=new Map;for(const T of E){if(!k.keys.has(T))throw new Error("Relation assembly lost its captured row identity");const R=k.keys.get(T),v=j.get(R)||[];v.push(T),j.set(R,v)}if(m)for(const T of E)delete T[c.foreignKey];for(const[T,R]of e.entries()){const v=j.get(u[T])||[];if(c.many&&a.query?.facets?.length){const S=a.query.clone();S.entity=c.targetEntity;const _=u[T],z={[c.foreignKey]:_==null?{$in:[]}:{$eq:_}};S.filterCondition=S.filterCondition?{$and:[S.filterCondition,z]}:z,je(t,S);const ae=new L(t).derive(S,a.name,a.operation).query;R[a.name]=new ee(v,{facets:await Xi(this,Ji=>Ji,ae,S.facets)})}else{const S=u[T];R[a.name]=c.many?v:v[0]??(S==null?null:{[c.foreignKey]:S})}}O.success({attributes:{"teaql.result.cardinality":E.length}})}catch(w){throw O.failure(w),w}}}async enhanceRelationAggregates(e,t,i,r){const o=t.relationAggregates;if(!e.length||!Array.isArray(o)||!o.length)return;const s=this.schema(t.entity),a=new L(t).intent;for(const c of o){const u=s.relations?.[c.relationName];if(!u)throw new Error(`Missing relation ${t.entity}.${c.relationName}`);const l=i.get(u.localKey),d=l.filter(b=>b!=null);if(!d.length){for(const b of e)b[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{};continue}const h=c.query.clone();h.entity=u.targetEntity,h.selectItems=[],h.properties=[],h.orderItems=[],h.limitValue=0,h.offsetValue=0,h.relations=[],h.relationAggregates=[],h.aggregateItems.length||h.aggregate("Count","id",c.alias),h.groupByItems.includes(u.foreignKey)||h.groupBy(u.foreignKey);const f={[u.foreignKey]:{$in:d}};h.filterCondition=h.filterCondition?{$and:[h.filterCondition,f]}:f,h[this.internalQueryToken]=!0;const p=await this.executeDerivedQuery(new L(t).deriveAggregate(h,c.relationName,c.operation??{kind:"relation-count",relation:c.relationName,alias:c.alias}).query,r,a),m=new Map;for(const b of p)m.set(b[u.foreignKey],b);for(const[b,g]of e.entries()){const y=m.get(l[b]);y?c.singleResult?g[c.alias]=y[h.aggregateItems[0].alias]??null:g[c.alias]=Object.fromEntries(Object.entries(y).filter(([O])=>O!==u.foreignKey)):g[c.alias]=c.singleResult?this.emptyAggregateValue(c.query):{}}}}emptyAggregateValue(e){const t=e.aggregateItems[0];return!t||String(t.function).toLowerCase()==="count"?0:null}queryLimit(e){if(e._limit!==void 0)return Number(e._limit);if(e.limitValue!==void 0&&Number(e.limitValue)>0)return Number(e.limitValue)}async close(){try{await this.driver.close()}finally{await this.telemetryStartup,await this.standardTelemetryHandle?.release(),this.standardTelemetryHandle=void 0}}}function xr(n){if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(n))throw new Error(`Unsafe SQL identifier: ${n}`);return n}function qr(n){const t={count:"COUNT",sum:"SUM",avg:"AVG",min:"MIN",max:"MAX"}[String(n).toLowerCase()];if(!t)throw new Error(`Unsupported aggregate: ${n}`);return t}class Mr{constructor(e){this.worker=e,this.nextRequestId=1,this.pending=new Map,this.closed=!1,this.onMessage=t=>{const i=t.data;if(!i||i.type!=="teaql-browser-sqlite-response")return;const r=this.pending.get(i.requestId);if(r)if(this.pending.delete(i.requestId),i.error){const o=new Error(i.error.message);o.name=i.error.name,i.error.code&&(o.code=i.error.code),r.reject(o)}else r.resolve(i.result)},this.onError=t=>{const i=new Error(t.message||"Browser SQLite worker failed");i.name="BrowserSQLiteWorkerError";for(const r of this.pending.values())r.reject(i);this.pending.clear()},e.addEventListener("message",this.onMessage),e.addEventListener("error",this.onError)}request(e,t){if(this.closed)return Promise.reject(new Error("Browser SQLite worker is closed"));const i=this.nextRequestId++;return new Promise((r,o)=>{this.pending.set(i,{resolve:s=>r(s),reject:o}),this.worker.postMessage({type:"teaql-browser-sqlite-request",requestId:i,operation:e,payload:t})})}async close(e){if(!this.closed)try{await this.request("close")}finally{this.closed=!0,this.worker.removeEventListener("message",this.onMessage),this.worker.removeEventListener("error",this.onError),e&&this.worker.terminate?.();const t=new Error("Browser SQLite worker is closed");for(const i of this.pending.values())i.reject(t);this.pending.clear()}}}class Dr{constructor(e){this.transport=e}query(e,t=[]){return this.transport.request("query",{sql:e,values:t})}}class Rt{constructor(e,t){this.transport=e,this.options=t,this.databaseKind="sqlite",this.accessTail=Promise.resolve()}static async open(e,t={}){const i={storage:t.storage??"memory",databaseName:zr(t.databaseName??"teaql-browser.sqlite3"),terminateWorkerOnClose:t.terminateWorkerOnClose??!0},r=new Mr(e);return await r.request("open",i),new Rt(r,i)}identifier(e){return`"${xr(e)}"`}placeholder(e){return"?"}contains(e,t){return`CAST(${e} AS TEXT) LIKE '%' || ${t} || '%'`}aggregateFunction(e){return qr(e)}decimalComparison(e,t,i){return`teaql_decimal_cmp(${e}, ${i}) ${t} 0`}decimalOrderExpression(e){return`teaql_decimal_order_key(${e})`}decimalAggregateFunction(e){const i={sum:"teaql_decimal_sum",min:"teaql_decimal_min",max:"teaql_decimal_max"}[e.toLowerCase()];if(!i)throw new Error(`EXACT_DECIMAL_UNSUPPORTED: ${e} requires an explicit exact rounding policy`);return i}longComparison(e,t,i){return`CAST(${e} AS INTEGER) ${t} CAST(${i} AS INTEGER)`}longOrderExpression(e){return`CAST(${e} AS INTEGER)`}encode(e,t){return e==null?e:t?.logicalType==="decimal"&&t.decode==="decimal"?ue(e):t?.logicalType==="long"?be(e):t?.logicalType==="time"?Ce(e):t?.logicalType==="json"&&typeof e!="string"?JSON.stringify(e):t?.logicalType==="boolean"?e?1:0:e instanceof Date?e.toISOString():e}async exclusive(e){const t=this.accessTail;let i;this.accessTail=new Promise(r=>{i=r}),await t;try{return await e()}finally{i()}}query(e,t=[]){return this.exclusive(()=>this.transport.request("query",{sql:e,values:t}))}async*stream(e,t=[]){const i=await this.query(e,t);for(const r of i.rows)yield r}transaction(e){return this.exclusive(async()=>{const t=new Dr(this.transport);await t.query("BEGIN IMMEDIATE");try{const i=await e(t);return await t.query("COMMIT"),i}catch(i){try{await t.query("ROLLBACK")}catch{}throw i}})}async ensureSchema(e){for(const t of Object.values(e)){const i=this.identifier(t.table);await this.query(`CREATE TABLE IF NOT EXISTS ${i} ("id" INTEGER PRIMARY KEY, "version" INTEGER NOT NULL)`);const r=await this.query(`PRAGMA table_info(${i})`),o=new Set(r.rows.map(s=>String(s.name)));for(const[s,a]of Object.entries(t.columns)){if(a.logicalType==="decimal"&&a.decode==="decimal"||a.logicalType==="long"){const c=r.rows.find(u=>String(u.name)===a.columnName);if(c&&String(c.type).toUpperCase()!=="TEXT")throw new Error(`EXACT_${a.logicalType.toUpperCase()}_SCHEMA_MISMATCH: ${t.table}.${a.columnName} requires TEXT; migrate the existing column explicitly`)}s==="id"||s==="version"||o.has(a.columnName)||await this.query(`ALTER TABLE ${i} ADD COLUMN ${this.identifier(a.columnName)} ${Fr(a.logicalType,a.decode)}${a.nullable===!1?" NOT NULL":""}`)}}for(const t of Ar(e))await this.query(`CREATE INDEX IF NOT EXISTS ${this.identifier(t.name)} ON ${this.identifier(t.table)} (${this.identifier(t.foreignColumn)}, ${this.identifier(t.idColumn)} DESC)`);await this.query("CREATE TABLE IF NOT EXISTS teaql_id_space (type_name TEXT PRIMARY KEY, current_level INTEGER NOT NULL)")}async nextId(e,t){for(let i=1;i<=100;i+=1){const r=await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t]);if(!r.rowCount){try{if((await e.query("INSERT INTO teaql_id_space(type_name, current_level) VALUES (?, 1)",[t])).rowCount===1)return"1"}catch(c){if(!(await e.query("SELECT current_level AS id FROM teaql_id_space WHERE type_name = ?",[t])).rowCount)throw c}continue}const o=Number(r.rows[0].id),s=o+1,a=await e.query("UPDATE teaql_id_space SET current_level = ? WHERE type_name = ? AND current_level = ?",[s,t,o]);if(a.rowCount===1)return String(s);if(a.rowCount!==0)throw new Error(`ID space update for ${t} changed ${a.rowCount} rows`)}throw new Error(`Unable to allocate ID for ${t} after 100 optimistic-lock attempts`)}ensureIdFloor(e,t,i){return Rr(e,r=>this.placeholder(r),t,i)}reset(){return this.exclusive(()=>this.transport.request("reset",this.options))}close(){return this.exclusive(()=>this.transport.close(this.options.terminateWorkerOnClose))}}class Yi extends Nr{constructor(e,t){super(e,t),this.browserDriver=e}static async open(e,t,i={}){return new Yi(await Rt.open(e,i),t)}get storage(){return this.browserDriver.options.storage}async reset(e){await this.browserDriver.reset(),this.invalidateSchemaState(),await e.ensureSchema()}}function Fr(n,e){return{boolean:"INTEGER",double:"REAL",decimal:e==="decimal"?"TEXT":"NUMERIC",long:"TEXT",time:"TEXT",date:"TEXT",datetime:"TEXT",json:"TEXT",integer:"INTEGER",text:"TEXT"}[n]}function zr(n){const e=n.trim();if(!e||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new TypeError("Browser SQLite databaseName must be a simple file name");return e}function Vr(n){if(typeof n!="string")return!1;try{return ue(n),!0}catch{return!1}}function Yr(n,e,t,i){const r=o=>{if(o.includes("."))throw new Error("Dynamic search requires a trusted relation binding");const s=t[n.entity]?.queryFields;if(!s||!Object.prototype.hasOwnProperty.call(s,o))throw new Error("Missing generated scalar search binding");return s[o]};return Ur(n,e,t,{filter:(o,s)=>{const[a,c]=Object.entries(s)[0];if(c===null&&a!=="$eq"&&a!=="$ne")throw new Error("Null supports only equality predicates");return{[r(o)]:s}},order:(o,s)=>s==="asc"?Y.asc(r(o)):Y.desc(r(o))},i)}function Ur(n,e,t,i,r=o=>console.warn({...o,fieldPath:""})){const o=Qr(e,n.entity,t,()=>{}),s=Object.entries(o.search.filter??{}).map(([d,h])=>i.filter(d,h)),a=(o.search.orderBy??[]).map(d=>i.order(d.field,d.direction));if(s.some(d=>!Re(d)))throw new Error("Invalid trusted search filter binding");if(a.some(d=>!(d instanceof Y)))throw new Error("Invalid trusted search order binding");const c=n.clone(),u=n._filters??[],l=[...u,...n.filterCondition?[n.filterCondition]:[]];return(s.length||u.length)&&c.filter({$and:[...l,...s]}),c.orderItems.push(...a),o.warnings.forEach(d=>r({...d})),{query:c,warnings:o.warnings}}const Ke=(n,e)=>Object.prototype.hasOwnProperty.call(n,e),Re=n=>typeof n=="object"&&n!==null&&!Array.isArray(n),Br=new Set(["__proto__","prototype","constructor"]),Kr=new Set(["$eq","$ne","$gt","$gte","$lt","$lte","$in","$notIn","$contains"]);function Qr(n,e,t,i=o=>console.warn({...o,fieldPath:""}),r=100){if(!Number.isSafeInteger(r)||r<1)throw new Error("Invalid search limit");if(!Ke(t,e))throw new Error("Unknown search entity");let o;try{o=typeof n=="string"?JSON.parse(n):n}catch{throw new Error("Dynamic search requires valid JSON")}if(!Re(o)||Object.keys(o).some(f=>!["filter","orderBy"].includes(f)))throw new Error("Unsupported dynamic search input or control");if(o.filter!==void 0&&!Re(o.filter))throw new Error("Invalid search filter");if(o.orderBy!==void 0&&!Array.isArray(o.orderBy))throw new Error("Invalid search ordering");const s=Object.entries(o.filter??{}),a=o.orderBy??[];if(s.length+a.length>r)throw new Error("Dynamic search exceeds clause limit");const c=[],u={filter:Object.create(null),orderBy:[]};function l(f){const p=f.split(".");if(p.length>16||p.some(g=>!g||g.startsWith("$")||Br.has(g)))throw new Error("Invalid dynamic search field path");let m=t[e];for(const g of p.slice(0,-1)){if(!Ke(m.relations,g))return;const y=m.relations[g];if(!Ke(t,y))throw new Error("Invalid trusted search relation metadata");m=t[y]}const b=p[p.length-1];return Ke(m.fields,b)?m.fields[b]:void 0}function d(f,p){c.push({code:"DYNAMIC_SEARCH_UNKNOWN_FIELD",entity:e,clause:p,fieldPath:f})}function h(f,p){if(f===null)return;if(!(p==="date"?typeof f=="string"&&/^\d{4}-\d{2}-\d{2}$/.test(f)&&!f.startsWith("0000-")&&Number.isFinite(Date.parse(f+"T00:00:00Z"))&&new Date(f+"T00:00:00Z").toISOString().slice(0,10)===f:p==="decimal"?Vr(f):p==="integer"||p==="timestamp"?typeof f=="number"&&Number.isSafeInteger(f):p==="number"?typeof f=="number"&&Number.isFinite(f):typeof f===p))throw new Error("Invalid value for known search field")}for(const[f,p]of s){const m=Re(p)?Object.entries(p):[["$eq",p]];if(m.length!==1||!Kr.has(m[0][0]))throw new Error("Unsupported or malformed dynamic search operator");const[b,g]=m[0];if((b==="$in"||b==="$notIn")&&(!Array.isArray(g)||g.length>1e3))throw new Error("Invalid or oversized search value list");const y=l(f);if(y===void 0){d(f,"FILTER");continue}if(y==="unsupported")throw new Error("Known search field has no supported scalar binding");if(b==="$contains"&&y!=="string")throw new Error("String operator requires a string field");if(Array.isArray(g)){if(b!=="$in"&&b!=="$notIn")throw new Error("Unexpected search value list");g.forEach(O=>h(O,y))}else h(g,y);u.filter[f]={[b]:Array.isArray(g)?[...g]:g}}for(const f of a){if(!Re(f)||Object.keys(f).some(m=>!["field","direction"].includes(m))||typeof f.field!="string"||!["asc","desc"].includes(f.direction))throw new Error("Invalid dynamic search ordering");const p=l(f.field);if(p===void 0){d(f.field,"ORDER_BY");continue}if(p==="unsupported")throw new Error("Known search field has no supported scalar binding");u.orderBy.push({field:f.field,direction:f.direction})}return c.forEach(f=>i({...f})),{search:u,warnings:c}}export{Yi as B,G as C,Wr as D,wn as E,$ as L,Ie as M,Y as O,it as Q,It as R,jr as S,rt as U,ee as a,Xr as b,Hr as c,F as d,Xi as e,Gn as f,M as g,ue as h,ui as i,Yr as j,jt as k,Ur as m,ct as n}; diff --git a/dist/assets/entity-creation-Bqaw1C4U.js b/dist/assets/entity-creation-Bqaw1C4U.js new file mode 100644 index 0000000000000000000000000000000000000000..f20b27b341b92f0c398ab72e3e59f140df8640ef --- /dev/null +++ b/dist/assets/entity-creation-Bqaw1C4U.js @@ -0,0 +1 @@ +import{U as l,k as f,L as p}from"./dynamic-search-BwvXmN4R.js";const d=new WeakMap,u=new WeakSet,i=new WeakMap,y=(o,t)=>JSON.stringify([o,t]);class a extends Error{constructor(){super("ENTITY_CREATION_CONTEXT_REQUIRED: create through the Context-bound Q factory or load a persisted version before mutation"),this.code="ENTITY_CREATION_CONTEXT_REQUIRED",this.name="EntityCreationError"}}class T{static async create(t,r,s){if(!(t instanceof l))throw new a;const n=await t.generateInternalId(r),e=s(n);return d.set(e,Object.freeze({entity:r,id:n})),e}static bootstrap(t,r,s,n){if(!(t instanceof l))throw new a;const e=f(s);if(!i.get(t)?.has(y(r,e)))throw new a;const c=n(e);return d.set(c,Object.freeze({entity:r,id:e})),c}static hydrated(t){return u.add(t),t}static requireMutation(t,r,s,n,e,c){if(!c)return;let w;try{w=f(s)}catch{throw new a}if(f(r.id)!==w)throw new a;const h=p.forEntity(t);if(n==="Create"){const E=d.get(t);if(!E||E.entity!==r.entity||E.id!==w||h?.origin!=="creationBaseline"||!e.isNew(r))throw new a}else if(!u.has(t)&&!d.has(t)||h?.origin!=="hydrated"||h.persistedVersion===void 0)throw new a}}async function I(o,t,r){const s=i.get(o),n=new Set;for(const e of[t.defaultDomainRoot,...t.constants??[]])e&&n.add(y(e.entity,f(e.id)));i.set(o,n);try{await r()}finally{s?i.set(o,s):i.delete(o)}}export{T as EntityCreation,a as EntityCreationError,I as runGeneratedBootstrap}; diff --git a/dist/assets/main-Csdici-L.js b/dist/assets/main-Csdici-L.js new file mode 100644 index 0000000000000000000000000000000000000000..166de027a039c2f996560a2065240388d9462ee3 --- /dev/null +++ b/dist/assets/main-Csdici-L.js @@ -0,0 +1,104 @@ +import{S as x,m as De,a as qe,e as xe,O as R,B as Qe,b as Be,R as Re,U as $e,D as ke,c as Fe,M as ze}from"./dynamic-search-BwvXmN4R.js";/* empty css */const C=t=>({columnName:t,modelName:t,logicalType:"integer",decode:"string"}),h=t=>({columnName:t,modelName:t,logicalType:"text",decode:"native"}),We=t=>({columnName:t,modelName:t,logicalType:"date",decode:"date"}),K=t=>({columnName:t,modelName:t,logicalType:"datetime",decode:"date"}),I=(t,e="decimal")=>({columnName:t,modelName:t,logicalType:e,decode:"number"}),f=Object.freeze({PENDING_PAYMENT:"1001",PAID:"1002",SHIPPED:"1003",DELIVERED:"1004",CANCELLED:"1005"}),Me=[{entity:"OrderStatus",id:f.PENDING_PAYMENT,values:{name:"Pending payment",code:"PENDING_PAYMENT",color:"#D97706",displayOrder:10}},{entity:"OrderStatus",id:f.PAID,values:{name:"Paid",code:"PAID",color:"#2563EB",displayOrder:20}},{entity:"OrderStatus",id:f.SHIPPED,values:{name:"Shipped",code:"SHIPPED",color:"#16A34A",displayOrder:30}},{entity:"OrderStatus",id:f.DELIVERED,values:{name:"Delivered",code:"DELIVERED",color:"#047857",displayOrder:40}},{entity:"OrderStatus",id:f.CANCELLED,values:{name:"Cancelled",code:"CANCELLED",color:"#9F1239",displayOrder:50}}],V={Platform:{table:"platform_data",columns:{id:C("id"),name:h("name"),code:h("code"),region:h("region"),currency:h("currency"),version:I("version","integer")},relations:{customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platformId",many:!0},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"platformId",many:!0}}},Customer:{table:"customer_data",columns:{id:C("id"),name:h("name"),email:h("email"),city:h("city"),tier:h("tier"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customerId",many:!0}}},CustomerOrder:{table:"customer_order_data",columns:{id:C("id"),orderNumber:h("order_number"),orderDate:We("order_date"),status:C("status_id"),totalAmount:I("total_amount"),currency:h("currency"),customerId:C("customer_id"),platformId:C("platform_id"),version:I("version","integer")},relations:{platform:{targetEntity:"Platform",localKey:"platformId",foreignKey:"id",many:!1},customer:{targetEntity:"Customer",localKey:"customerId",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},itemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"orderId",many:!0},paymentList:{targetEntity:"Payment",localKey:"id",foreignKey:"orderId",many:!0},shipmentList:{targetEntity:"Shipment",localKey:"id",foreignKey:"orderId",many:!0}}},OrderStatus:{table:"order_status_data",columns:{id:C("id"),name:h("name"),code:h("code"),color:h("color"),displayOrder:I("display_order","integer"),version:I("version","integer")},relations:{orderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},OrderItem:{table:"order_item_data",columns:{id:C("id"),orderId:C("order_id"),productName:h("product_name"),sku:h("sku"),quantity:I("quantity","integer"),unitPrice:I("unit_price"),lineAmount:I("line_amount"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Payment:{table:"payment_data",columns:{id:C("id"),orderId:C("order_id"),provider:h("provider"),status:h("status"),amount:I("amount"),currency:h("currency"),transactionId:h("transaction_id"),paidAt:K("paid_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}},Shipment:{table:"shipment_data",columns:{id:C("id"),orderId:C("order_id"),carrier:h("carrier"),status:h("status"),trackingNumber:h("tracking_number"),shipToCity:h("ship_to_city"),shippedAt:K("shipped_at"),deliveredAt:K("delivered_at"),version:I("version","integer")},relations:{order:{targetEntity:"CustomerOrder",localKey:"orderId",foreignKey:"id",many:!1}}}},pe=[{entity:"Platform",id:"1",payload:{name:"TeaQL Store",code:"TEAQL-CN",region:"China",currency:"CNY"}},{entity:"Platform",id:"2",payload:{name:"TeaQL Global",code:"TEAQL-GLOBAL",region:"Global",currency:"USD"}},{entity:"Customer",id:"101",payload:{name:"Lin Xiao",email:"lin.xiao@example.com",city:"Shanghai",tier:"GOLD",platformId:"1"}},{entity:"Customer",id:"102",payload:{name:"Zhou Ran",email:"zhou.ran@example.com",city:"Hangzhou",tier:"SILVER",platformId:"1"}},{entity:"Customer",id:"103",payload:{name:"Maya Patel",email:"maya.patel@example.com",city:"Singapore",tier:"GOLD",platformId:"2"}},{entity:"Customer",id:"104",payload:{name:"Lucas Martin",email:"lucas.martin@example.com",city:"Paris",tier:"SILVER",platformId:"2"}},{entity:"Customer",id:"105",payload:{name:"Wang Ning",email:"wang.ning@example.com",city:"Chengdu",tier:"BRONZE",platformId:"1"}},{entity:"CustomerOrder",id:"1001",payload:{orderNumber:"TQL-2026-1001",orderDate:"2026-08-28",status:f.DELIVERED,totalAmount:499,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1002",payload:{orderNumber:"TQL-2026-1002",orderDate:"2026-09-02",status:f.SHIPPED,totalAmount:1299,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1003",payload:{orderNumber:"TQL-2026-1003",orderDate:"2026-09-06",status:f.PAID,totalAmount:328.8,currency:"CNY",customerId:"101",platformId:"1"}},{entity:"CustomerOrder",id:"1004",payload:{orderNumber:"TQL-2026-1004",orderDate:"2026-09-11",status:f.PENDING_PAYMENT,totalAmount:79.9,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"CustomerOrder",id:"1005",payload:{orderNumber:"TQL-2026-1005",orderDate:"2026-09-14",status:f.DELIVERED,totalAmount:219,currency:"USD",customerId:"103",platformId:"2"}},{entity:"CustomerOrder",id:"1006",payload:{orderNumber:"TQL-2026-1006",orderDate:"2026-09-18",status:f.PAID,totalAmount:640,currency:"USD",customerId:"104",platformId:"2"}},{entity:"CustomerOrder",id:"1007",payload:{orderNumber:"TQL-2026-1007",orderDate:"2026-09-21",status:f.CANCELLED,totalAmount:159,currency:"CNY",customerId:"102",platformId:"1"}},{entity:"CustomerOrder",id:"1008",payload:{orderNumber:"TQL-2026-1008",orderDate:"2026-09-25",status:f.SHIPPED,totalAmount:268,currency:"CNY",customerId:"105",platformId:"1"}},{entity:"OrderItem",id:"2001",payload:{orderId:"1001",productName:"TeaQL Mechanical Keyboard",sku:"KB-TQL-87",quantity:1,unitPrice:299,lineAmount:299}},{entity:"OrderItem",id:"2002",payload:{orderId:"1001",productName:"Silent Wireless Mouse",sku:"MS-SILENT",quantity:2,unitPrice:100,lineAmount:200}},{entity:"OrderItem",id:"2003",payload:{orderId:"1002",productName:"27-inch Developer Monitor",sku:"MON-27-4K",quantity:1,unitPrice:1299,lineAmount:1299}},{entity:"OrderItem",id:"2004",payload:{orderId:"1003",productName:"White Porcelain Travel Tea Set",sku:"TEA-TRAVEL",quantity:1,unitPrice:168.8,lineAmount:168.8}},{entity:"OrderItem",id:"2005",payload:{orderId:"1003",productName:"Pre-Qingming Longjing Tea",sku:"TEA-LJ-100",quantity:2,unitPrice:80,lineAmount:160}},{entity:"OrderItem",id:"2006",payload:{orderId:"1004",productName:"Double-wall Glass Tumbler",sku:"CUP-GLASS",quantity:1,unitPrice:79.9,lineAmount:79.9}},{entity:"OrderItem",id:"2007",payload:{orderId:"1005",productName:"Travel Brew Kit",sku:"BREW-KIT",quantity:1,unitPrice:219,lineAmount:219}},{entity:"OrderItem",id:"2008",payload:{orderId:"1006",productName:"Desktop Studio Speaker",sku:"SPK-STUDIO",quantity:2,unitPrice:200,lineAmount:400}},{entity:"OrderItem",id:"2009",payload:{orderId:"1006",productName:"Speaker Stand",sku:"SPK-STAND",quantity:1,unitPrice:80,lineAmount:80}},{entity:"OrderItem",id:"2010",payload:{orderId:"1007",productName:"Desktop Reading Lamp",sku:"LAMP-DESK",quantity:1,unitPrice:159,lineAmount:159}},{entity:"OrderItem",id:"2011",payload:{orderId:"1008",productName:"TeaQL Portable Keyboard",sku:"KB-TQL-68",quantity:1,unitPrice:168,lineAmount:168}},{entity:"OrderItem",id:"2012",payload:{orderId:"1008",productName:"Keyboard Protective Case",sku:"KB-CASE-68",quantity:1,unitPrice:30,lineAmount:30}},{entity:"OrderItem",id:"2013",payload:{orderId:"1008",productName:"Foldable Travel Stand",sku:"KB-STAND-FOLD",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2014",payload:{orderId:"1008",productName:"Braided USB-C Cable",sku:"CABLE-USBC",quantity:1,unitPrice:20,lineAmount:20}},{entity:"OrderItem",id:"2015",payload:{orderId:"1008",productName:"Accent Keycap Set",sku:"KEYCAP-ACCENT",quantity:1,unitPrice:25,lineAmount:25}},{entity:"OrderItem",id:"2016",payload:{orderId:"1006",productName:"Balanced Audio Cable",sku:"AUDIO-XLR",quantity:1,unitPrice:40,lineAmount:40}},{entity:"OrderItem",id:"2017",payload:{orderId:"1006",productName:"Speaker Isolation Pads",sku:"SPK-PADS",quantity:1,unitPrice:60,lineAmount:60}},{entity:"OrderItem",id:"2018",payload:{orderId:"1006",productName:"USB DAC Adapter",sku:"AUDIO-DAC-USB",quantity:1,unitPrice:60,lineAmount:60}},{entity:"Payment",id:"3001",payload:{orderId:"1001",provider:"Alipay",status:"CAPTURED",amount:499,currency:"CNY",transactionId:"ALI-260828-01",paidAt:"2026-08-28T10:14:00Z"}},{entity:"Payment",id:"3002",payload:{orderId:"1002",provider:"WeChat Pay",status:"CAPTURED",amount:1299,currency:"CNY",transactionId:"WX-260902-08",paidAt:"2026-09-02T03:20:00Z"}},{entity:"Payment",id:"3003",payload:{orderId:"1003",provider:"Alipay",status:"CAPTURED",amount:328.8,currency:"CNY",transactionId:"ALI-260906-11",paidAt:"2026-09-06T11:42:00Z"}},{entity:"Payment",id:"3004",payload:{orderId:"1004",provider:"WeChat Pay",status:"PENDING",amount:79.9,currency:"CNY",transactionId:"WX-260911-02",paidAt:null}},{entity:"Payment",id:"3005",payload:{orderId:"1005",provider:"Stripe",status:"CAPTURED",amount:219,currency:"USD",transactionId:"PI-260914-05",paidAt:"2026-09-14T06:10:00Z"}},{entity:"Payment",id:"3006",payload:{orderId:"1006",provider:"Stripe",status:"CAPTURED",amount:640,currency:"USD",transactionId:"PI-260918-03",paidAt:"2026-09-18T15:08:00Z"}},{entity:"Payment",id:"3007",payload:{orderId:"1007",provider:"Alipay",status:"REFUNDED",amount:159,currency:"CNY",transactionId:"ALI-260921-07",paidAt:"2026-09-21T02:55:00Z"}},{entity:"Payment",id:"3008",payload:{orderId:"1008",provider:"WeChat Pay",status:"CAPTURED",amount:268,currency:"CNY",transactionId:"WX-260925-06",paidAt:"2026-09-25T08:31:00Z"}},{entity:"Shipment",id:"4001",payload:{orderId:"1001",carrier:"SF Express",status:"DELIVERED",trackingNumber:"SF2608281001",shipToCity:"Shanghai",shippedAt:"2026-08-29T02:00:00Z",deliveredAt:"2026-08-30T07:26:00Z"}},{entity:"Shipment",id:"4002",payload:{orderId:"1002",carrier:"JD Logistics",status:"IN_TRANSIT",trackingNumber:"JD2609021002",shipToCity:"Hangzhou",shippedAt:"2026-09-03T04:12:00Z",deliveredAt:null}},{entity:"Shipment",id:"4003",payload:{orderId:"1003",carrier:"SF Express",status:"READY",trackingNumber:"SF2609061003",shipToCity:"Shanghai",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4004",payload:{orderId:"1005",carrier:"DHL",status:"DELIVERED",trackingNumber:"DHL2609141005",shipToCity:"Singapore",shippedAt:"2026-09-15T01:10:00Z",deliveredAt:"2026-09-17T09:22:00Z"}},{entity:"Shipment",id:"4005",payload:{orderId:"1006",carrier:"DHL",status:"READY",trackingNumber:"DHL2609181006",shipToCity:"Paris",shippedAt:null,deliveredAt:null}},{entity:"Shipment",id:"4006",payload:{orderId:"1008",carrier:"SF Express",status:"IN_TRANSIT",trackingNumber:"SF2609251008",shipToCity:"Chengdu",shippedAt:"2026-09-26T03:18:00Z",deliveredAt:null}}],N=t=>`'${t.replaceAll("\\","\\\\").replaceAll("'","\\'").replaceAll(` +`,"\\n")}'`,U=t=>t.toQExpression().replace(/\s*\n\s*/g,""),_e={CustomerOrder:{fields:{id:"integer",orderNumber:"string",orderDate:"date",status:"integer",totalAmount:"decimal",currency:"string",customerId:"integer",platformId:"integer"},relations:{status:"OrderStatus",itemList:"OrderItem"}},OrderStatus:{fields:{id:"integer",name:"string",code:"string",color:"string",displayOrder:"integer"},relations:{}},OrderItem:{fields:{id:"integer",orderId:"integer",productName:"string",sku:"string"},relations:{}}};function Ke(t){if(!t||typeof t!="object"||Array.isArray(t))return t;const e=structuredClone(t),r=e.filter;if(!r||typeof r!="object"||Array.isArray(r)||!("status"in r))return e;const n=r,s=n.status,o=a=>{const i=f[String(a)];return i===void 0?a:Number(i)};return s&&typeof s=="object"&&!Array.isArray(s)&&"$in"in s?n.status={$in:Array.isArray(s.$in)?s.$in.map(o):s.$in}:n.status=o(s),e}class P{query;filters=[];qRoot;qSteps=[];auditComment="";queryPurpose="";pageTotalAlias;constructor(e,r){this.query=new x(e),this.qRoot=r}comment(e){return this.auditComment=e,this.query.comment(e),this.record(`comment(${N(e)})`),this}purpose(e){return this.queryPurpose=e,this.query.purpose(e),this.record(`purpose(${N(e)})`),this}limit(e){return this.query.limit(e),this.record(`limit(${e})`),this}offset(e){return this.query.offset(e),this.record(`offset(${e})`),this}toQExpression(e){const r=e?[...this.qSteps,e]:this.qSteps;return[this.qRoot,...r.map(n=>` .${n}`)].join(` +`)}toQuery(){const e=this.query.clone();return this.filters.length&&e.filter({$and:[...this.filters]}),e}async executeForList(e){return this.executeList(e,this.pageTotalAlias!==void 0)}async executeForRows(e){return this.executeList(e,!1)}async executeList(e,r){this.ensureIntent();const n=this.service(e),s=this.toQuery(),o=r?await n.executeCount(s,this.pageTotalAlias,{kind:"named-count",method:"countAs",alias:this.pageTotalAlias}):void 0,a=s.clone();r&&(a.aggregateItems=a.aggregateItems.filter(m=>!(String(m.function).toLowerCase()==="count"&&m.alias===this.pageTotalAlias)));const i=await n.executeQuery(e.prepareQuery(a)),c=new qe(i,{totalCount:o});return r&&this.pageTotalAlias!==void 0&&(c.aggregations[this.pageTotalAlias]=o),s.facets.length&&(c.facets=await xe(n,m=>e.prepareQuery(m),s,s.facets)),c}addFilter(e){return this.filters.push(e),this}select(...e){return this.query.select(e),this}order(e,r){return this.query.order(r==="asc"?R.asc(e):R.desc(e)),this}group(e){return this.query.groupBy(e),this}aggregate(e,r,n){return this.query.aggregate(e,r,n),this}record(e){return this.qSteps.push(e),this}includePageTotalAs(e){return this.pageTotalAlias=e,this}service(e){return e.requireResource("dataService")}ensureIntent(){if(!this.auditComment.trim()||!this.queryPurpose.trim())throw new Error("Generated Q requests require comment() and purpose() before execution")}}class Ue extends P{constructor(){super("Platform","Q.platforms()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCode(){return this.select("code")}withIdIs(e){return this.addFilter({id:{$eq:e}})}}class Ge extends P{constructor(){super("Customer","Q.customers()")}selectId(){return this.select("id")}selectName(){return this.select("name")}selectCity(){return this.select("city")}selectTier(){return this.select("tier")}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}countOrderListAs(e){return this.query.relationAggregate("orderList",e,new x("CustomerOrder").aggregate("Count","id",e)),this}orderByNameAscending(){return this.order("name","asc")}}class Ye extends P{constructor(){super("OrderItem","Q.orderItems()")}selectId(){return this.select("id"),this.record("selectId()")}selectOrderId(){return this.select("orderId"),this.record("selectOrderId()")}selectProductName(){return this.select("productName"),this.record("selectProductName()")}selectSku(){return this.select("sku"),this.record("selectSku()")}selectQuantity(){return this.select("quantity"),this.record("selectQuantity()")}withProductNameContaining(e){return this.addFilter({productName:{$contains:e}})}orderByIdAscending(){return this.order("id","asc"),this.record("orderByIdAscending()")}groupByProductName(){return this.group("productName")}sumQuantityAs(e){return this.aggregate("Sum","quantity",e)}sumLineAmountAs(e){return this.aggregate("Sum","lineAmount",e)}countAs(e){return this.aggregate("Count","id",e)}}class je extends P{constructor(){super("OrderStatus","Q.orderStatuses()")}selectId(){return this.select("id"),this.record("selectId()")}selectName(){return this.select("name"),this.record("selectName()")}selectCode(){return this.select("code"),this.record("selectCode()")}selectColor(){return this.select("color"),this.record("selectColor()")}selectDisplayOrder(){return this.select("displayOrder"),this.record("selectDisplayOrder()")}withCodeIs(e){return this.addFilter({code:{$eq:e}})}countAs(e){return this.aggregate("Count","id",e),this.record(`countAs(${N(e)})`)}sumOrderTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e),this.record(`sumOrderTotalAmountAs(${N(e)})`)}orderByDisplayOrderAscending(){return this.order("displayOrder","asc"),this.record("orderByDisplayOrderAscending()")}}class Ve extends P{constructor(){super("Payment","Q.payments()")}groupByCurrency(){return this.group("currency")}groupByProvider(){return this.group("provider")}groupByStatus(){return this.group("status")}countAs(e){return this.aggregate("Count","id",e)}sumAmountAs(e){return this.aggregate("Sum","amount",e)}orderByCurrencyAscending(){return this.order("currency","asc")}orderByProviderAscending(){return this.order("provider","asc")}orderByIdAscending(){return this.order("id","asc")}}class He extends P{constructor(){super("Shipment","Q.shipments()")}withStatusIn(...e){return this.addFilter({status:{$in:e}})}selectOrderWith(e){return this.query.relationQuery("order",e.toQuery(),"orderId","id",!1),this}orderByStatusAscending(){return this.order("status","asc")}orderByIdAscending(){return this.order("id","asc")}}class de extends P{dynamicWarnings=[];countAlias;rowCountApplied=!1;constructor(e=!1){super("CustomerOrder",e?"Q.customerOrdersWithMinimalFields()":"Q.customerOrders()"),e?this.query.select(["id","version"]):this.query.select(["id","orderNumber","orderDate","status","totalAmount","currency","customerId","platformId","version"])}selectId(){return this.select("id")}selectOrderNumber(){return this.select("orderNumber"),this.record("selectOrderNumber()")}selectOrderDate(){return this.select("orderDate"),this.record("selectOrderDate()")}selectStatus(){return this.select("status")}selectTotalAmount(){return this.select("totalAmount")}selectCurrency(){return this.select("currency")}withOrderNumberIs(e){return this.addFilter({orderNumber:{$eq:e}})}withOrderNumberContaining(e){return this.addFilter({orderNumber:{$contains:e}})}withStatusMatching(e){return this.addFilter({status:{$inSubquery:{query:e.toQuery(),field:"id"}}})}withStatusIsPendingPayment(){return this.addFilter({status:{$eq:f.PENDING_PAYMENT}})}withStatusIsPaid(){return this.addFilter({status:{$eq:f.PAID}})}withStatusIsShipped(){return this.addFilter({status:{$eq:f.SHIPPED}})}withStatusIsDelivered(){return this.addFilter({status:{$eq:f.DELIVERED}})}withStatusIsCancelled(){return this.addFilter({status:{$eq:f.CANCELLED}})}withCurrencyIs(e){return this.addFilter({currency:{$eq:e}})}withTotalAmountGreaterThanOrEqualTo(e){return this.addFilter({totalAmount:{$gte:e}})}withOrderDateGreaterThanOrEqualTo(e){return this.addFilter({orderDate:{$gte:e}})}withPlatformIdIs(e){return this.addFilter({platformId:{$eq:e}})}withItemListMatching(e){return this.addFilter({id:{$inSubquery:{query:e.toQuery(),field:"orderId"}}})}filterByJson(e){const{query:r,warnings:n}=De(this.toQuery(),Ke(e),_e,{filter:(s,o)=>s==="status.code"?{status:{$inSubquery:{query:new x("OrderStatus").filter({code:o}),field:"id"}}}:s==="itemList.productName"?{id:{$inSubquery:{query:new x("OrderItem").filter({productName:o}),field:"orderId"}}}:{[s]:o},order:(s,o)=>o==="asc"?R.asc(s):R.desc(s)});return this.dynamicWarnings=n,this.query.filterCondition=r.filterCondition,this.query.orderItems=[...r.orderItems],this.record("filterByJson(searchParams)"),this}warnings(){return this.dynamicWarnings}selectPlatformWith(e){return this.query.relationQuery("platform",e.toQuery(),"platformId","id",!1),this}selectCustomerWith(e){return this.query.relationQuery("customer",e.toQuery(),"customerId","id",!1),this}selectStatusWith(e){return this.query.select(["status"]),this.query.relationQuery("status",e.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this.record(`selectStatusWith(${U(e)})`)}selectItemListWith(e){return this.query.relationQuery("itemList",e.toQuery(),"id","orderId",!0,{kind:"relation-select",method:"selectItemListWith",relation:"itemList"}),this.record(`selectItemListWith(${U(e)})`)}selectPaymentListWith(e){return this.query.relationQuery("paymentList",e.toQuery(),"id","orderId",!0),this}selectShipmentListWith(e){return this.query.relationQuery("shipmentList",e.toQuery(),"id","orderId",!0),this}countItemListAs(e){return this.query.relationAggregate("itemList",e,new x("OrderItem").aggregate("Count","id",e).comment("count items"),!0,{kind:"relation-count",method:"countItemListAs",relation:"itemList",alias:e}),this.record(`countItemListAs(${N(e)})`)}facetByStatusAs(e,r,n=!0){const s=r.toQuery();return s.commentText||s.comment("load status facets"),this.query.facetBy(e,"status",{toQuery:()=>s},n,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:e}),this.record(`facetByStatusAs(${N(e)}, ${U(r)})`)}orderByOrderDateDescending(){return this.order("orderDate","desc"),this.record("orderByOrderDateDescending()")}orderByOrderDateAscending(){return this.order("orderDate","asc")}orderByIdDescending(){return this.order("id","desc"),this.record("orderByIdDescending()")}orderByTotalAmountDescending(){return this.order("totalAmount","desc")}groupByCurrency(){return this.group("currency")}groupByStatus(){return this.group("status")}countAs(e){return this.countAlias=e,this.record(`countAs(${N(e)})`)}sumTotalAmountAs(e){return this.aggregate("Sum","totalAmount",e)}averageTotalAmountAs(e){return this.aggregate("Avg","totalAmount",e)}executeForList(e){return this.countAlias&&this.includePageTotalAs(this.countAlias),super.executeForList(e)}executeForRows(e){return this.applyRowCount(),super.executeForRows(e)}applyRowCount(){!this.countAlias||this.rowCountApplied||(this.query.aggregate("Count","id",this.countAlias),this.rowCountApplied=!0)}}class u{static platforms(){return new Ue}static customers(){return new Ge}static customerOrders(){return new de}static customerOrdersWithMinimalFields(){return new de(!0)}static orderItems(){return new Ye}static orderStatuses(){return new je}static payments(){return new Ve}static shipments(){return new He}}const F=document.querySelector("#status"),$=document.querySelector("#persist"),G=document.querySelector("#reset"),k=document.querySelector("#query-catalog"),w=document.querySelector("#result"),ye=document.querySelector("#result-title"),he=document.querySelector("#result-description"),X=document.querySelector("#result-meta"),ce=document.querySelector("#query-code"),Ze=document.querySelector("#query-params-block"),Je=document.querySelector("#query-params-code"),Xe=document.querySelector("#result-grid"),B=document.querySelector("#result-view-label"),et=document.querySelector("#sql-count"),ue=document.querySelector("#sql-output"),ee=document.querySelector("#expand-all"),tt=document.querySelector("#collapse-all"),Q=document.querySelector("#view-table"),H=document.querySelector("#view-tree"),ge=Array.from(document.querySelectorAll("[data-locale]")),rt={heroTitle:{en:"Understand TeaQL queries through a familiar order model.",zh:"用一个熟悉的订单模型,看懂 TeaQL 查询。"},heroIntro:{en:"Platform, customer, order, item, payment, and shipment data all run in the browser. Order status is backed by a constant model. Choose a query below to inspect real SQLite/WASM results.",zh:"平台、用户、订单、明细、支付和物流数据都在浏览器中运行;订单状态由常数模型提供。选择下面的查询,查看真实的 SQLite/WASM 结果。"},runtimeCoverage:{en:"RUNTIME COVERAGE",zh:"RUNTIME 覆盖"},runtimeTitle:{en:"This demo runs TypeScript in your browser.",zh:"这个演示在浏览器中运行 TypeScript。"},runtimeIntro:{en:"The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.",zh:"同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。"},currentBrowserRuntime:{en:"Current browser runtime",zh:"当前浏览器 runtime"},supportedRuntime:{en:"Supported runtime",zh:"已支持 runtime"},developmentProcess:{en:"00 / DEVELOPMENT PROCESS",zh:"00 / 开发过程"},developmentProcessTitle:{en:"From one domain model to executable evidence.",zh:"从一份领域模型,到可以执行和审查的证据。"},developmentProcessIntro:{en:"TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.",zh:"TeaQL 让业务模型保持精简、可读,从模型生成确定性的领域 API,并把请求意图一直带到 Runtime 实际执行的 SQL。"},modelSource:{en:"MODEL SOURCE",zh:"模型源文件"},viewOrderModel:{en:"View order-model.xml",zh:"查看 order-model.xml"},scopedGuidance:{en:"SCOPED GUIDANCE",zh:"按需指导"},viewModelAssist:{en:"View model-aware Assist",zh:"查看模型感知 Assist"},processModelTitle:{en:"Model the domain",zh:"建立领域模型"},processModelBody:{en:"Define entities, fields, relationships, constant objects, and constraints in one model file.",zh:"在一个模型文件中定义对象、字段、关系、常数对象和约束。"},processGenerateTitle:{en:"Generate the working surface",zh:"生成领域开发接口"},processGenerateBody:{en:"Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.",zh:"从模型生成强类型 Q 与 E API、Schema、可审计变更和字段级 Assist。"},processQueryTitle:{en:"Build one bounded Q request",zh:"构建一个有界的 Q 请求"},processQueryBody:{en:"Application code selects only what the page needs and attaches a readable comment and purpose.",zh:"应用代码只选择页面需要的内容,并附上可读的 comment 和 purpose。"},processEvidenceTitle:{en:"Run and retain evidence",zh:"运行并保留证据"},processEvidenceBody:{en:"The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.",zh:"Runtime 执行策略和 SQLite/WASM,并保留从 purpose、嵌套 comment 到耗时和实际 SQL 的 TraceChain。"},contextEfficiency:{en:"CONTEXT EFFICIENCY",zh:"上下文效率"},contextEfficiencyTitle:{en:"Spend context on the business change.",zh:"把上下文窗口留给真正的业务变更。"},contextEfficiencyBody:{en:"Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.",zh:"Agent 不需要加载 Runtime 内部实现和所有生成文件,而是从精简模型出发,只打开当前对象、动作或字段所需的 Assist。强类型领域操作把数据库和 Provider 细节压缩成更小的工作界面,减少重复占用上下文,同时保持行为确定、可审查。"},observabilityTitle:{en:"TraceChain in OpenObserve",zh:"OpenObserve 中的 TraceChain"},observabilityIntro:{en:"A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.",zh:"一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。"},observabilityCaption:{en:"OpenObserve dashboard showing one verified trace and its eight actual SQL executions.",zh:"OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。"},platform:{en:"Platform",zh:"平台"},customer:{en:"Customer",zh:"用户"},order:{en:"Order",zh:"订单"},item:{en:"Item",zh:"明细"},payment:{en:"Payment",zh:"支付"},shipment:{en:"Shipment",zh:"物流"},constantModel:{en:"Constant model",zh:"常数模型"},persist:{en:"Persist locally with OPFS",zh:"使用 OPFS 保存在本地"},reset:{en:"Reset demo data",zh:"重置演示数据"},chooseQuery:{en:"Choose a query",zh:"选择一个查询"},queryIntro:{en:"Queries are grouped by purpose and share the same order dataset.",zh:"查询按用途分组,并共用同一份订单数据。"},table:{en:"Table",zh:"表格"},resultTree:{en:"Result Tree",zh:"结果树"},expandAll:{en:"Expand all",zh:"全部展开"},collapseAll:{en:"Collapse all",zh:"全部折叠"},waiting:{en:"Waiting for query…",zh:"等待查询…"},queryNote:{en:"The Q expression stays fixed; search, status cards, and pagination only update dynamic parameters. The underlying SelectQuery remains inside the generated request implementation.",zh:"Q 表达式保持不变;搜索、状态卡片和分页只更新动态参数。底层 SelectQuery 仍封装在生成的请求实现中。"},executionEvidence:{en:"EXECUTION EVIDENCE",zh:"执行证据"},evidenceTime:{en:"Time",zh:"时间"},identity:{en:"Identity",zh:"身份"},traceChain:{en:"Trace chain",zh:"追踪链"},sqlNote:{en:"One plain-text line per statement: time, identity, trace chain, and the SQL SQLite executed.",zh:"每条语句使用一行纯文本:时间、身份、追踪链,以及 SQLite 实际执行的 SQL。"},localData:{en:"Data stays in this browser",zh:"数据只保留在当前浏览器中"}},nt={基本查询:"Basic queries","从订单、用户和关联对象开始":"Start with orders, customers, and related objects",汇总查询:"Aggregations","分组、计数、求和与平均值":"Grouping, counts, sums, and averages",过滤查询:"Filtered queries","精确、范围与组合条件":"Exact, range, and combined predicates",动态查询:"Dynamic queries","由页面条件安全生成,不使用 eval":"Safely generated from page criteria without eval","综合:订单管理中心":"Comprehensive: Order management center","一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。":"A real composite query page: status metrics, search, product previews, and pagination are all driven by TeaQL.",最近订单:"Recent orders","按下单日期倒序浏览全部订单,并带出所属平台与用户。":"Browse all orders by date descending, including their platform and customer.",完整订单详情:"Complete order details","查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。":"Inspect one order with its customer, items, payments, and shipments as a complete object graph.",用户与订单数:"Customers with order counts","列出用户,并通过关联汇总显示每位用户的订单数量。":"List customers and show each customer’s order count through a relation aggregate.",订单状态汇总:"Orders by status","按币种与订单状态统计订单数、总额和平均客单价。":"Aggregate order count, gross amount, and average order value by currency and status.",商品销售汇总:"Product sales summary","按商品汇总销量与销售额,找出最受欢迎的订单明细。":"Aggregate units and revenue by product to identify the most popular order items.",支付渠道对账:"Payment reconciliation","按币种、支付渠道和状态汇总笔数与金额。":"Aggregate transaction count and amount by currency, payment provider, and status.",待支付订单:"Orders awaiting payment","筛选尚未完成付款的订单,并带出对应支付记录。":"Find orders that have not completed payment and include their payment records.",国内大额订单:"High-value domestic orders","组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。":"Combine platform and amount filters to find TeaQL Store orders worth at least CNY 500.",运输中的包裹:"Active shipments","筛选待揽收和运输中的物流单,并关联订单信息。":"Find shipments that are ready or in transit and include their order information.","动态:已付款国内订单":"Dynamic: paid domestic orders","从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。":"Build a query from dynamic criteria: CNY, at least 250, and status PAID or SHIPPED.","动态:九月新订单":"Dynamic: new September orders","运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。":"Pass a date range and sort order at runtime to find orders after September 15.","动态:字段白名单":"Dynamic: field allowlist","未知字段会被报告并忽略;合法条件仍可安全执行。":"Unknown fields are reported and ignored while valid predicates still execute safely."};let d=localStorage.getItem("teaql-browser-locale")==="zh"?"zh":"en";function st(t){return rt[t]?.[d]??t}function O(t){return d==="en"?nt[t]??t:t}let E,z=window.location.hash.slice(1)||"order-center";window.location.hash||history.replaceState(null,"","#order-center");let b="tree",T,fe=0,te;const A={search:"",page:0,pageSize:4},Ae=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";$.checked=Ae==="opfs";async function Y(t,e){const r=u.customerOrders().filterByJson(e).limit(20).comment("what: execute a validated browser search").purpose("why: demonstrate safe dynamic order discovery"),n=await r.executeForList(t.context);return{request:e,warnings:r.warnings(),data:n}}const ot=Object.fromEntries(Object.entries(f).map(([t,e])=>[e,t]));function re(t){const e=String(t.code??"");return e&&e in f?e:"color"in t?ot[String(t.id??"")]??"":""}function Se(t){const e=t.trim();if(!e)return{filter:{}};const r=e.toUpperCase(),n=["PENDING_PAYMENT","PAID","SHIPPED","DELIVERED","CANCELLED"].find(s=>s.includes(r));return n?{filter:{"status.code":n}}:/^(TQL-|\d)/i.test(e)?{filter:{orderNumber:{$contains:r}}}:{filter:{"itemList.productName":{$contains:e}}}}async function at(t){const e=Se(A.search),r=u.customerOrdersWithMinimalFields().filterByJson(e).countAs("totalOrders").facetByStatusAs("statusCounts",u.orderStatuses().selectName().selectColor().countAs("orderCount").sumOrderTotalAmountAs("orderTotalAmount").orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor().comment("load status")).selectItemListWith(u.orderItems().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countItemListAs("itemCount").orderByOrderDateDescending().orderByIdDescending().comment("load order list").purpose("render order list page"),n=r.toQExpression(`offset(pageOffset) + .limit(pageSize) + .executeForList(ctx);`),s=await r.offset(A.page*A.pageSize).limit(A.pageSize).executeForList(t.context),o=s.facet("statusCounts")??[];return{orders:s,totalOrders:Number(s.aggregations.totalOrders??s.totalCount),filteredOrders:s.totalCount??0,statusFacets:o.map(a=>({code:re(a),name:String(a.name??""),color:String(a.color??""),orderCount:Number(a.orderCount??0),orderTotalAmount:Number(a.orderTotalAmount??0)})).filter(a=>a.code&&a.name),search:A.search,page:A.page,pageSize:A.pageSize,queryExpression:n}}const Ce=[{label:"基本查询",description:"从订单、用户和关联对象开始",queries:[{id:"order-center",title:"综合:订单管理中心",description:"一个真实的综合查询页面:状态指标、搜索、商品预览和分页都由 TeaQL 查询驱动。",code:"",view:"dashboard",run:at},{id:"recent-orders",title:"最近订单",description:"按下单日期倒序浏览全部订单,并带出所属平台与用户。",code:`await Q.customerOrders() + .selectPlatformWith(Q.platforms().selectName()) + .selectCustomerWith(Q.customers().selectName().selectCity().selectTier()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .orderByOrderDateDescending() + .orderByIdDescending() + .limit(8) + .comment('what: list recent commerce orders') + .purpose('why: provide the default order overview') + .executeForList(ctx)`,run:t=>u.customerOrders().selectPlatformWith(u.platforms().selectName()).selectCustomerWith(u.customers().selectName().selectCity().selectTier()).selectStatusWith(u.orderStatuses().selectName().selectColor()).orderByOrderDateDescending().orderByIdDescending().limit(8).comment("what: list recent commerce orders").purpose("why: provide the default order overview").executeForList(t.context)},{id:"order-detail",title:"完整订单详情",description:"查看一个订单及其用户、商品明细、支付和物流,体现完整对象图。",code:`await Q.customerOrders() + .withOrderNumberIs('TQL-2026-1003') + .selectPlatformWith(Q.platforms()) + .selectCustomerWith(Q.customers()) + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectItemListWith(Q.orderItems().orderByIdAscending()) + .selectPaymentListWith(Q.payments().orderByIdAscending()) + .selectShipmentListWith(Q.shipments().orderByIdAscending()) + .limit(1) + .comment('what: load one complete order graph') + .purpose('why: inspect items, payment and fulfillment together') + .executeForList(ctx)`,run:t=>u.customerOrders().withOrderNumberIs("TQL-2026-1003").selectPlatformWith(u.platforms()).selectCustomerWith(u.customers()).selectStatusWith(u.orderStatuses().selectName().selectColor()).selectItemListWith(u.orderItems().orderByIdAscending()).selectPaymentListWith(u.payments().orderByIdAscending()).selectShipmentListWith(u.shipments().orderByIdAscending()).limit(1).comment("what: load one complete order graph").purpose("why: inspect items, payment and fulfillment together").executeForList(t.context)},{id:"customers-with-order-count",title:"用户与订单数",description:"列出用户,并通过关联汇总显示每位用户的订单数量。",code:`await Q.customers() + .selectPlatformWith(Q.platforms().selectName()) + .countOrderListAs('orderCount') + .orderByNameAscending() + .comment('what: list customers with related order counts') + .purpose('why: compare customer activity at a glance') + .executeForList(ctx)`,run:t=>u.customers().selectPlatformWith(u.platforms().selectName()).countOrderListAs("orderCount").orderByNameAscending().comment("what: list customers with related order counts").purpose("why: compare customer activity at a glance").executeForList(t.context)}]},{label:"汇总查询",description:"分组、计数、求和与平均值",queries:[{id:"orders-by-status",title:"订单状态汇总",description:"按币种与订单状态统计订单数、总额和平均客单价。",code:`await Q.customerOrders() + .groupByCurrency().groupByStatus() + .countAs('orderCount') + .sumTotalAmountAs('grossAmount') + .averageTotalAmountAs('averageOrderValue') + .comment('what: aggregate orders by currency and status') + .purpose('why: show the current order funnel') + .executeForRows(ctx)`,run:t=>u.customerOrders().groupByCurrency().groupByStatus().countAs("orderCount").sumTotalAmountAs("grossAmount").averageTotalAmountAs("averageOrderValue").comment("what: aggregate orders by currency and status").purpose("why: show the current order funnel").executeForRows(t.context)},{id:"product-sales",title:"商品销售汇总",description:"按商品汇总销量与销售额,找出最受欢迎的订单明细。",code:`await Q.orderItems() + .groupByProductName() + .sumQuantityAs('units') + .sumLineAmountAs('revenue') + .comment('what: aggregate sold units and line revenue') + .purpose('why: identify the strongest products in the demo data') + .executeForRows(ctx)`,run:t=>u.orderItems().groupByProductName().sumQuantityAs("units").sumLineAmountAs("revenue").comment("what: aggregate sold units and line revenue").purpose("why: identify the strongest products in the demo data").executeForRows(t.context)},{id:"payment-reconciliation",title:"支付渠道对账",description:"按币种、支付渠道和状态汇总笔数与金额。",code:`await Q.payments() + .groupByCurrency().groupByProvider().groupByStatus() + .countAs('paymentCount').sumAmountAs('paymentAmount') + .orderByCurrencyAscending().orderByProviderAscending() + .comment('what: reconcile payment totals by provider') + .purpose('why: compare captured, pending and refunded money') + .executeForRows(ctx)`,run:t=>u.payments().groupByCurrency().groupByProvider().groupByStatus().countAs("paymentCount").sumAmountAs("paymentAmount").orderByCurrencyAscending().orderByProviderAscending().comment("what: reconcile payment totals by provider").purpose("why: compare captured, pending and refunded money").executeForRows(t.context)}]},{label:"过滤查询",description:"精确、范围与组合条件",queries:[{id:"pending-payment",title:"待支付订单",description:"筛选尚未完成付款的订单,并带出对应支付记录。",code:`await Q.customerOrders() + .withStatusIsPendingPayment() + .selectStatusWith(Q.orderStatuses().selectName().selectColor()) + .selectCustomerWith(Q.customers().selectName()) + .selectPaymentListWith(Q.payments()) + .comment('what: find orders awaiting payment') + .purpose('why: support payment follow-up') + .executeForList(ctx)`,run:t=>u.customerOrders().withStatusIsPendingPayment().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectCustomerWith(u.customers().selectName()).selectPaymentListWith(u.payments()).comment("what: find orders awaiting payment").purpose("why: support payment follow-up").executeForList(t.context)},{id:"large-cn-orders",title:"国内大额订单",description:"组合平台与金额条件,找出 TeaQL 商城中金额不低于 500 元的订单。",code:`await Q.customerOrders() + .withPlatformIdIs('1') + .withTotalAmountGreaterThanOrEqualTo(500) + .selectCustomerWith(Q.customers().selectName().selectCity()) + .orderByTotalAmountDescending() + .comment('what: find high-value domestic orders') + .purpose('why: prioritize valuable fulfillment work') + .executeForList(ctx)`,run:t=>u.customerOrders().withPlatformIdIs("1").withTotalAmountGreaterThanOrEqualTo(500).selectCustomerWith(u.customers().selectName().selectCity()).orderByTotalAmountDescending().comment("what: find high-value domestic orders").purpose("why: prioritize valuable fulfillment work").executeForList(t.context)},{id:"open-shipments",title:"运输中的包裹",description:"筛选待揽收和运输中的物流单,并关联订单信息。",code:`await Q.shipments() + .withStatusIn('READY', 'IN_TRANSIT') + .selectOrderWith(Q.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(Q.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()) + .orderByStatusAscending().orderByIdAscending() + .comment('what: find shipments that are not delivered') + .purpose('why: monitor active fulfillment') + .executeForList(ctx)`,run:t=>u.shipments().withStatusIn("READY","IN_TRANSIT").selectOrderWith(u.customerOrders().selectOrderNumber().selectOrderDate().selectStatusWith(u.orderStatuses().selectName().selectColor()).selectTotalAmount().selectCurrency()).orderByStatusAscending().orderByIdAscending().comment("what: find shipments that are not delivered").purpose("why: monitor active fulfillment").executeForList(t.context)}]},{label:"动态查询",description:"由页面条件安全生成,不使用 eval",queries:[{id:"dynamic-paid-cn",title:"动态:已付款国内订单",description:"从动态条件对象生成查询:人民币、金额至少 250,且状态为已付款或已发货。",code:`const input = { + "filter": { + "currency": "CNY", + "totalAmount": { "$gte": "250" }, + "status": { "$in": ["PAID", "SHIPPED"] } + }, + "orderBy": [{ "field": "totalAmount", "direction": "desc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>Y(t,{filter:{currency:"CNY",totalAmount:{$gte:"250"},status:{$in:["PAID","SHIPPED"]}},orderBy:[{field:"totalAmount",direction:"desc"}]})},{id:"dynamic-date-range",title:"动态:九月新订单",description:"运行时传入日期范围与排序方式,查询 9 月 15 日之后的订单。",code:`const input = { + "filter": { "orderDate": { "$gte": "2026-09-15" } }, + "orderBy": [{ "field": "orderDate", "direction": "asc" }] +}; +const data = await Q.customerOrders() + .filterByJson(input) + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx);`,run:t=>Y(t,{filter:{orderDate:{$gte:"2026-09-15"}},orderBy:[{field:"orderDate",direction:"asc"}]})},{id:"dynamic-safe-fields",title:"动态:字段白名单",description:"未知字段会被报告并忽略;合法条件仍可安全执行。",code:`const input = { + "filter": { + "status": "DELIVERED", + "internalNote": { "$contains": "not queryable" } + } +}; +const request = Q.customerOrders().filterByJson(input); +const data = await request + .limit(20) + .comment('what: execute a validated browser search') + .purpose('why: demonstrate safe dynamic order discovery') + .executeForList(ctx); +const warnings = request.warnings();`,run:t=>Y(t,{filter:{status:"DELIVERED",internalNote:{$contains:"not queryable"}}})}]}],le=Ce.flatMap(t=>t.queries);async function it(t){const e=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),r=await Qe.open(e,{...V},{storage:t,databaseName:"teaql-order-playground-v4.sqlite3"}),n=new Be().enableSelect();r.install(new Re(V,{},{constants:Me})),r.setRuntimeTelemetrySink(n).setDiagnosticSQLLogSink(void 0);const s=Object.freeze({policyId:"browser-order-demo-seed",version:"1",fingerprint:"sha256:browser-order-demo-seed-v2"}),o=new $e().insertResource("dataService",r).withMutationPolicyRegistry(new ke(()=>({identity:s,review:(a,i)=>i.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Fe(a=>({policy:a,approvedBy:"browser-demo-owner",approvedAt:new Date})));return r.setUserContext(o),await o.ensureSchema(),{client:r,context:o,evidence:n}}async function Ie(t){if((await u.customerOrders().selectId().limit(1).comment("what: detect existing order playground data").purpose("why: keep deterministic browser bootstrap idempotent").executeForList(t.context)).length)return;const r=new ze("Seed deterministic order playground data");await t.client.executeGraphSave(r,async n=>{const s=pe.map(o=>n.request({entity:o.entity,action:"Create",id:o.id,payload:Object.fromEntries(Object.entries(o.payload).map(([a,i])=>{const c=V[o.entity]?.columns[a];if(!c)throw new Error(`Unknown fixture field ${o.entity}.${a}`);return[c.modelName??a,i]}))}));for(const o of s)t.client.preflightMutation(o);for(const o of s)await t.client.executeMutation(o)})}function dt(){k.replaceChildren();for(const t of Ce){const e=document.createElement("section");e.className="query-group";const r=document.createElement("div");r.className="query-group-heading";const n=document.createElement("h2");n.textContent=O(t.label);const s=document.createElement("p");s.textContent=O(t.description),r.append(n,s);const o=document.createElement("div");o.className="query-links";for(const a of t.queries){const i=document.createElement("a");i.href=`#${a.id}`,i.dataset.queryId=a.id,i.textContent=O(a.title),i.addEventListener("click",c=>{c.preventDefault(),z=a.id,history.replaceState(null,"",`#${a.id}`),Z(),E&&v(a,E).catch(L)}),o.append(i)}e.append(r,o),k.append(e)}Z()}function Z(){k.querySelectorAll("a[data-query-id]").forEach(t=>{const e=t.dataset.queryId===z;t.classList.toggle("active",e),e?t.setAttribute("aria-current","page"):t.removeAttribute("aria-current")})}async function v(t,e){const r=performance.now(),n=new Date;e.evidence.enableSelect(),w.classList.add("loading"),w.setAttribute("aria-busy","true"),ye.textContent=O(t.title),he.textContent=O(t.description),ce.textContent=t.code,Ze.classList.toggle("hidden",t.view!=="dashboard"),Je.textContent=t.view==="dashboard"?JSON.stringify({searchParams:Se(A.search),pageOffset:A.page*A.pageSize,pageSize:A.pageSize},null,2):"",Xe.classList.toggle("dashboard-mode",t.view==="dashboard"),w.classList.toggle("dashboard-result",t.view==="dashboard"),ee.closest(".tree-actions")?.classList.toggle("hidden",t.view==="dashboard"),B.textContent=t.view==="dashboard"?d==="en"?"Order management center":"订单管理中心":d==="en"?"Result tree":"结果树",X.textContent=d==="en"?"Running query…":"查询中…";try{const s=await t.run(e);t.view==="dashboard"&&(ce.textContent=s.queryExpression),T={data:s,query:t,active:e},b=t.view==="dashboard"||J(s)?"table":"tree",W();const o=Math.max(1,Math.round(performance.now()-r));fe=o,te=n;const a=e.evidence.snapshot();be(a,n),Ne(s,t,o)}finally{w.classList.remove("loading"),w.removeAttribute("aria-busy")}}function be(t,e=te){ue.replaceChildren(),et.textContent=d==="en"?`${t.length} statement${t.length===1?"":"s"}`:`${t.length} 条语句`,t.forEach((r,n)=>{const s=document.createElement("tr");s.className="evidence-row";const o=[...r.tracePath].reverse().find(l=>l.kind==="relation"||l.kind==="request"||l.kind==="entity"),a=document.createElement("td");a.className="evidence-time",a.dataset.executedAt=e?.toISOString()??"",a.textContent=`${e?.toISOString()??"—"} · ${Math.max(.01,r.elapsedMicros/1e3).toFixed(2)} ms`;const i=document.createElement("td");i.textContent=`${T?.query.id??"query"} · #${n+1} · ${o?.name??"query"}`;const c=document.createElement("td");if(c.className="evidence-trace",r.traceChain?.length){const l=r.traceChain.find(g=>g.kind==="purpose"),S=r.traceChain.filter(g=>g.kind==="comment").map(g=>g.detail||g.name);c.textContent=`${l?.detail||l?.name||""}: ${S.join(" → ")}`}else c.textContent=r.tracePath.map(l=>l.detail||l.name).join(" → ");const m=document.createElement("td");m.className="evidence-sql";const p=r.parameters.length?r.parameters.map(l=>String(l)).join(", "):"none";m.textContent=`${r.parameterizedSQL} · bindings: ${p}`,s.append(a,i,c,m),ue.append(s)})}function J(t){return Array.isArray(t)&&t.every(e=>e!==null&&typeof e=="object"&&!Array.isArray(e))}function W(){if(!T)return;const{data:t,query:e,active:r}=T,n=e.view==="dashboard"||J(t);if(n||(b="tree"),Q.disabled=!n,Q.classList.toggle("active",b==="table"),H.classList.toggle("active",b==="tree"),Q.setAttribute("aria-pressed",String(b==="table")),H.setAttribute("aria-pressed",String(b==="tree")),ee.closest(".tree-actions")?.classList.toggle("hidden",b!=="tree"),b==="table"&&e.view==="dashboard"){B.textContent=d==="en"?"Result table":"结果表格",mt(t,r,e);return}if(b==="table"&&J(t)){B.textContent=d==="en"?"Result table":"结果表格",ut(t);return}B.textContent=d==="en"?"Result tree":"结果树",Ee(e.view==="dashboard"?ct(t):t)}function ct(t){return{orders:t.orders,totalOrders:t.totalOrders,filteredOrders:t.filteredOrders,statusFacets:t.statusFacets,search:t.search,page:t.page,pageSize:t.pageSize}}function ut(t){const e=document.createElement("div");if(e.className="result-table-shell",!t.length){const i=document.createElement("p");i.className="result-table-empty",i.textContent=d==="en"?"The query returned no records.":"查询没有返回记录。",e.append(i),w.replaceChildren(e);return}const r=[...new Set(t.flatMap(i=>Object.keys(i)))],n=document.createElement("table");n.className="result-table";const s=document.createElement("thead"),o=document.createElement("tr");for(const i of r){const c=document.createElement("th");c.scope="col",c.textContent=i,o.append(c)}s.append(o);const a=document.createElement("tbody");for(const i of t){const c=document.createElement("tr");for(const m of r){const p=document.createElement("td");p.textContent=lt(i[m]),c.append(p)}a.append(c)}n.append(s,a),e.append(n),w.replaceChildren(e)}function lt(t){if(t==null)return"—";if(Array.isArray(t))return d==="en"?`${t.length} items`:`${t.length} 项`;if(t instanceof Date)return t.toISOString();if(typeof t=="object"){const e=t,r=re(e);if(r)return we(r);const n=e.name??e.orderNumber??e.code??e.id;return n===void 0?d==="en"?`${Object.keys(e).length} fields`:`${Object.keys(e).length} 个字段`:String(n)}return String(t)}function mt(t,e,r){const n=document.createElement("div");n.className="order-center";const s=document.createElement("div");s.className="order-center-toolbar";const o=document.createElement("div"),a=document.createElement("h3");a.textContent=d==="en"?"Order Management Center":"订单管理中心";const i=document.createElement("p");i.textContent=d==="en"?"One generated Q expression describes the entire page":"一个生成式 Q 表达式描述整个页面",o.append(a,i);const c=document.createElement("form");c.className="order-search";const m=document.createElement("input");m.type="search",m.placeholder=d==="en"?"Order number, status, or product…":"订单号、状态或商品名称…",m.value=t.search,m.setAttribute("aria-label",d==="en"?"Search orders":"搜索订单");const p=document.createElement("button");p.type="submit",p.className="order-search-submit",p.setAttribute("aria-label",d==="en"?"Run order query":"执行订单查询"),p.title=d==="en"?"Search":"查询";const l=document.createElement("span");l.className="search-icon",l.setAttribute("aria-hidden","true"),p.append(l),c.append(m,p),c.addEventListener("submit",y=>{y.preventDefault(),A.search=m.value.trim(),A.page=0,v(r,e).catch(L)}),s.append(o,c);const S=document.createElement("div");S.className="order-metrics",S.append(me(d==="en"?"All orders":"全部订单",t.totalOrders,"total","#2B66D9",!t.search,()=>{A.search="",A.page=0,v(r,e).catch(L)}));for(const y of t.statusFacets)S.append(me(y.name,y.orderCount,y.code.toLowerCase(),y.color,t.search.toUpperCase()===y.code,()=>{A.search=y.code,A.page=0,v(r,e).catch(L)},`${d==="en"?"Total":"总额"} ${pt(y.orderTotalAmount)}`));const g=document.createElement("div");g.className="order-table";const M=document.createElement("div");M.className="order-row order-row-head";const Te=d==="en"?["Order number","Order date","Status","Line Items"]:["订单号","订单日期","状态","订单明细"];for(const y of Te){const q=document.createElement("span");q.textContent=y,M.append(q)}if(g.append(M),!t.orders.length){const y=document.createElement("div");y.className="order-empty",y.textContent=d==="en"?"No matching orders. Try an order number, status code, or product name.":"没有匹配的订单,请尝试订单号、状态英文或商品名称。",g.append(y)}for(const y of t.orders)g.append(yt(y));const _=document.createElement("div");_.className="order-center-footer";const se=document.createElement("p"),oe=t.filteredOrders?t.page*t.pageSize+1:0,ae=Math.min(t.filteredOrders,(t.page+1)*t.pageSize);se.textContent=d==="en"?`Showing ${oe}–${ae} of ${t.filteredOrders} orders`:`显示 ${oe}–${ae},共 ${t.filteredOrders} 条订单`;const D=document.createElement("div");D.className="pagination";const ie=Math.max(1,Math.ceil(t.filteredOrders/t.pageSize));D.append(j("‹",t.page-1,t.page===0,e,r));for(let y=0;y=ie-1,e,r)),_.append(se,D),n.append(s,S,g,_),w.replaceChildren(n)}function me(t,e,r,n,s,o,a){const i=document.createElement("button");i.type="button",i.className=`metric-card metric-${r}`,n&&i.style.setProperty("--metric-color",n),i.classList.toggle("active",s);const c=document.createElement("span");c.textContent=t;const m=document.createElement("strong");if(m.textContent=String(e),i.append(c,m),a){const p=document.createElement("small");p.textContent=a,i.append(p)}return i.addEventListener("click",o),i}function pt(t){return new Intl.NumberFormat(d==="en"?"en-US":"zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2}).format(t)}function yt(t){const e=document.createElement("div");e.className="order-row";const r=t.status??{},n=Array.isArray(t.itemList)?t.itemList:[];[String(t.orderNumber??""),String(t.orderDate??"")].forEach(l=>{const S=document.createElement("span");S.className="order-primary",S.textContent=l,e.append(S)});const o=document.createElement("span"),a=document.createElement("span"),i=re(r);a.className=`status-badge status-${i.toLowerCase()}`,a.textContent=we(i)||String(r.name??i);const c=String(r.color??"");c&&(a.style.color=c,a.style.backgroundColor=`${c}18`),o.append(a),e.append(o);const m=document.createElement("span");m.className="product-preview",n.forEach((l,S)=>{const g=document.createElement("span");g.className=`product-thumb product-tone-${S%3}`,g.textContent=String(l.productName??"?").slice(0,1),g.title=`${String(l.productName??"")} × ${String(l.quantity??1)}`,m.append(g)});const p=Number(t.itemCount??n.length);if(p>n.length){const l=document.createElement("small");l.className="line-item-count",l.textContent=d==="en"?`${p} items`:`共 ${p} 项`,l.title=d==="en"?`Showing ${n.length} of ${p} line items`:`显示 ${n.length} 项,共 ${p} 项订单明细`,m.append(l)}return e.append(m),e}function j(t,e,r,n,s){const o=document.createElement("button");return o.type="button",o.textContent=t,o.disabled=r,o.addEventListener("click",()=>{A.page=e,v(s,n).catch(L)}),o}function we(t){return(d==="en"?{PENDING_PAYMENT:"Pending payment",PAID:"Paid",SHIPPED:"Shipped",DELIVERED:"Delivered",CANCELLED:"Cancelled"}:{PENDING_PAYMENT:"待支付",PAID:"已支付",SHIPPED:"运输中",DELIVERED:"已完成",CANCELLED:"已取消"})[t]??t}function Ee(t){w.replaceChildren(Le(t,"result",0))}function Le(t,e,r){if(t!==null&&typeof t=="object"){const a=Array.isArray(t)?t.map((S,g)=>[String(g),S]):Object.entries(t),i=document.createElement("details");i.className="tree-branch",i.open=r===0;const c=document.createElement("summary"),m=document.createElement("span");m.className="tree-key",m.textContent=e;const p=document.createElement("span");p.className="tree-preview",p.textContent=ht(t,a.length),c.append(m,p),i.append(c);const l=document.createElement("div");l.className="tree-children";for(const[S,g]of a)l.append(Le(g,Array.isArray(t)?`#${Number(S)+1}`:S,r+1));return i.append(l),i}const n=document.createElement("div");n.className="tree-leaf";const s=document.createElement("span");s.className="tree-key",s.textContent=e;const o=document.createElement("span");return o.className=`tree-value tree-${t===null?"null":typeof t}`,o.textContent=t===null?"null":typeof t=="string"?`“${t}”`:String(t),n.append(s,o),n}function ht(t,e){if(Array.isArray(t))return d==="en"?`${e} items`:`${e} 项`;const r=t,n=r.orderNumber??r.name??r.productName??r.transactionId??r.trackingNumber;return n?String(n):d==="en"?`${e} fields`:`${e} 个字段`}function gt(t){return Array.isArray(t)?t.length:Array.isArray(t?.data)?t.data.length:1}function Ne(t,e,r){const n=e.view==="dashboard"?t.filteredOrders:gt(t),s=d==="en"?`${n} ${e.view==="dashboard"?`matching order${n===1?"":"s"}`:`result${n===1?"":"s"}`}`:`${n} 条${e.view==="dashboard"?"匹配订单":"结果"}`;X.textContent=`${s} · ${r} ms · ${d==="en"?"in-browser SQLite":"浏览器内 SQLite"}`}function Oe(t){const e=pe.filter(r=>r.entity==="CustomerOrder").length;F.textContent=d==="en"?`${t.toUpperCase()} · ${e} orders · 7 entities · policy installed · ready`:`${t.toUpperCase()} · ${e} 个订单 · 7 个实体 · 已安装策略 · 就绪`}function ve(){document.documentElement.lang=d==="en"?"en":"zh-CN",document.title=d==="en"?"TeaQL Order Query Playground":"TeaQL 订单查询演练场";const t=document.querySelector('meta[name="description"]');if(t&&(t.content=d==="en"?"A TeaQL order-query playground running entirely in the browser":"完全运行在浏览器中的 TeaQL 订单查询演练场"),document.querySelectorAll("[data-i18n]").forEach(e=>{const r=e.dataset.i18n;r&&(e.textContent=st(r))}),ge.forEach(e=>{const r=e.dataset.locale===d;e.classList.toggle("active",r),e.setAttribute("aria-pressed",String(r))}),document.querySelector(".language-switch")?.setAttribute("aria-label",d==="en"?"Language":"语言"),document.querySelector(".brand")?.setAttribute("aria-label",d==="en"?"TeaQL Playground home":"TeaQL 演练场首页"),document.querySelector(".model-map")?.setAttribute("aria-label",d==="en"?"Order domain model":"订单领域模型"),document.querySelector(".runtime-language-selector")?.setAttribute("aria-label",d==="en"?"TeaQL runtimes":"TeaQL 运行时"),document.querySelector(".runtime-bar")?.setAttribute("aria-label",d==="en"?"Runtime settings":"运行时设置"),k.setAttribute("aria-label",d==="en"?"Example queries":"示例查询"),document.querySelector(".result-view-switch")?.setAttribute("aria-label",d==="en"?"Result views":"结果视图"),document.querySelector(".tree-actions")?.setAttribute("aria-label",d==="en"?"Result tree actions":"结果树操作"),dt(),T){const{data:e,query:r,active:n}=T;ye.textContent=O(r.title),he.textContent=O(r.description),W(),be(n.evidence.snapshot(),te),Ne(e,r,fe),Oe($.checked?"opfs":"memory")}else F.textContent=d==="en"?"Starting SQLite/WASM…":"正在启动 SQLite/WASM…"}function ne(){return le.find(t=>t.id===z)??le[0]}async function Pe(t){F.textContent=d==="en"?`Opening ${t.toUpperCase()} SQLite/WASM…`:`正在打开 ${t.toUpperCase()} SQLite/WASM…`;const e=E;E=void 0,await e?.client.close();const r=await it(t);E=r,await Ie(r),await v(ne(),r),Oe(t)}$.addEventListener("change",()=>{const t=$.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",t),Pe(t).catch(L)});G.addEventListener("click",async()=>{if(E){G.disabled=!0;try{await E.client.reset(E.context),await Ie(E),await v(ne(),E)}catch(t){L(t)}finally{G.disabled=!1}}});ee.addEventListener("click",()=>{w.querySelectorAll("details").forEach(t=>{t.open=!0})});Q.addEventListener("click",()=>{Q.disabled||(b="table",W())});H.addEventListener("click",()=>{b="tree",W()});tt.addEventListener("click",()=>{w.querySelectorAll("details").forEach((t,e)=>{t.open=e===0})});ge.forEach(t=>{t.addEventListener("click",()=>{d=t.dataset.locale==="zh"?"zh":"en",localStorage.setItem("teaql-browser-locale",d),ve()})});function L(t){const e=t instanceof Error?t:new Error(String(t));F.textContent=`${e.name}: ${e.message}`,X.textContent=d==="en"?"Query failed":"查询失败",Ee({error:e.name,message:e.message})}ve();z=ne().id;Z();Pe(Ae).catch(L); diff --git a/dist/assets/orders-DBfzfR_e.js b/dist/assets/orders-DBfzfR_e.js new file mode 100644 index 0000000000000000000000000000000000000000..45ca2800723e6fb607fbbeae6773510c11607b98 --- /dev/null +++ b/dist/assets/orders-DBfzfR_e.js @@ -0,0 +1,2 @@ +import{d as p,S as bt,f as Y,E as k,a as L,g as Z,L as d,M as N,C as g,n as tt,i as X,h as mt,j as et,e as M,Q as rt,U as H,R as Nt,B as Et,D as $t,c as Tt,b as Dt}from"./dynamic-search-BwvXmN4R.js";import{EntityCreationError as it,EntityCreation as E}from"./entity-creation-Bqaw1C4U.js";/* empty css */class D{constructor(t,e,r,i,s){this.rootExpression=t,this.profile=e,this.location=r,this.steps=i,this.missing=s}static root(t,e="camelCase"){return new D(t,e,p.root(),[])}member(t,e){return this.append(`${e}()`,this.location.property(t),!0)}index(t,e=!1){return this.append(e?"first()":`get(${t})`,this.location.index(t),!0)}operation(t){return this.append(t,this.location,!1)}append(t,e,r){return new D(this.rootExpression,this.profile,e,[...this.steps,{call:t,location:e,traverses:r}],this.missing)}markMissing(){return new D(this.rootExpression,this.profile,this.location,this.steps,this.missing??this.steps.length-1)}withFailureFrom(t){return new D(this.rootExpression,this.profile,this.location,this.steps,t.missing)}render(t=!1){return this.rootExpression+this.steps.map((e,r)=>`.${e.call}${t&&r===this.missing?"":""}`).join("")}diagnostic(t){const e=this.missing===void 0?this.location:this.steps[this.missing].location,r=e.segments[e.segments.length-1];return{code:"NOT_LOADED",location:e.segments,instancePath:e.instancePath(this.profile),breakPoint:r?.kind==="property"?r.name:t,attemptedLocation:this.location.segments,attemptedInstancePath:this.location.instancePath(this.profile),breakPointIndex:Math.max(0,e.segments.length-1),originalExpression:this.render(),expressionWithBrokenPoint:this.render(!0),suggestedFix:{action:"preload",location:e.segments}}}}class v extends Error{constructor(t,e){const r=t.diagnostic(e),i=r.location.reduce((s,o)=>o.kind==="index"?s.index(o.index):s.property(o.name),p.root());super(`TeaQLNotLoadedError: access_path=${i.nativePath()} break_point=${r.breakPoint} — select the missing field or relation expression=${r.expressionWithBrokenPoint}`),this.path=t,this.breakPoint=e,this.name="TeaQLNotLoadedError",this.details=r}withPath(t){return new v(t.withFailureFrom(this.path),this.breakPoint)}terminal(t){return new v(this.path.operation(t),this.breakPoint)}toWire(){return this.details}}class O extends bt{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,r="id",i="id",s=!0,o){return super.relationQuery(t,e,r,i,s,o)}}const nt=Symbol("managed entity construction");class T{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("Customer",["id","platform","name","version"],{id:"immutable_field",version:"immutable_field"});id;platform;name;version;constructor(t,e,r=!1){if(e!==nt)throw new it;if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--T.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.customerOrderList,Object.assign(this,s),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof C?t.platform:C.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const o=t.customerOrderList;this._customerOrderList=new L(o.map(n=>n instanceof b?n:b.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("customerOrderList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Customer",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._customerOrderList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new T(t,nt));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("customerOrderList")&&(t.customerOrderList=this._customerOrderList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return T.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"Customer",e,r=>new T({id:r},nt,!0))}static teaqlCreate(t){return E.create(t,"Customer",e=>new T({id:e},nt,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._customerOrderList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._customerOrderList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("customer_order_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(T.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._customerOrderList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(T.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},customer_order_list:t.sourceMembers(this._customerOrderList)}));for(const r of this._customerOrderList){r.teaqlAttachRoot(this._root);const i=r.customer;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("customer")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updateCustomer(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),T.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"Customer",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._customerOrderList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("customer_order_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(T.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"id",canonical:"id"},{member:"platform",canonical:"platform"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"Customer",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"Customer",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const w=a.customer;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("customer")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updateCustomer(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("customer_order_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"Customer",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const _=y.customer;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("customer")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updateCustomer(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("customer_order_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._customerOrderList.entries()){q.teaqlAttachRoot(this._root);const y=q.customer;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("customer")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updateCustomer(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("customer_order_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,platform:this.platform,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}const at=Symbol("managed entity construction");class Q{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("OrderItem",["id","customer_order","product_name","quantity","unit_price","version"],{id:"immutable_field",version:"immutable_field"});id;customerOrder;productName;quantity;unitPrice;version;constructor(t,e,r=!1){if(e!==at)throw new it;{const s=X(t?.quantity,"OrderItem","quantity");if(s)throw s}if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--Q.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];Object.assign(this,s),t.customerOrder&&typeof t.customerOrder=="object"&&(this.customerOrder=t.customerOrder instanceof b?t.customerOrder:b.fromRecord(t.customerOrder),this.markLoaded("customerOrder"))}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"OrderItem",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const r=E.hydrated(new Q(t,at));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){{const e=X(this.quantity,"OrderItem","quantity");if(e)throw e}return Object.fromEntries(Object.entries(this))}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return Q.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"OrderItem",e,r=>new Q({id:r},at,!0))}static teaqlCreate(t){return E.create(t,"OrderItem",e=>new Q({id:e},at,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());return E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),r}teaqlValidateLoadedIdentities(t=new Set){t.has(this)||(t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version))}teaqlDiscardRestoredGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(Q.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)))}teaqlNormalizeGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(Q.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{customer_order:"CustomerOrder"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()}})))}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),Q.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"OrderItem",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}return r}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(Q.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const l=[{member:"id",canonical:"id"},{member:"customerOrder",canonical:"customer_order"},{member:"productName",canonical:"product_name"},{member:"quantity",canonical:"quantity"},{member:"unitPrice",canonical:"unit_price"},{member:"version",canonical:"version"}].find(c=>!this.isLoaded(c.member));if(l)throw new g([{ruleId:"invalid_type",entityType:"OrderItem",location:p.property(l.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"OrderItem",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f),f.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"OrderItem",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return l.scopeFor(this.teaqlEntityKey()),this;const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();return l.scopeFor(m),e.afterGraphRollback(()=>{for(const S of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,S)||delete this[S];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m),l.scopeFor(m),e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,customer_order:this.customerOrder,product_name:this.productName,quantity:this.quantity,unit_price:this.unitPrice,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateProductName(t){return this.productName=t,this.markLoaded("productName"),this._root.set(this.teaqlEntityKey(),"product_name",t),this}updateQuantity(t){return this.quantity=t,this.markLoaded("quantity"),this._root.set(this.teaqlEntityKey(),"quantity",t),this}updateUnitPrice(t){return t!=null&&(t=mt(t)),this.unitPrice=t,this.markLoaded("unitPrice"),this._root.set(this.teaqlEntityKey(),"unit_price",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomerOrder(t){return this.customerOrder=t?.id??t,this.markLoaded("customerOrder"),this._root.set(this.teaqlEntityKey(),"customer_order",this.customerOrder),this}}const ut=Symbol("managed entity construction");class b{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("CustomerOrder",["id","customer","status","order_number","order_date","total_amount","version"],{id:"immutable_field",version:"immutable_field"});id;customer;status;orderNumber;orderDate;totalAmount;version;constructor(t,e,r=!1){if(e!==ut)throw new it;if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--b.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderItemList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.orderItemList,Object.assign(this,s),t.customer&&typeof t.customer=="object"&&(this.customer=t.customer instanceof T?t.customer:T.fromRecord(t.customer),this.markLoaded("customer")),t.status&&typeof t.status=="object"&&(this.status=t.status instanceof P?t.status:P.fromRecord(t.status),this.markLoaded("status")),Array.isArray(t.orderItemList)){const o=t.orderItemList;this._orderItemList=new L(o.map(n=>n instanceof Q?n:Q.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("orderItemList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"CustomerOrder",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._orderItemList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new b(t,ut));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("orderItemList")&&(t.orderItemList=this._orderItemList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return b.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"CustomerOrder",e,r=>new b({id:r},ut,!0))}static teaqlCreate(t){return E.create(t,"CustomerOrder",e=>new b({id:e},ut,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._orderItemList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._orderItemList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("order_item_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(b.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._orderItemList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(b.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{customer:"Customer",status:"OrderStatus"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},order_item_list:t.sourceMembers(this._orderItemList)}));for(const r of this._orderItemList){r.teaqlAttachRoot(this._root);const i=r.customerOrder;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("customerOrder")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updateCustomerOrder(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),b.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"CustomerOrder",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._orderItemList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("order_item_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(b.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"id",canonical:"id"},{member:"customer",canonical:"customer"},{member:"status",canonical:"status"},{member:"orderNumber",canonical:"order_number"},{member:"orderDate",canonical:"order_date"},{member:"totalAmount",canonical:"total_amount"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"CustomerOrder",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"CustomerOrder",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._orderItemList.entries()){a.teaqlAttachRoot(this._root);const w=a.customerOrder;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("customerOrder")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updateCustomerOrder(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("order_item_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"CustomerOrder",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._orderItemList.entries()){y.teaqlAttachRoot(this._root);const _=y.customerOrder;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("customerOrder")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updateCustomerOrder(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("order_item_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._orderItemList.entries()){q.teaqlAttachRoot(this._root);const y=q.customerOrder;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("customerOrder")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updateCustomerOrder(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("order_item_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,customer:this.customer,status:this.status,order_number:this.orderNumber,order_date:this.orderDate,total_amount:this.totalAmount,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateOrderNumber(t){return this.orderNumber=t,this.markLoaded("orderNumber"),this._root.set(this.teaqlEntityKey(),"order_number",t),this}updateOrderDate(t){return this.orderDate=t,this.markLoaded("orderDate"),this._root.set(this.teaqlEntityKey(),"order_date",t),this}updateTotalAmount(t){return t!=null&&(t=mt(t)),this.totalAmount=t,this.markLoaded("totalAmount"),this._root.set(this.teaqlEntityKey(),"total_amount",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updateCustomer(t){return this.customer=t?.id??t,this.markLoaded("customer"),this._root.set(this.teaqlEntityKey(),"customer",this.customer),this}updateStatus(t){return this.status=t?.id??t,this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToNew(){return this.status="1001",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToPaid(){return this.status="1002",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}updateStatusToCancelled(){return this.status="1003",this.markLoaded("status"),this._root.set(this.teaqlEntityKey(),"status",this.status),this}orderItemList(){return this._orderItemList}}const dt=Symbol("managed entity construction");class P{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("OrderStatus",["platform","id","name","code","color","display_order","version"],{id:"immutable_field",version:"immutable_field"});platform;id;name;code;color;displayOrder;version;constructor(t,e,r=!1){if(e!==dt)throw new it;{const s=X(t?.displayOrder,"OrderStatus","display_order");if(s)throw s}if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--P.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerOrderList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.customerOrderList,Object.assign(this,s),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof C?t.platform:C.fromRecord(t.platform),this.markLoaded("platform")),Array.isArray(t.customerOrderList)){const o=t.customerOrderList;this._customerOrderList=new L(o.map(n=>n instanceof b?n:b.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("customerOrderList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"OrderStatus",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._customerOrderList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new P(t,dt));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){{const e=X(this.displayOrder,"OrderStatus","display_order");if(e)throw e}const t=Object.fromEntries(Object.entries(this));return this.isLoaded("customerOrderList")&&(t.customerOrderList=this._customerOrderList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return P.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"OrderStatus",e,r=>new P({id:r},dt,!0))}static teaqlCreate(t){return E.create(t,"OrderStatus",e=>new P({id:e},dt,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._customerOrderList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._customerOrderList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("customer_order_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(P.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._customerOrderList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(P.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},customer_order_list:t.sourceMembers(this._customerOrderList)}));for(const r of this._customerOrderList){r.teaqlAttachRoot(this._root);const i=r.status;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("status")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updateStatus(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),P.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"OrderStatus",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._customerOrderList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("customer_order_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(P.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"platform",canonical:"platform"},{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"code",canonical:"code"},{member:"color",canonical:"color"},{member:"displayOrder",canonical:"display_order"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"OrderStatus",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"OrderStatus",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._customerOrderList.entries()){a.teaqlAttachRoot(this._root);const w=a.status;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("status")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updateStatus(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("customer_order_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"OrderStatus",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._customerOrderList.entries()){y.teaqlAttachRoot(this._root);const _=y.status;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("status")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updateStatus(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("customer_order_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._customerOrderList.entries()){q.teaqlAttachRoot(this._root);const y=q.status;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("status")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updateStatus(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("customer_order_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{platform:this.platform,id:this.id,name:this.name,code:this.code,color:this.color,display_order:this.displayOrder,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateCode(t){return this.code=t,this.markLoaded("code"),this._root.set(this.teaqlEntityKey(),"code",t),this}updateColor(t){return this.color=t,this.markLoaded("color"),this._root.set(this.teaqlEntityKey(),"color",t),this}updateDisplayOrder(t){return this.displayOrder=t,this.markLoaded("displayOrder"),this._root.set(this.teaqlEntityKey(),"display_order",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}customerOrderList(){return this._customerOrderList}}const ht=Symbol("managed entity construction");class C{static teaqlTemporaryId=0;static teaqlMutationFields=new Y("Platform",["id","name","version"],{id:"immutable_field",version:"immutable_field"});id;name;version;constructor(t,e,r=!1){if(e!==ht)throw new it;if(Object.defineProperty(this,"_action",{value:r?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:r,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--C.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_orderStatusList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),Object.defineProperty(this,"_customerList",{value:r?new L:L.empty(),writable:!0,enumerable:!1}),t){const s={...t};for(const o of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete s[o];if(delete s.orderStatusList,delete s.customerList,Object.assign(this,s),Array.isArray(t.orderStatusList)){const o=t.orderStatusList;this._orderStatusList=new L(o.map(n=>n instanceof P?n:P.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("orderStatusList")}if(Array.isArray(t.customerList)){const o=t.customerList;this._customerList=new L(o.map(n=>n instanceof T?n:T.fromRecord(n)),{totalCount:o.totalCount,aggregations:o.aggregations,summary:o.summary,facets:o.facets,isLoaded:o.isLoaded??!0}),this.markLoaded("customerList")}}const i=this.teaqlEntityKey();this.version!==void 0&&(this.version=Z(this.version)),this._action==="Create"?this._root.markAsNew(i):this.version!==void 0&&this._root.setOriginalVersion(i,this.version),d.captureFor(this,this.teaqlMutationPayload(),i,this.version,r?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const r of this._orderStatusList)r.teaqlAttachRoot(t,e);for(const r of this._customerList)r.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const r=E.hydrated(new C(t,ht));return e?r.teaqlAttachRoot(e,!0):r}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("orderStatusList")&&(t.orderStatusList=this._orderStatusList),this.isLoaded("customerList")&&(t.customerList=this._customerList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return C.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return E.bootstrap(t,"Platform",e,r=>new C({id:r},ht,!0))}static teaqlCreate(t){return E.create(t,"Platform",e=>new C({id:e},ht,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new N(t).comment,this}async save(t){if(new N(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new N(this._comment),async r=>this.teaqlSaveWithinGraph(t,e,r),r=>{this.teaqlPreflightGraph(t,e,r),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),r.sealPreparedGraph()},r=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(r),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(r),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r);for(const i of this._orderStatusList)r=i.teaqlValidateMutationOrigins(t)||r;for(const i of this._customerList)r=i.teaqlValidateMutationOrigins(t)||r;return r}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),d.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,r]of this._orderStatusList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("order_status_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}for(const[e,r]of this._customerList.entries())try{r.teaqlValidateLoadedIdentities(t)}catch(i){if(!(i instanceof g))throw i;const s=p.property("customer_list").index(e);throw new g(i.violations.map(o=>({...o,location:o.location.prefixedBy(s)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(C.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));for(const r of this._orderStatusList)r.teaqlDiscardRestoredGraph(t,e);for(const r of this._customerList)r.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(C.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},order_status_list:t.sourceMembers(this._orderStatusList),customer_list:t.sourceMembers(this._customerList)}));for(const r of this._orderStatusList){r.teaqlAttachRoot(this._root);const i=r.platform;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("platform")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updatePlatform(this),r.teaqlNormalizeGraph(t,e)}for(const r of this._customerList){r.teaqlAttachRoot(this._root);const i=r.platform;(r._action!=="Update"||r._root.hasPending(r.teaqlEntityKey()))&&(this.id===void 0||!r.isLoaded("platform")||(typeof i=="object"&&i!==null?i.id:i)!==this.id)&&r.updatePlatform(this),r.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,r=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(E.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,r),d.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),C.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),r&&(tt(e,d.forEntity(this)?.persistedVersion),e==="Update")){const s=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(o=>!this.isLoaded(o.member));if(s)throw new g([{ruleId:"invalid_type",entityType:"Platform",location:p.property(s.canonical),message:"Mutation requires a fully loaded entity"}])}let i=r;for(const[s,o]of this._orderStatusList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("order_status_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}for(const[s,o]of this._customerList.entries())try{i=o.teaqlAdmitGraph(t)||i}catch(n){if(!(n instanceof g))throw n;const f=p.property("customer_list").index(s);throw new g(n.violations.map(l=>({...l,location:l.location.prefixedBy(f)})))}return i}teaqlPreflightGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return;s.add(this);const o=this._action;r.discardRestoredFields(C.teaqlMutationFields,this._root,this.teaqlEntityKey(),d.forEntity(this));const n=o!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(o==="Update"&&n){const c=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(c)throw new g([{ruleId:"invalid_type",entityType:"Platform",location:p.property(c.canonical),message:"Mutation requires a fully loaded entity"}])}const f=r.request({entity:"Platform",action:o,payload:o==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);n&&e.preflightMutation(f);const l=f.scopeFor(this.teaqlEntityKey());for(const[c,a]of this._orderStatusList.entries()){a.teaqlAttachRoot(this._root);const w=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("order_status_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}for(const[c,a]of this._customerList.entries()){a.teaqlAttachRoot(this._root);const w=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof w=="object"&&w!==null?w.id:w)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,r,l,s)}catch(m){if(!(m instanceof g))throw m;const R=p.property("customer_list").index(c);throw new g(t.translateCheckResults(m.violations.map(S=>({...S,location:S.location.prefixedBy(R)}))))}}}async teaqlSaveWithinGraph(t,e,r,i,s=new Set){if(i||new N(this._comment),s.has(this))return this;s.add(this);const o=this._action,n=this._root.change(this.teaqlEntityKey()),f={entity:"Platform",action:this._action,payload:o==="Update"?n:this.teaqlMutationPayload(),id:this.id,version:d.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},l=r.request(f,i,this._comment).withLoadedSnapshot(d.forEntity(this)??new d);if(o==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const I=l.scopeFor(this.teaqlEntityKey());for(const[q,y]of this._orderStatusList.entries()){y.teaqlAttachRoot(this._root);const _=y.platform;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("order_status_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}for(const[q,y]of this._customerList.entries()){y.teaqlAttachRoot(this._root);const _=y.platform;(y._action!=="Update"||y._root.hasPending(y.teaqlEntityKey()))&&(this.id===void 0||!y.isLoaded("platform")||(typeof _=="object"&&_!==null?_.id:_)!==this.id)&&y.updatePlatform(this);try{await y.teaqlSaveWithinGraph(t,e,r,I,s)}catch(A){if(!(A instanceof g))throw A;const $=p.property("customer_list").index(q);throw new g(t.translateCheckResults(A.violations.map(B=>({...B,location:B.location.prefixedBy($)}))))}}return this}const c=await e.executeMutation(l);if(r.validatePreparedSources(),!c.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:d.forEntity(this)},w=this.teaqlEntityKey();Object.assign(this,c.persistedRecord),this._ledgerId=this.id??this._ledgerId;const m=this.teaqlEntityKey();this._root.rekey(w,m);const R=this.teaqlScalarSnapshot();l.scopeFor(m),e.afterGraphRollback(()=>{for(const I of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,I)||delete this[I];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,d.restoreFor(this,a.loadedSnapshot),this._root.rekey(m,w)}),this._loadedFields=new Set(Object.keys(c.persistedRecord)),this._fullyLoaded=!1,f.action!=="Delete"&&(this._action="Update"),r.acceptPreparedResult(this._root,w,m);const S=l.scopeFor(m);for(const[I,q]of this._orderStatusList.entries()){q.teaqlAttachRoot(this._root);const y=q.platform;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("order_status_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}for(const[I,q]of this._customerList.entries()){q.teaqlAttachRoot(this._root);const y=q.platform;(q._action!=="Update"||q._root.hasPending(q.teaqlEntityKey()))&&(this.id===void 0||!q.isLoaded("platform")||(typeof y=="object"&&y!==null?y.id:y)!==this.id)&&q.updatePlatform(this);try{await q.teaqlSaveWithinGraph(t,e,r,S,s)}catch(_){if(!(_ instanceof g))throw _;const A=p.property("customer_list").index(I);throw new g(t.translateCheckResults(_.violations.map($=>({...$,location:$.location.prefixedBy(A)}))))}}return e.afterGraphCommit(()=>{r.validatePreparedSources(),d.restoreFor(this,R),this._root.clearEntity(m),this.version!==void 0&&this._root.acceptCommittedVersion(m,this.version),r.finishPreparedCommit(this._root,m)}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new d(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}orderStatusList(){return this._orderStatusList}customerList(){return this._customerList}}const st=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({orderStatusList:"OrderStatus",customerList:"Customer"})}),OrderStatus:Object.freeze({fields:Object.freeze({platform:"integer",id:"integer",name:"string",code:"string",color:"string",display_order:"integer",displayOrder:"integer",version:"integer"}),queryFields:Object.freeze({platform:"platform",id:"id",name:"name",code:"code",color:"color",display_order:"displayOrder",displayOrder:"displayOrder",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),Customer:Object.freeze({fields:Object.freeze({id:"integer",platform:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",platform:"platform",name:"name",version:"version"}),relations:Object.freeze({platform:"Platform",customerOrderList:"CustomerOrder"})}),CustomerOrder:Object.freeze({fields:Object.freeze({id:"integer",customer:"integer",status:"integer",order_number:"string",orderNumber:"string",order_date:"date",orderDate:"date",total_amount:"decimal",totalAmount:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer:"customer",status:"status",order_number:"orderNumber",orderNumber:"orderNumber",order_date:"orderDate",orderDate:"orderDate",total_amount:"totalAmount",totalAmount:"totalAmount",version:"version"}),relations:Object.freeze({customer:"Customer",status:"OrderStatus",orderItemList:"OrderItem"})}),OrderItem:Object.freeze({fields:Object.freeze({id:"integer",customer_order:"integer",customerOrder:"integer",product_name:"string",productName:"string",quantity:"integer",unit_price:"decimal",unitPrice:"decimal",version:"integer"}),queryFields:Object.freeze({id:"id",customer_order:"customerOrder",customerOrder:"customerOrder",product_name:"productName",productName:"productName",quantity:"quantity",unit_price:"unitPrice",unitPrice:"unitPrice",version:"version"}),relations:Object.freeze({customer_order:"CustomerOrder",customerOrder:"CustomerOrder"})})});class qt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Platform"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new kt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectOrderStatusListWith(t){return this.query.relationQuery("orderStatusList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectOrderStatusListWith",relation:"orderStatusList"}),this}selectCustomerListWith(t){return this.query.relationQuery("customerList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectCustomerListWith",relation:"customerList"}),this}haveOrderStatuses(){return this.withOrderStatusListMatching({entityName:"OrderStatus",toQuery:()=>new O("OrderStatus")})}haveNoOrderStatuses(){return this.withoutOrderStatusListMatching({entityName:"OrderStatus",toQuery:()=>new O("OrderStatus")})}withOrderStatusListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutOrderStatusListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}haveCustomers(){return this.withCustomerListMatching({entityName:"Customer",toQuery:()=>new O("Customer")})}haveNoCustomers(){return this.withoutCustomerListMatching({entityName:"Customer",toQuery:()=>new O("Customer")})}withCustomerListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutCustomerListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countOrderStatuses(){return this.countOrderStatusesAs("countOrderStatuses")}countOrderStatusesAs(t){const e=new O("OrderStatus").filter({version:{$gte:1}});return this.countOrderStatusesWith(t,{entityName:"OrderStatus",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderStatusesAs",relation:"orderStatusList",alias:t},this}countOrderStatusesWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"relation-count",method:"countOrderStatusesWith",relation:"orderStatusList",alias:t}),this}minDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.minDisplayOrderOfOrderStatusesAs("minOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}minDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"minDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}maxDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.maxDisplayOrderOfOrderStatusesAs("maxOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}maxDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"maxDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sumDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.sumDisplayOrderOfOrderStatusesAs("sumOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}sumDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sumDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}avgDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.avgDisplayOrderOfOrderStatusesAs("avgOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}avgDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"avgDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}standardDeviationDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.standardDeviationDisplayOrderOfOrderStatusesAs("standardDeviationOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}standardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"standardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs("squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}sampleVarianceDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.sampleVarianceDisplayOrderOfOrderStatusesAs("sampleVarianceOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}sampleVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"sampleVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}samplePopulationVarianceDisplayOrderOfOrderStatuses(){const t=new O("OrderStatus").filter({version:{$gte:1}});return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs("samplePopulationVarianceOfDisplayOrderOfOrderStatuses",{entityName:"OrderStatus",toQuery:()=>t})}samplePopulationVarianceDisplayOrderOfOrderStatusesAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","displayOrder",t),this.query.relationAggregate("orderStatusList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceDisplayOrderOfOrderStatusesAs",relation:"orderStatusList",alias:t}),this}countCustomers(){return this.countCustomersAs("countCustomers")}countCustomersAs(t){const e=new O("Customer").filter({version:{$gte:1}});return this.countCustomersWith(t,{entityName:"Customer",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomersAs",relation:"customerList",alias:t},this}countCustomersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerList",t,r,!0,{kind:"relation-count",method:"countCustomersWith",relation:"customerList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof C?n:C.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof C?a:C.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof C?n:C.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class kt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return C.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class wt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("OrderStatus"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"OrderStatus"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Rt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["platform","id","name","code","color","displayOrder","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectCode(){return this.query.select(["code"]),this}selectColor(){return this.query.select(["color"]),this}selectDisplayOrder(){return this.query.select(["displayOrder"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","status",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"status"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"status"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new O("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{entityName:"CustomerOrder",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withCodeContaining(t){return this.filters.push({code:{$contains:t}}),this}withCodeIs(t){return this.filters.push({code:{$eq:t}}),this}withCodeIsNot(t){return this.filters.push({code:{$ne:t}}),this}withCodeIn(...t){return this.filters.push({code:{$in:t}}),this}withCodeNotIn(...t){return this.filters.push({code:{$notIn:t}}),this}withCodeGreaterThan(t){return this.filters.push({code:{$gt:t}}),this}withCodeGreaterThanOrEqualTo(t){return this.filters.push({code:{$gte:t}}),this}withCodeLessThan(t){return this.filters.push({code:{$lt:t}}),this}withCodeLessThanOrEqualTo(t){return this.filters.push({code:{$lte:t}}),this}withCodeBetween(t,e){return this.filters.push({code:{$between:[t,e]}}),this}withCodeIsKnown(){return this.filters.push({code:{$isNull:!1}}),this}withCodeIsUnknown(){return this.filters.push({code:{$isNull:!0}}),this}withCodeNotContaining(t){return this.filters.push({code:{$notContains:t}}),this}withCodeStartingWith(t){return this.filters.push({code:{$startsWith:t}}),this}withCodeNotStartingWith(t){return this.filters.push({code:{$notStartsWith:t}}),this}withCodeEndingWith(t){return this.filters.push({code:{$endsWith:t}}),this}withCodeNotEndingWith(t){return this.filters.push({code:{$notEndsWith:t}}),this}withCodeSoundingLike(t){return this.filters.push({code:{$soundLike:t}}),this}withColorContaining(t){return this.filters.push({color:{$contains:t}}),this}withColorIs(t){return this.filters.push({color:{$eq:t}}),this}withColorIsNot(t){return this.filters.push({color:{$ne:t}}),this}withColorIn(...t){return this.filters.push({color:{$in:t}}),this}withColorNotIn(...t){return this.filters.push({color:{$notIn:t}}),this}withColorGreaterThan(t){return this.filters.push({color:{$gt:t}}),this}withColorGreaterThanOrEqualTo(t){return this.filters.push({color:{$gte:t}}),this}withColorLessThan(t){return this.filters.push({color:{$lt:t}}),this}withColorLessThanOrEqualTo(t){return this.filters.push({color:{$lte:t}}),this}withColorBetween(t,e){return this.filters.push({color:{$between:[t,e]}}),this}withColorIsKnown(){return this.filters.push({color:{$isNull:!1}}),this}withColorIsUnknown(){return this.filters.push({color:{$isNull:!0}}),this}withColorNotContaining(t){return this.filters.push({color:{$notContains:t}}),this}withColorStartingWith(t){return this.filters.push({color:{$startsWith:t}}),this}withColorNotStartingWith(t){return this.filters.push({color:{$notStartsWith:t}}),this}withColorEndingWith(t){return this.filters.push({color:{$endsWith:t}}),this}withColorNotEndingWith(t){return this.filters.push({color:{$notEndsWith:t}}),this}withColorSoundingLike(t){return this.filters.push({color:{$soundLike:t}}),this}withDisplayOrderIs(t){return this.filters.push({displayOrder:{$eq:t}}),this}withDisplayOrderIsNot(t){return this.filters.push({displayOrder:{$ne:t}}),this}withDisplayOrderIn(...t){return this.filters.push({displayOrder:{$in:t}}),this}withDisplayOrderNotIn(...t){return this.filters.push({displayOrder:{$notIn:t}}),this}withDisplayOrderGreaterThan(t){return this.filters.push({displayOrder:{$gt:t}}),this}withDisplayOrderGreaterThanOrEqualTo(t){return this.filters.push({displayOrder:{$gte:t}}),this}withDisplayOrderLessThan(t){return this.filters.push({displayOrder:{$lt:t}}),this}withDisplayOrderLessThanOrEqualTo(t){return this.filters.push({displayOrder:{$lte:t}}),this}withDisplayOrderBetween(t,e){return this.filters.push({displayOrder:{$between:[t,e]}}),this}withDisplayOrderIsKnown(){return this.filters.push({displayOrder:{$isNull:!1}}),this}withDisplayOrderIsUnknown(){return this.filters.push({displayOrder:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByCodeAscending(){return this.query.orderBy("code","asc"),this}orderByCodeDescending(){return this.query.orderBy("code","desc"),this}orderByColorAscending(){return this.query.orderBy("color","asc"),this}orderByColorDescending(){return this.query.orderBy("color","desc"),this}orderByDisplayOrderAscending(){return this.query.orderBy("displayOrder","asc"),this}orderByDisplayOrderDescending(){return this.query.orderBy("displayOrder","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minDisplayOrder(){return this.minDisplayOrderAs("minOfDisplayOrder")}minDisplayOrderAs(t){return this.query.aggregate("min","displayOrder",t),this}maxDisplayOrder(){return this.maxDisplayOrderAs("maxOfDisplayOrder")}maxDisplayOrderAs(t){return this.query.aggregate("max","displayOrder",t),this}sumDisplayOrder(){return this.sumDisplayOrderAs("sumOfDisplayOrder")}sumDisplayOrderAs(t){return this.query.aggregate("sum","displayOrder",t),this}avgDisplayOrder(){return this.avgDisplayOrderAs("avgOfDisplayOrder")}avgDisplayOrderAs(t){return this.query.aggregate("avg","displayOrder",t),this}standardDeviationDisplayOrder(){return this.standardDeviationDisplayOrderAs("standardDeviationOfDisplayOrder")}standardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev","displayOrder",t),this}squareRootOfPopulationStandardDeviationDisplayOrder(){return this.squareRootOfPopulationStandardDeviationDisplayOrderAs("squareRootOfPopulationStandardDeviationOfDisplayOrder")}squareRootOfPopulationStandardDeviationDisplayOrderAs(t){return this.query.aggregate("stddev_pop","displayOrder",t),this}sampleVarianceDisplayOrder(){return this.sampleVarianceDisplayOrderAs("sampleVarianceOfDisplayOrder")}sampleVarianceDisplayOrderAs(t){return this.query.aggregate("var_samp","displayOrder",t),this}samplePopulationVarianceDisplayOrder(){return this.samplePopulationVarianceDisplayOrderAs("samplePopulationVarianceOfDisplayOrder")}samplePopulationVarianceDisplayOrderAs(t){return this.query.aggregate("var_pop","displayOrder",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByCode(){return this.query.groupBy("code"),this}groupByCodeAs(t){return this.query.groupBy("code",t),this}groupByColor(){return this.query.groupBy("color"),this}groupByColorAs(t){return this.query.groupBy("color",t),this}groupByDisplayOrder(){return this.query.groupBy("displayOrder"),this}groupByDisplayOrderAs(t){return this.query.groupBy("displayOrder",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof P?n:P.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof P?a:P.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof P?n:P.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Rt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return P.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class vt{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("Customer"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Customer"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Qt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","platform","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectCustomerOrderListWith(t){return this.query.relationQuery("customerOrderList",t.toQuery(),"id","customer",!0,{kind:"relation-select",method:"selectCustomerOrderListWith",relation:"customerOrderList"}),this}haveCustomerOrders(){return this.withCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}haveNoCustomerOrders(){return this.withoutCustomerOrderListMatching({entityName:"CustomerOrder",toQuery:()=>new O("CustomerOrder")})}withCustomerOrderListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customer"}}}),this}withoutCustomerOrderListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customer"}}}),this}countCustomerOrders(){return this.countCustomerOrdersAs("countCustomerOrders")}countCustomerOrdersAs(t){const e=new O("CustomerOrder").filter({version:{$gte:1}});return this.countCustomerOrdersWith(t,{entityName:"CustomerOrder",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countCustomerOrdersAs",relation:"customerOrderList",alias:t},this}countCustomerOrdersWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"relation-count",method:"countCustomerOrdersWith",relation:"customerOrderList",alias:t}),this}minTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.minTotalAmountOfCustomerOrdersAs("minOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}minTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"minTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}maxTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.maxTotalAmountOfCustomerOrdersAs("maxOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}maxTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"maxTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sumTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sumTotalAmountOfCustomerOrdersAs("sumOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sumTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sumTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}avgTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.avgTotalAmountOfCustomerOrdersAs("avgOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}avgTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"avgTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}standardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.standardDeviationTotalAmountOfCustomerOrdersAs("standardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}standardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"standardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs("squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}sampleVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.sampleVarianceTotalAmountOfCustomerOrdersAs("sampleVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}sampleVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"sampleVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}samplePopulationVarianceTotalAmountOfCustomerOrders(){const t=new O("CustomerOrder").filter({version:{$gte:1}});return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs("samplePopulationVarianceOfTotalAmountOfCustomerOrders",{entityName:"CustomerOrder",toQuery:()=>t})}samplePopulationVarianceTotalAmountOfCustomerOrdersAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","totalAmount",t),this.query.relationAggregate("customerOrderList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceTotalAmountOfCustomerOrdersAs",relation:"customerOrderList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByPlatformAs(t,e,r=!0){return this.query.facetBy(t,"platform",e,r,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof T?n:T.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof T?a:T.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof T?n:T.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Qt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return T.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class _t{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("CustomerOrder"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"CustomerOrder"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Bt(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customer","status","orderNumber","orderDate","totalAmount","version"]),this}selectId(){return this.query.select(["id"]),this}selectOrderNumber(){return this.query.select(["orderNumber"]),this}selectOrderDate(){return this.query.select(["orderDate"]),this}selectTotalAmount(){return this.query.select(["totalAmount"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerWith(t){return this.query.select(["customer"]),this.query.relationQuery("customer",t.toQuery(),"customer","id",!1,{kind:"relation-select",method:"selectCustomerWith",relation:"customer"}),this}selectStatusWith(t){return this.query.select(["status"]),this.query.relationQuery("status",t.toQuery(),"status","id",!1,{kind:"relation-select",method:"selectStatusWith",relation:"status"}),this}withCustomerMatching(t){return this.filters.push({customer:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerMatching(t){return this.filters.push({customer:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withStatusMatching(t){return this.filters.push({status:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutStatusMatching(t){return this.filters.push({status:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}selectOrderItemListWith(t){return this.query.relationQuery("orderItemList",t.toQuery(),"id","customerOrder",!0,{kind:"relation-select",method:"selectOrderItemListWith",relation:"orderItemList"}),this}haveOrderItems(){return this.withOrderItemListMatching({entityName:"OrderItem",toQuery:()=>new O("OrderItem")})}haveNoOrderItems(){return this.withoutOrderItemListMatching({entityName:"OrderItem",toQuery:()=>new O("OrderItem")})}withOrderItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}withoutOrderItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"customerOrder"}}}),this}countOrderItems(){return this.countOrderItemsAs("countOrderItems")}countOrderItemsAs(t){const e=new O("OrderItem").filter({version:{$gte:1}});return this.countOrderItemsWith(t,{entityName:"OrderItem",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countOrderItemsAs",relation:"orderItemList",alias:t},this}countOrderItemsWith(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("Count","id",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"relation-count",method:"countOrderItemsWith",relation:"orderItemList",alias:t}),this}minQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.minQuantityOfOrderItemsAs("minOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}minQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.maxQuantityOfOrderItemsAs("maxOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}maxQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sumQuantityOfOrderItemsAs("sumOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sumQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.avgQuantityOfOrderItemsAs("avgOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}avgQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.standardDeviationQuantityOfOrderItemsAs("standardDeviationOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}standardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceQuantityOfOrderItemsAs("sampleVarianceOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sampleVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceQuantityOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceQuantityOfOrderItemsAs("samplePopulationVarianceOfQuantityOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}samplePopulationVarianceQuantityOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","quantity",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceQuantityOfOrderItemsAs",relation:"orderItemList",alias:t}),this}minUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.minUnitPriceOfOrderItemsAs("minOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}minUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("min","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"minUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}maxUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.maxUnitPriceOfOrderItemsAs("maxOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}maxUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("max","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"maxUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sumUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sumUnitPriceOfOrderItemsAs("sumOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sumUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("sum","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sumUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}avgUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.avgUnitPriceOfOrderItemsAs("avgOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}avgUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("avg","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"avgUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}standardDeviationUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.standardDeviationUnitPriceOfOrderItemsAs("standardDeviationOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}standardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"standardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs("squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("stddev_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}sampleVarianceUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.sampleVarianceUnitPriceOfOrderItemsAs("sampleVarianceOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}sampleVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_samp","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"sampleVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}samplePopulationVarianceUnitPriceOfOrderItems(){const t=new O("OrderItem").filter({version:{$gte:1}});return this.samplePopulationVarianceUnitPriceOfOrderItemsAs("samplePopulationVarianceOfUnitPriceOfOrderItems",{entityName:"OrderItem",toQuery:()=>t})}samplePopulationVarianceUnitPriceOfOrderItemsAs(t,e){const r=e.toQuery().clone();return r.aggregateItems=[],r.aggregate("var_pop","unitPrice",t),this.query.relationAggregate("orderItemList",t,r,!0,{kind:"aggregate",method:"samplePopulationVarianceUnitPriceOfOrderItemsAs",relation:"orderItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomer(t){return this.filters.push({customer:{$eq:t}}),this}filterByCustomerIn(...t){return this.filters.push({customer:{$in:t}}),this}withCustomerIsKnown(){return this.filters.push({customer:{$isNull:!1}}),this}withCustomerIsUnknown(){return this.filters.push({customer:{$isNull:!0}}),this}filterByStatus(t){return this.filters.push({status:{$eq:t}}),this}filterByStatusIn(...t){return this.filters.push({status:{$in:t}}),this}withStatusIsKnown(){return this.filters.push({status:{$isNull:!1}}),this}withStatusIsUnknown(){return this.filters.push({status:{$isNull:!0}}),this}withStatusIsNew(){return this.filters.push({status:{$eq:"1001"}}),this}withStatusIsPaid(){return this.filters.push({status:{$eq:"1002"}}),this}withStatusIsCancelled(){return this.filters.push({status:{$eq:"1003"}}),this}withOrderNumberContaining(t){return this.filters.push({orderNumber:{$contains:t}}),this}withOrderNumberIs(t){return this.filters.push({orderNumber:{$eq:t}}),this}withOrderNumberIsNot(t){return this.filters.push({orderNumber:{$ne:t}}),this}withOrderNumberIn(...t){return this.filters.push({orderNumber:{$in:t}}),this}withOrderNumberNotIn(...t){return this.filters.push({orderNumber:{$notIn:t}}),this}withOrderNumberGreaterThan(t){return this.filters.push({orderNumber:{$gt:t}}),this}withOrderNumberGreaterThanOrEqualTo(t){return this.filters.push({orderNumber:{$gte:t}}),this}withOrderNumberLessThan(t){return this.filters.push({orderNumber:{$lt:t}}),this}withOrderNumberLessThanOrEqualTo(t){return this.filters.push({orderNumber:{$lte:t}}),this}withOrderNumberBetween(t,e){return this.filters.push({orderNumber:{$between:[t,e]}}),this}withOrderNumberIsKnown(){return this.filters.push({orderNumber:{$isNull:!1}}),this}withOrderNumberIsUnknown(){return this.filters.push({orderNumber:{$isNull:!0}}),this}withOrderNumberNotContaining(t){return this.filters.push({orderNumber:{$notContains:t}}),this}withOrderNumberStartingWith(t){return this.filters.push({orderNumber:{$startsWith:t}}),this}withOrderNumberNotStartingWith(t){return this.filters.push({orderNumber:{$notStartsWith:t}}),this}withOrderNumberEndingWith(t){return this.filters.push({orderNumber:{$endsWith:t}}),this}withOrderNumberNotEndingWith(t){return this.filters.push({orderNumber:{$notEndsWith:t}}),this}withOrderNumberSoundingLike(t){return this.filters.push({orderNumber:{$soundLike:t}}),this}withOrderDateIs(t){return this.filters.push({orderDate:{$eq:t}}),this}withOrderDateIsNot(t){return this.filters.push({orderDate:{$ne:t}}),this}withOrderDateIn(...t){return this.filters.push({orderDate:{$in:t}}),this}withOrderDateNotIn(...t){return this.filters.push({orderDate:{$notIn:t}}),this}withOrderDateGreaterThan(t){return this.filters.push({orderDate:{$gt:t}}),this}withOrderDateGreaterThanOrEqualTo(t){return this.filters.push({orderDate:{$gte:t}}),this}withOrderDateLessThan(t){return this.filters.push({orderDate:{$lt:t}}),this}withOrderDateLessThanOrEqualTo(t){return this.filters.push({orderDate:{$lte:t}}),this}withOrderDateBetween(t,e){return this.filters.push({orderDate:{$between:[t,e]}}),this}withOrderDateIsKnown(){return this.filters.push({orderDate:{$isNull:!1}}),this}withOrderDateIsUnknown(){return this.filters.push({orderDate:{$isNull:!0}}),this}withTotalAmountIs(t){return this.filters.push({totalAmount:{$eq:t}}),this}withTotalAmountIsNot(t){return this.filters.push({totalAmount:{$ne:t}}),this}withTotalAmountIn(...t){return this.filters.push({totalAmount:{$in:t}}),this}withTotalAmountNotIn(...t){return this.filters.push({totalAmount:{$notIn:t}}),this}withTotalAmountGreaterThan(t){return this.filters.push({totalAmount:{$gt:t}}),this}withTotalAmountGreaterThanOrEqualTo(t){return this.filters.push({totalAmount:{$gte:t}}),this}withTotalAmountLessThan(t){return this.filters.push({totalAmount:{$lt:t}}),this}withTotalAmountLessThanOrEqualTo(t){return this.filters.push({totalAmount:{$lte:t}}),this}withTotalAmountBetween(t,e){return this.filters.push({totalAmount:{$between:[t,e]}}),this}withTotalAmountIsKnown(){return this.filters.push({totalAmount:{$isNull:!1}}),this}withTotalAmountIsUnknown(){return this.filters.push({totalAmount:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByOrderNumberAscending(){return this.query.orderBy("orderNumber","asc"),this}orderByOrderNumberDescending(){return this.query.orderBy("orderNumber","desc"),this}orderByOrderDateAscending(){return this.query.orderBy("orderDate","asc"),this}orderByOrderDateDescending(){return this.query.orderBy("orderDate","desc"),this}orderByTotalAmountAscending(){return this.query.orderBy("totalAmount","asc"),this}orderByTotalAmountDescending(){return this.query.orderBy("totalAmount","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minTotalAmount(){return this.minTotalAmountAs("minOfTotalAmount")}minTotalAmountAs(t){return this.query.aggregate("min","totalAmount",t),this}maxTotalAmount(){return this.maxTotalAmountAs("maxOfTotalAmount")}maxTotalAmountAs(t){return this.query.aggregate("max","totalAmount",t),this}sumTotalAmount(){return this.sumTotalAmountAs("sumOfTotalAmount")}sumTotalAmountAs(t){return this.query.aggregate("sum","totalAmount",t),this}avgTotalAmount(){return this.avgTotalAmountAs("avgOfTotalAmount")}avgTotalAmountAs(t){return this.query.aggregate("avg","totalAmount",t),this}standardDeviationTotalAmount(){return this.standardDeviationTotalAmountAs("standardDeviationOfTotalAmount")}standardDeviationTotalAmountAs(t){return this.query.aggregate("stddev","totalAmount",t),this}squareRootOfPopulationStandardDeviationTotalAmount(){return this.squareRootOfPopulationStandardDeviationTotalAmountAs("squareRootOfPopulationStandardDeviationOfTotalAmount")}squareRootOfPopulationStandardDeviationTotalAmountAs(t){return this.query.aggregate("stddev_pop","totalAmount",t),this}sampleVarianceTotalAmount(){return this.sampleVarianceTotalAmountAs("sampleVarianceOfTotalAmount")}sampleVarianceTotalAmountAs(t){return this.query.aggregate("var_samp","totalAmount",t),this}samplePopulationVarianceTotalAmount(){return this.samplePopulationVarianceTotalAmountAs("samplePopulationVarianceOfTotalAmount")}samplePopulationVarianceTotalAmountAs(t){return this.query.aggregate("var_pop","totalAmount",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByCustomer(){return this.query.groupBy("customer"),this}groupByCustomerAs(t){return this.query.groupBy("customer",t),this}groupByStatus(){return this.query.groupBy("status"),this}groupByStatusAs(t){return this.query.groupBy("status",t),this}groupByOrderNumber(){return this.query.groupBy("orderNumber"),this}groupByOrderNumberAs(t){return this.query.groupBy("orderNumber",t),this}groupByOrderDate(){return this.query.groupBy("orderDate"),this}groupByOrderDateAs(t){return this.query.groupBy("orderDate",t),this}groupByTotalAmount(){return this.query.groupBy("totalAmount"),this}groupByTotalAmountAs(t){return this.query.groupBy("totalAmount",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByCustomerAs(t,e,r=!0){return this.query.facetBy(t,"customer",e,r,{kind:"facet",method:"facetByCustomerAs",relation:"customer",alias:t}),this}facetByStatusAs(t,e,r=!0){return this.query.facetBy(t,"status",e,r,{kind:"facet",method:"facetByStatusAs",relation:"status",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof b?n:b.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof b?a:b.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof b?n:b.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Bt{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return b.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class It{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new O("OrderItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"OrderItem"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const r=this.query.clone();this.filters.length>0&&r.filter({$and:this.filters});const i=et(r,t,st,e);return this.query=i.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...i.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new Ft(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,r)=>this.executeForStreamInternal(e,r),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,r){return this.query.optimizePaginationWithIdSetConfig(t,e,r),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","customerOrder","productName","quantity","unitPrice","version"]),this}selectId(){return this.query.select(["id"]),this}selectProductName(){return this.query.select(["productName"]),this}selectQuantity(){return this.query.select(["quantity"]),this}selectUnitPrice(){return this.query.select(["unitPrice"]),this}selectVersion(){return this.query.select(["version"]),this}selectCustomerOrderWith(t){return this.query.select(["customerOrder"]),this.query.relationQuery("customerOrder",t.toQuery(),"customerOrder","id",!1,{kind:"relation-select",method:"selectCustomerOrderWith",relation:"customerOrder"}),this}withCustomerOrderMatching(t){return this.filters.push({customerOrder:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutCustomerOrderMatching(t){return this.filters.push({customerOrder:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}filterByCustomerOrder(t){return this.filters.push({customerOrder:{$eq:t}}),this}filterByCustomerOrderIn(...t){return this.filters.push({customerOrder:{$in:t}}),this}withCustomerOrderIsKnown(){return this.filters.push({customerOrder:{$isNull:!1}}),this}withCustomerOrderIsUnknown(){return this.filters.push({customerOrder:{$isNull:!0}}),this}withProductNameContaining(t){return this.filters.push({productName:{$contains:t}}),this}withProductNameIs(t){return this.filters.push({productName:{$eq:t}}),this}withProductNameIsNot(t){return this.filters.push({productName:{$ne:t}}),this}withProductNameIn(...t){return this.filters.push({productName:{$in:t}}),this}withProductNameNotIn(...t){return this.filters.push({productName:{$notIn:t}}),this}withProductNameGreaterThan(t){return this.filters.push({productName:{$gt:t}}),this}withProductNameGreaterThanOrEqualTo(t){return this.filters.push({productName:{$gte:t}}),this}withProductNameLessThan(t){return this.filters.push({productName:{$lt:t}}),this}withProductNameLessThanOrEqualTo(t){return this.filters.push({productName:{$lte:t}}),this}withProductNameBetween(t,e){return this.filters.push({productName:{$between:[t,e]}}),this}withProductNameIsKnown(){return this.filters.push({productName:{$isNull:!1}}),this}withProductNameIsUnknown(){return this.filters.push({productName:{$isNull:!0}}),this}withProductNameNotContaining(t){return this.filters.push({productName:{$notContains:t}}),this}withProductNameStartingWith(t){return this.filters.push({productName:{$startsWith:t}}),this}withProductNameNotStartingWith(t){return this.filters.push({productName:{$notStartsWith:t}}),this}withProductNameEndingWith(t){return this.filters.push({productName:{$endsWith:t}}),this}withProductNameNotEndingWith(t){return this.filters.push({productName:{$notEndsWith:t}}),this}withProductNameSoundingLike(t){return this.filters.push({productName:{$soundLike:t}}),this}withQuantityIs(t){return this.filters.push({quantity:{$eq:t}}),this}withQuantityIsNot(t){return this.filters.push({quantity:{$ne:t}}),this}withQuantityIn(...t){return this.filters.push({quantity:{$in:t}}),this}withQuantityNotIn(...t){return this.filters.push({quantity:{$notIn:t}}),this}withQuantityGreaterThan(t){return this.filters.push({quantity:{$gt:t}}),this}withQuantityGreaterThanOrEqualTo(t){return this.filters.push({quantity:{$gte:t}}),this}withQuantityLessThan(t){return this.filters.push({quantity:{$lt:t}}),this}withQuantityLessThanOrEqualTo(t){return this.filters.push({quantity:{$lte:t}}),this}withQuantityBetween(t,e){return this.filters.push({quantity:{$between:[t,e]}}),this}withQuantityIsKnown(){return this.filters.push({quantity:{$isNull:!1}}),this}withQuantityIsUnknown(){return this.filters.push({quantity:{$isNull:!0}}),this}withUnitPriceIs(t){return this.filters.push({unitPrice:{$eq:t}}),this}withUnitPriceIsNot(t){return this.filters.push({unitPrice:{$ne:t}}),this}withUnitPriceIn(...t){return this.filters.push({unitPrice:{$in:t}}),this}withUnitPriceNotIn(...t){return this.filters.push({unitPrice:{$notIn:t}}),this}withUnitPriceGreaterThan(t){return this.filters.push({unitPrice:{$gt:t}}),this}withUnitPriceGreaterThanOrEqualTo(t){return this.filters.push({unitPrice:{$gte:t}}),this}withUnitPriceLessThan(t){return this.filters.push({unitPrice:{$lt:t}}),this}withUnitPriceLessThanOrEqualTo(t){return this.filters.push({unitPrice:{$lte:t}}),this}withUnitPriceBetween(t,e){return this.filters.push({unitPrice:{$between:[t,e]}}),this}withUnitPriceIsKnown(){return this.filters.push({unitPrice:{$isNull:!1}}),this}withUnitPriceIsUnknown(){return this.filters.push({unitPrice:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByProductNameAscending(){return this.query.orderBy("productName","asc"),this}orderByProductNameDescending(){return this.query.orderBy("productName","desc"),this}orderByQuantityAscending(){return this.query.orderBy("quantity","asc"),this}orderByQuantityDescending(){return this.query.orderBy("quantity","desc"),this}orderByUnitPriceAscending(){return this.query.orderBy("unitPrice","asc"),this}orderByUnitPriceDescending(){return this.query.orderBy("unitPrice","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}minQuantity(){return this.minQuantityAs("minOfQuantity")}minQuantityAs(t){return this.query.aggregate("min","quantity",t),this}maxQuantity(){return this.maxQuantityAs("maxOfQuantity")}maxQuantityAs(t){return this.query.aggregate("max","quantity",t),this}sumQuantity(){return this.sumQuantityAs("sumOfQuantity")}sumQuantityAs(t){return this.query.aggregate("sum","quantity",t),this}avgQuantity(){return this.avgQuantityAs("avgOfQuantity")}avgQuantityAs(t){return this.query.aggregate("avg","quantity",t),this}standardDeviationQuantity(){return this.standardDeviationQuantityAs("standardDeviationOfQuantity")}standardDeviationQuantityAs(t){return this.query.aggregate("stddev","quantity",t),this}squareRootOfPopulationStandardDeviationQuantity(){return this.squareRootOfPopulationStandardDeviationQuantityAs("squareRootOfPopulationStandardDeviationOfQuantity")}squareRootOfPopulationStandardDeviationQuantityAs(t){return this.query.aggregate("stddev_pop","quantity",t),this}sampleVarianceQuantity(){return this.sampleVarianceQuantityAs("sampleVarianceOfQuantity")}sampleVarianceQuantityAs(t){return this.query.aggregate("var_samp","quantity",t),this}samplePopulationVarianceQuantity(){return this.samplePopulationVarianceQuantityAs("samplePopulationVarianceOfQuantity")}samplePopulationVarianceQuantityAs(t){return this.query.aggregate("var_pop","quantity",t),this}minUnitPrice(){return this.minUnitPriceAs("minOfUnitPrice")}minUnitPriceAs(t){return this.query.aggregate("min","unitPrice",t),this}maxUnitPrice(){return this.maxUnitPriceAs("maxOfUnitPrice")}maxUnitPriceAs(t){return this.query.aggregate("max","unitPrice",t),this}sumUnitPrice(){return this.sumUnitPriceAs("sumOfUnitPrice")}sumUnitPriceAs(t){return this.query.aggregate("sum","unitPrice",t),this}avgUnitPrice(){return this.avgUnitPriceAs("avgOfUnitPrice")}avgUnitPriceAs(t){return this.query.aggregate("avg","unitPrice",t),this}standardDeviationUnitPrice(){return this.standardDeviationUnitPriceAs("standardDeviationOfUnitPrice")}standardDeviationUnitPriceAs(t){return this.query.aggregate("stddev","unitPrice",t),this}squareRootOfPopulationStandardDeviationUnitPrice(){return this.squareRootOfPopulationStandardDeviationUnitPriceAs("squareRootOfPopulationStandardDeviationOfUnitPrice")}squareRootOfPopulationStandardDeviationUnitPriceAs(t){return this.query.aggregate("stddev_pop","unitPrice",t),this}sampleVarianceUnitPrice(){return this.sampleVarianceUnitPriceAs("sampleVarianceOfUnitPrice")}sampleVarianceUnitPriceAs(t){return this.query.aggregate("var_samp","unitPrice",t),this}samplePopulationVarianceUnitPrice(){return this.samplePopulationVarianceUnitPriceAs("samplePopulationVarianceOfUnitPrice")}samplePopulationVarianceUnitPriceAs(t){return this.query.aggregate("var_pop","unitPrice",t),this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByCustomerOrder(){return this.query.groupBy("customerOrder"),this}groupByCustomerOrderAs(t){return this.query.groupBy("customerOrder",t),this}groupByProductName(){return this.query.groupBy("productName"),this}groupByProductNameAs(t){return this.query.groupBy("productName",t),this}groupByQuantity(){return this.query.groupBy("quantity"),this}groupByQuantityAs(t){return this.query.groupBy("quantity",t),this}groupByUnitPrice(){return this.query.groupBy("unitPrice"),this}groupByUnitPriceAs(t){return this.query.groupBy("unitPrice",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByCustomerOrderAs(t,e,r=!0){return this.query.facetBy(t,"customerOrder",e,r,{kind:"facet",method:"facetByCustomerOrderAs",relation:"customerOrder",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=await e.executeQuery(t.prepareQuery(this.query)),i=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,s=i?[]:r.map(n=>n instanceof Q?n:Q.fromRecord(n,new k)),o=new L(s);return i&&r[0]&&Object.assign(o.aggregations,r[0]),this.query.facets.length>0&&(o.facets=await M(e,n=>t.prepareQuery(n),this.query,this.query.facets)),o}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new L(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),r=t.prepareQuery(this.query),i=r.localIdSetPaginationOptions()!==void 0,s={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},o=i?void 0:await e.executeCount(r,this._pageCountAlias,s),n=r.clone();n.aggregateItems=n.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const f=await e.executeQuery(n),l=i&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:o??await e.executeCount(r,this._pageCountAlias,s),c=new L(f.map(a=>a instanceof Q?a:Q.fromRecord(a,new k)));return c.totalCount=l,this._pageCountAlias!==void 0&&(c.aggregations[this._pageCountAlias]=l),this.query.facets.length>0&&(c.facets=await M(e,a=>t.prepareQuery(a),r,r.facets)),c}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const r=t.requireResource("dataService"),i=t.prepareQuery(this.query),s=r.executeForStream(i,e);return(async function*(){for await(const o of s)for(const n of o)yield n instanceof Q?n:Q.fromRecord(n,new k)})()}ensureIntent(){new rt(this._comment,this._purpose)}}class Ft{constructor(t,e,r,i,s,o){this.execute=t,this.executeRows=e,this.stream=r,this.limitOne=i,this.addComment=s,this.ensureIntent=o}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof H))throw new TypeError("UserContext is required for creation");return Q.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class F{static platforms(){return new qt(!1)}static platformsWithMinimalFields(){return new qt(!0)}static orderStatuses(){return new wt(!1)}static orderStatusesWithMinimalFields(){return new wt(!0)}static customers(){return new vt(!1)}static customersWithMinimalFields(){return new vt(!0)}static customerOrders(){return new _t(!1)}static customerOrdersWithMinimalFields(){return new _t(!0)}static orderItems(){return new It(!1)}static orderItemsWithMinimalFields(){return new It(!0)}}class u{constructor(t,e=!0,r,i){this.value=t,this.present=e,this.notLoaded=r,this.invalidValue=i}value;present;notLoaded;invalidValue;static missing(){return new u(void 0,!1)}static notLoaded(t){return new u(void 0,!1,t)}static invalid(t){return new u(void 0,!1,void 0,t)}eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");if(this.invalidValue)throw this.invalidValue;return this.present?this.value:void 0}isPresent(){if(this.notLoaded)throw this.notLoaded.terminal("isPresent()");if(this.invalidValue)throw this.invalidValue;return this.present}orElse(t){if(this.notLoaded)throw this.notLoaded.terminal("orElse()");if(this.invalidValue)throw this.invalidValue;const e=this.value;return this.present&&e!=null?e:t}}class K{constructor(t,e="Platform(null)",r=D.root("E.platform()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}name(){const t=this.path.member("name","name");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("name")?new u(this.value.name):u.notLoaded(new v(t.markMissing(),"name")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}orderStatusList(){const t=this.path.member("order_status_list","orderStatusList");return this.notLoaded?new j([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderStatusList")?new j(this.value.orderStatusList(),this.root,t):new j([],this.root,t,!1,new v(t.markMissing(),"order_status_list")):j.missing(this.root,t)}customerList(){const t=this.path.member("customer_list","customerList");return this.notLoaded?new z([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("customerList")?new z(this.value.customerList(),this.root,t):new z([],this.root,t,!1,new v(t.markMissing(),"customer_list")):z.missing(this.root,t)}}class U{constructor(t,e="OrderStatus(null)",r=D.root("E.orderStatus()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}name(){const t=this.path.member("name","name");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("name")?new u(this.value.name):u.notLoaded(new v(t.markMissing(),"name")):u.missing()}code(){const t=this.path.member("code","code");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("code")?new u(this.value.code):u.notLoaded(new v(t.markMissing(),"code")):u.missing()}color(){const t=this.path.member("color","color");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("color")?new u(this.value.color):u.notLoaded(new v(t.markMissing(),"color")):u.missing()}displayOrder(){const t=this.path.member("display_order","displayOrder");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("displayOrder"))return u.notLoaded(new v(t.markMissing(),"display_order"));const e=X(this.value.displayOrder,"OrderStatus","display_order");return e?u.invalid(e):new u(this.value.displayOrder)}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}platformId(){const t=this.path.member("platform","platformId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("platform"))return u.notLoaded(new v(t.markMissing(),"platform"));const e=this.value.platform;return new u(e instanceof C?e.id:e)}platform(){const t=this.path.member("platform","platform");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const e=this.value.platform;if(e!=null&&!(e instanceof C))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const r=e instanceof C?e:void 0;return new K(r,this.root,t)}customerOrderList(){const t=this.path.member("customer_order_list","customerOrderList");return this.notLoaded?new x([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("customerOrderList")?new x(this.value.customerOrderList(),this.root,t):new x([],this.root,t,!1,new v(t.markMissing(),"customer_order_list")):x.missing(this.root,t)}}class W{constructor(t,e="Customer(null)",r=D.root("E.customer()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}name(){const t=this.path.member("name","name");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("name")?new u(this.value.name):u.notLoaded(new v(t.markMissing(),"name")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}platformId(){const t=this.path.member("platform","platformId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("platform"))return u.notLoaded(new v(t.markMissing(),"platform"));const e=this.value.platform;return new u(e instanceof C?e.id:e)}platform(){const t=this.path.member("platform","platform");if(this.notLoaded)return new K(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new K(void 0,this.root,t);if(!this.value.isLoaded("platform"))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const e=this.value.platform;if(e!=null&&!(e instanceof C))return new K(void 0,this.root,t,new v(t.markMissing(),"platform"));const r=e instanceof C?e:void 0;return new K(r,this.root,t)}customerOrderList(){const t=this.path.member("customer_order_list","customerOrderList");return this.notLoaded?new x([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("customerOrderList")?new x(this.value.customerOrderList(),this.root,t):new x([],this.root,t,!1,new v(t.markMissing(),"customer_order_list")):x.missing(this.root,t)}}class G{constructor(t,e="CustomerOrder(null)",r=D.root("E.customerOrder()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}orderNumber(){const t=this.path.member("order_number","orderNumber");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderNumber")?new u(this.value.orderNumber):u.notLoaded(new v(t.markMissing(),"order_number")):u.missing()}orderDate(){const t=this.path.member("order_date","orderDate");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderDate")?new u(this.value.orderDate):u.notLoaded(new v(t.markMissing(),"order_date")):u.missing()}totalAmount(){const t=this.path.member("total_amount","totalAmount");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("totalAmount")?new u(this.value.totalAmount):u.notLoaded(new v(t.markMissing(),"total_amount")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}customerId(){const t=this.path.member("customer","customerId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("customer"))return u.notLoaded(new v(t.markMissing(),"customer"));const e=this.value.customer;return new u(e instanceof T?e.id:e)}statusId(){const t=this.path.member("status","statusId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("status"))return u.notLoaded(new v(t.markMissing(),"status"));const e=this.value.status;return new u(e instanceof P?e.id:e)}customer(){const t=this.path.member("customer","customer");if(this.notLoaded)return new W(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new W(void 0,this.root,t);if(!this.value.isLoaded("customer"))return new W(void 0,this.root,t,new v(t.markMissing(),"customer"));const e=this.value.customer;if(e!=null&&!(e instanceof T))return new W(void 0,this.root,t,new v(t.markMissing(),"customer"));const r=e instanceof T?e:void 0;return new W(r,this.root,t)}status(){const t=this.path.member("status","status");if(this.notLoaded)return new U(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new U(void 0,this.root,t);if(!this.value.isLoaded("status"))return new U(void 0,this.root,t,new v(t.markMissing(),"status"));const e=this.value.status;if(e!=null&&!(e instanceof P))return new U(void 0,this.root,t,new v(t.markMissing(),"status"));const r=e instanceof P?e:void 0;return new U(r,this.root,t)}orderItemList(){const t=this.path.member("order_item_list","orderItemList");return this.notLoaded?new J([],this.root,t,!1,this.notLoaded.withPath(t)):this.value?this.value.isLoaded("orderItemList")?new J(this.value.orderItemList(),this.root,t):new J([],this.root,t,!1,new v(t.markMissing(),"order_item_list")):J.missing(this.root,t)}}class lt{constructor(t,e="OrderItem(null)",r=D.root("E.orderItem()","camelCase"),i){this.value=t,this.root=e,this.path=r,this.notLoaded=i}value;root;path;notLoaded;eval(){if(this.notLoaded)throw this.notLoaded.terminal("eval()");return this.value}id(){const t=this.path.member("id","id");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("id")?new u(this.value.id):u.notLoaded(new v(t.markMissing(),"id")):u.missing()}productName(){const t=this.path.member("product_name","productName");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("productName")?new u(this.value.productName):u.notLoaded(new v(t.markMissing(),"product_name")):u.missing()}quantity(){const t=this.path.member("quantity","quantity");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("quantity"))return u.notLoaded(new v(t.markMissing(),"quantity"));const e=X(this.value.quantity,"OrderItem","quantity");return e?u.invalid(e):new u(this.value.quantity)}unitPrice(){const t=this.path.member("unit_price","unitPrice");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("unitPrice")?new u(this.value.unitPrice):u.notLoaded(new v(t.markMissing(),"unit_price")):u.missing()}version(){const t=this.path.member("version","version");return this.notLoaded?u.notLoaded(this.notLoaded.withPath(t)):this.value?this.value.isLoaded("version")?new u(this.value.version):u.notLoaded(new v(t.markMissing(),"version")):u.missing()}customerOrderId(){const t=this.path.member("customer_order","customerOrderId");if(this.notLoaded)return u.notLoaded(this.notLoaded.withPath(t));if(!this.value)return u.missing();if(!this.value.isLoaded("customerOrder"))return u.notLoaded(new v(t.markMissing(),"customer_order"));const e=this.value.customerOrder;return new u(e instanceof b?e.id:e)}customerOrder(){const t=this.path.member("customer_order","customerOrder");if(this.notLoaded)return new G(void 0,this.root,t,this.notLoaded.withPath(t));if(!this.value)return new G(void 0,this.root,t);if(!this.value.isLoaded("customerOrder"))return new G(void 0,this.root,t,new v(t.markMissing(),"customer_order"));const e=this.value.customerOrder;if(e!=null&&!(e instanceof b))return new G(void 0,this.root,t,new v(t.markMissing(),"customer_order"));const r=e instanceof b?e:void 0;return new G(r,this.root,t)}}class j{constructor(t,e="OrderStatus(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new j([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new U(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new U(void 0,this.root,r):new U(this.items[t],this.root,r)}}class z{constructor(t,e="Customer(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new z([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new W(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new W(void 0,this.root,r):new W(this.items[t],this.root,r)}}class x{constructor(t,e="CustomerOrder(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new x([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new G(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new G(void 0,this.root,r):new G(this.items[t],this.root,r)}}class J{constructor(t,e="OrderItem(null)",r=D.root("E.entity()","camelCase"),i=!0,s){this.items=t,this.root=e,this.path=r,this.present=i,this.notLoaded=s}items;root;path;present;notLoaded;static missing(t,e=D.root("E.entity()","camelCase")){return new J([],t,e,!1)}size(){return this.notLoaded?u.notLoaded(this.notLoaded.withPath(this.path.operation("size()"))):this.present?new u(this.items.length):u.missing()}first(){return this.item(0,!0)}get(t){return this.item(t,!1)}item(t,e){const r=this.path.index(t,e);return this.notLoaded?new lt(void 0,this.root,r,this.notLoaded.withPath(r)):!this.present||t<0||t>=this.items.length?new lt(void 0,this.root,r):new lt(this.items[t],this.root,r)}}class ft{static platform(t){return new K(t,"Platform",D.root("E.platform()","camelCase"))}static orderStatus(t){return new U(t,"OrderStatus",D.root("E.orderStatus()","camelCase"))}static customer(t){return new W(t,"Customer",D.root("E.customer()","camelCase"))}static customerOrder(t){return new G(t,"CustomerOrder",D.root("E.customerOrder()","camelCase"))}static orderItem(t){return new lt(t,"OrderItem",D.root("E.orderItem()","camelCase"))}}const Lt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{orderStatusList:{targetEntity:"OrderStatus",localKey:"id",foreignKey:"platform",many:!0},customerList:{targetEntity:"Customer",localKey:"id",foreignKey:"platform",many:!0}}},OrderStatus:{table:"order_status_data",auditMaskFields:[],columns:{platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},code:{columnName:"code",modelName:"code",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},color:{columnName:"color",modelName:"color",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},displayOrder:{columnName:"display_order",modelName:"display_order",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1,integer32:!0},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"status",many:!0}}},Customer:{table:"customer_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1},customerOrderList:{targetEntity:"CustomerOrder",localKey:"id",foreignKey:"customer",many:!0}}},CustomerOrder:{table:"customer_order_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customer:{columnName:"customer",modelName:"customer",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},status:{columnName:"status",modelName:"status",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},orderNumber:{columnName:"order_number",modelName:"order_number",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},orderDate:{columnName:"order_date",modelName:"order_date",logPolicy:"plain",logicalType:"date",decode:"date",nullable:!1},totalAmount:{columnName:"total_amount",modelName:"total_amount",logPolicy:"plain",logicalType:"decimal",decode:"decimal",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customer:{targetEntity:"Customer",localKey:"customer",foreignKey:"id",many:!1},status:{targetEntity:"OrderStatus",localKey:"status",foreignKey:"id",many:!1},orderItemList:{targetEntity:"OrderItem",localKey:"id",foreignKey:"customerOrder",many:!0}}},OrderItem:{table:"order_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},customerOrder:{columnName:"customer_order",modelName:"customer_order",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},productName:{columnName:"product_name",modelName:"product_name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},quantity:{columnName:"quantity",modelName:"quantity",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1,integer32:!0},unitPrice:{columnName:"unit_price",modelName:"unit_price",logPolicy:"plain",logicalType:"decimal",decode:"decimal",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{customerOrder:{targetEntity:"CustomerOrder",localKey:"customerOrder",foreignKey:"id",many:!1}}}};async function Vt(h){let t=(await F.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];t||(t=C.teaqlBootstrapNew(h,"1"),t.updateName("Commerce Test Platform"),await t.auditAs("create generated Domain Root Platform").save(h)),h.withActiveRoot({entity:"Platform",id:t.id});let e=(await F.orderStatuses().withIdIs("1001").comment("what: locate generated constant OrderStatus(1001)").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];if(!e)e=P.teaqlBootstrapNew(h,"1001"),e.updatePlatform(t),e.updateName("New"),e.updateCode("NEW"),e.updateColor("#94A3B8"),e.updateDisplayOrder(1),await e.auditAs("create model constant OrderStatus(1001)").save(h);else{let s=!1;String(e.platform?.id??e.platform)!==String(t.id)&&(e.updatePlatform(t),s=!0),e.name!=="New"&&(e.updateName("New"),s=!0),e.code!=="NEW"&&(e.updateCode("NEW"),s=!0),e.color!=="#94A3B8"&&(e.updateColor("#94A3B8"),s=!0),e.displayOrder!==1&&(e.updateDisplayOrder(1),s=!0),s&&await e.auditAs("reconcile model constant OrderStatus(1001)").save(h)}let r=(await F.orderStatuses().withIdIs("1002").comment("what: locate generated constant OrderStatus(1002)").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];if(!r)r=P.teaqlBootstrapNew(h,"1002"),r.updatePlatform(t),r.updateName("Paid"),r.updateCode("PAID"),r.updateColor("#22C55E"),r.updateDisplayOrder(2),await r.auditAs("create model constant OrderStatus(1002)").save(h);else{let s=!1;String(r.platform?.id??r.platform)!==String(t.id)&&(r.updatePlatform(t),s=!0),r.name!=="Paid"&&(r.updateName("Paid"),s=!0),r.code!=="PAID"&&(r.updateCode("PAID"),s=!0),r.color!=="#22C55E"&&(r.updateColor("#22C55E"),s=!0),r.displayOrder!==2&&(r.updateDisplayOrder(2),s=!0),s&&await r.auditAs("reconcile model constant OrderStatus(1002)").save(h)}let i=(await F.orderStatuses().withIdIs("1003").comment("what: locate generated constant OrderStatus(1003)").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];if(!i)i=P.teaqlBootstrapNew(h,"1003"),i.updatePlatform(t),i.updateName("Cancelled"),i.updateCode("CANCELLED"),i.updateColor("#EF4444"),i.updateDisplayOrder(3),await i.auditAs("create model constant OrderStatus(1003)").save(h);else{let s=!1;String(i.platform?.id??i.platform)!==String(t.id)&&(i.updatePlatform(t),s=!0),i.name!=="Cancelled"&&(i.updateName("Cancelled"),s=!0),i.code!=="CANCELLED"&&(i.updateCode("CANCELLED"),s=!0),i.color!=="#EF4444"&&(i.updateColor("#EF4444"),s=!0),i.displayOrder!==3&&(i.updateDisplayOrder(3),s=!0),s&&await i.auditAs("reconcile model constant OrderStatus(1003)").save(h)}}const Kt=new Nt(Lt,{Platform:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:p.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:p.property("name"),inputValue:t.payload.name,systemValue:100})}},OrderStatus:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:p.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:p.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:p.property("name"),inputValue:t.payload.name,systemValue:100}),(t.action==="Create"&&t.payload.code===void 0||t.payload.code===null)&&e.push({ruleId:"required",location:p.property("code")}),t.payload.code!=null&&[...String(t.payload.code)].length>100&&e.push({ruleId:"max_length",location:p.property("code"),inputValue:t.payload.code,systemValue:100}),(t.action==="Create"&&t.payload.color===void 0||t.payload.color===null)&&e.push({ruleId:"required",location:p.property("color")}),t.payload.color!=null&&[...String(t.payload.color)].length>100&&e.push({ruleId:"max_length",location:p.property("color"),inputValue:t.payload.color,systemValue:100}),(t.action==="Create"&&t.payload.display_order===void 0||t.payload.display_order===null)&&e.push({ruleId:"required",location:p.property("display_order")})}},Customer:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:p.property("platform")}),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:p.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:p.property("name"),inputValue:t.payload.name,systemValue:100})}},CustomerOrder:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.customer===void 0||t.payload.customer===null)&&e.push({ruleId:"required",location:p.property("customer")}),(t.action==="Create"&&t.payload.status===void 0||t.payload.status===null)&&e.push({ruleId:"required",location:p.property("status")}),(t.action==="Create"&&t.payload.order_number===void 0||t.payload.order_number===null)&&e.push({ruleId:"required",location:p.property("order_number")}),t.payload.order_number!=null&&[...String(t.payload.order_number)].length>100&&e.push({ruleId:"max_length",location:p.property("order_number"),inputValue:t.payload.order_number,systemValue:100}),(t.action==="Create"&&t.payload.order_date===void 0||t.payload.order_date===null)&&e.push({ruleId:"required",location:p.property("order_date")}),(t.action==="Create"&&t.payload.total_amount===void 0||t.payload.total_amount===null)&&e.push({ruleId:"required",location:p.property("total_amount")})}},OrderItem:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.customer_order===void 0||t.payload.customer_order===null)&&e.push({ruleId:"required",location:p.property("customer_order")}),(t.action==="Create"&&t.payload.product_name===void 0||t.payload.product_name===null)&&e.push({ruleId:"required",location:p.property("product_name")}),t.payload.product_name!=null&&[...String(t.payload.product_name)].length>100&&e.push({ruleId:"max_length",location:p.property("product_name"),inputValue:t.payload.product_name,systemValue:100}),(t.action==="Create"&&t.payload.quantity===void 0||t.payload.quantity===null)&&e.push({ruleId:"required",location:p.property("quantity")}),(t.action==="Create"&&t.payload.unit_price===void 0||t.payload.unit_price===null)&&e.push({ruleId:"required",location:p.property("unit_price")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Commerce Test Platform"}},constants:[{entity:"OrderStatus",id:"1001",values:{platform:"1",name:"New",code:"NEW",color:"#94A3B8",displayOrder:1}},{entity:"OrderStatus",id:"1002",values:{platform:"1",name:"Paid",code:"PAID",color:"#22C55E",displayOrder:2}},{entity:"OrderStatus",id:"1003",values:{platform:"1",name:"Cancelled",code:"CANCELLED",color:"#EF4444",displayOrder:3}}],ensure:Vt}),Ot=document.querySelector("#status"),xt=document.querySelector("#result"),Mt=document.querySelector("#trace"),Ut=document.querySelector("#sql"),Wt=document.querySelector("#evidence-rows"),yt=document.querySelector("#persist"),At=document.querySelector("#logging"),gt=document.querySelector("#reset"),ct=document.querySelector("#query"),Pt=document.querySelector("#search"),Gt={filter:{orderNumber:{$contains:"KEEP"}}};let V;yt.checked=localStorage.getItem("teaql-browser-order-storage")==="opfs";async function jt(h){const t=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),e=await Et.open(t,{...Lt},{storage:h,databaseName:"teaql-browser-orders.sqlite3"});e.install(Kt),e.setDiagnosticSQLLogSink(void 0).setMutationLoggingEnabled(!1);const r=Object.freeze({policyId:"browser-order-seed",version:"1",fingerprint:"sha256:browser-order-seed-v1"}),i=new H().insertResource("dataService",e).withMutationPolicyRegistry(new $t(()=>({identity:r,review:(s,o)=>o.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new Tt(s=>({policy:s,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(i),await i.ensureSchema(),await i.ensureSchema(),{client:e,context:i,evidence:new Dt,diagnostics:[]}}async function Ct({context:h}){if((await F.customerOrdersWithMinimalFields().limit(1).comment("detect existing order demo").purpose("keep mutation seeding idempotent").executeForList(h)).length)return;const e=(await F.platforms().limit(2).comment("load bootstrap platform").purpose("prepare order demo").executeForList(h))[0],r=await F.customers().comment("initialize demo customer").purpose("prepare order demo").newEntity(h);r.updateName("North Star Retail").updatePlatform(e.id),await r.auditAs("seed browser order customer").save(h);for(let i=1;i<=4;i++){const s=await F.customerOrders().comment("initialize demo order").purpose("prepare order demo").newEntity(h);s.updateCustomer(r.id).updateOrderNumber(i<4?`KEEP-00${i}`:"DROP-004").updateOrderDate(`2026-10-0${i}`).updateTotalAmount(mt(String(i<4?i*100:900))),i===1?s.updateStatusToNew():s.updateStatusToPaid(),await s.auditAs("seed browser order").save(h);for(let o=1;o<=5;o++){const n=await F.orderItems().comment("initialize demo item").purpose("prepare item previews").newEntity(h);n.updateCustomerOrder(s.id).updateProductName(`Box ${o}`).updateQuantity(o).updateUnitPrice(mt("20")),await n.auditAs("seed browser order item").save(h)}}}async function pt(h){const t=JSON.parse(Pt.value),e=F.customerOrdersWithMinimalFields().filterByJson(t);h.evidence.enableAll(),h.diagnostics.length=0,h.client.setRuntimeTelemetrySink(h.evidence).setQueryLoggingEnabled(At.checked).setDiagnosticSQLLogSink({write:n=>h.diagnostics.push(n)});const r=await e.countAs("totalOrders").facetByStatusAs("statusCounts",F.orderStatusesWithMinimalFields().selectName().selectColor().countAs("orderCount").sumTotalAmountOfCustomerOrdersAs("orderTotalAmount",F.customerOrdersWithMinimalFields()).orderByDisplayOrderAscending().comment("load status facets")).selectOrderNumber().selectOrderDate().selectStatusWith(F.orderStatusesWithMinimalFields().selectName().selectColor().comment("load status")).selectOrderItemListWith(F.orderItemsWithMinimalFields().selectProductName().selectQuantity().orderByIdAscending().limit(3).comment("load item previews")).countOrderItemsAs("itemCount").orderByOrderDateDescending().orderByIdDescending().offset(1).limit(1).comment("load order list").purpose("render order list page").executeForList(h.context),i={data:r.data.map(n=>{const f=ft.customerOrder(n),l=f.orderItemList().size().eval();if(l==null)throw new Error("Selected item list unexpectedly has a null size");return{id:n.id,version:n.version,orderNumber:f.orderNumber().eval(),orderDate:f.orderDate().eval(),status:{name:f.status().name().eval(),color:f.status().color().eval()},items:Array.from({length:l},(c,a)=>({productName:f.orderItemList().get(a).productName().eval(),quantity:f.orderItemList().get(a).quantity().eval()})),itemCount:n.itemCount}}),metadata:{totalCount:r.totalCount,pageOffset:1,pageSize:1,aggregations:r.data.aggregations,searchWarnings:e.dynamicSearchWarnings},facets:{statusCounts:r.data.facets.statusCounts.map(n=>({id:n.id,name:ft.orderStatus(P.fromRecord(n)).name().eval(),color:ft.orderStatus(P.fromRecord(n)).color().eval(),orderCount:n.orderCount,orderTotalAmount:n.orderTotalAmount}))}};xt.textContent=JSON.stringify(i,null,2);const s=h.evidence.snapshot(),o=s.map(n=>{const f=n.traceChain??[],l=f.filter(w=>w.kind==="purpose"),c=l.length===1?`${l[0].detail}: ${f.filter(w=>w.kind==="comment").map(w=>w.detail).join(" → ")}`:"TraceChain unavailable",a=document.createElement("tr");for(const w of[`${n.elapsedMicros} µs`,n.tracePath.find(m=>m.kind==="request")?.name??"—",c,n.debugSQL]){const m=document.createElement("td");m.textContent=w,a.append(m)}return{row:a,businessTrace:c}});Wt.replaceChildren(...o.map(n=>n.row)),Mt.textContent=o.map(n=>n.businessTrace).join(` +`),Ut.textContent=JSON.stringify(s,null,2),Ot.textContent=`${h.client.storage.toUpperCase()} · ${r.totalCount} matches · ${s.length} SQL statements · ${h.diagnostics.length} diagnostics · policy installed · ready`}async function St(h){Ot.textContent=`Opening ${h.toUpperCase()} SQLite/WASM…`;const t=V;V=void 0,await t?.client.close();const e=await jt(h);V=e,await Ct(e),await pt(e)}function ot(h){Ot.textContent=h instanceof Error?`${h.name}: ${h.message}`:String(h)}ct.addEventListener("click",async()=>{if(V){ct.disabled=!0;try{await pt(V)}catch(h){ot(h)}finally{ct.disabled=!1}}});document.querySelector("#preset").addEventListener("click",()=>{Pt.value=JSON.stringify(Gt,null,2),ct.click()});At.addEventListener("change",()=>{V&&pt(V).catch(ot)});yt.addEventListener("change",()=>{const h=yt.checked?"opfs":"memory";localStorage.setItem("teaql-browser-order-storage",h),St(h).catch(ot)});gt.addEventListener("click",async()=>{if(V){gt.disabled=!0;try{await V.client.reset(V.context),await Ct(V),await pt(V)}catch(h){ot(h)}finally{gt.disabled=!1}}});St(yt.checked?"opfs":"memory").catch(ot); diff --git a/dist/assets/sqlite.worker-BcUEWFpc.js b/dist/assets/sqlite.worker-BcUEWFpc.js new file mode 100644 index 0000000000000000000000000000000000000000..dd1dc281680f44d338f6a68014ec7cd9338f5120 --- /dev/null +++ b/dist/assets/sqlite.worker-BcUEWFpc.js @@ -0,0 +1,3 @@ +(function(){"use strict";globalThis.sqlite3Worker1Promiser=function qe(ie=qe.defaultConfig){if(arguments.length===1&&typeof arguments[0]=="function"){const de=ie;ie=Object.assign(Object.create(null),qe.defaultConfig),ie.onready=de}else ie=Object.assign(Object.create(null),qe.defaultConfig,ie);const f=Object.create(null),he=function(){},ye=ie.onerror||he,ge=ie.debug||he,Se=ie.generateMessageId?void 0:Object.create(null),Be=ie.generateMessageId||function(de){return de.type+"#"+(Se[de.type]=(Se[de.type]||0)+1)},Qe=(...de)=>{throw new Error(de.join(" "))};ie.worker||(ie.worker=qe.defaultConfig.worker),typeof ie.worker=="function"&&(ie.worker=ie.worker());let De,We;return ie.worker.onmessage=function(de){de=de.data,ge("worker1.onmessage",de);let Le=f[de.messageId];if(!Le){if(de&&de.type==="sqlite3-api"&&de.result==="worker1-ready"){ie.onready&&ie.onready(We);return}if(Le=f[de.type],Le&&Le.onrow){Le.onrow(de);return}ie.onunhandled?ie.onunhandled(arguments[0]):ye("sqlite3Worker1Promiser() unhandled worker message:",de);return}switch(delete f[de.messageId],de.type){case"error":Le.reject(de);return;case"open":De||(De=de.dbId);break;case"close":de.dbId===De&&(De=void 0);break}try{Le.resolve(de)}catch(Ie){Le.reject(Ie)}},We=function(){let de;arguments.length===1?de=arguments[0]:arguments.length===2?(de=Object.create(null),de.type=arguments[0],de.args=arguments[1],de.dbId=de.args.dbId):Qe("Invalid arguments for sqlite3Worker1Promiser()-created factory."),!de.dbId&&de.type!=="open"&&(de.dbId=De),de.messageId=Be(de),de.departureTime=performance.now();const Le=Object.create(null);Le.message=de;let Ie;de.type==="exec"&&de.args&&(typeof de.args.callback=="function"?(Ie=de.messageId+":row",Le.onrow=de.args.callback,de.args.callback=Ie,f[Ie]=Le):typeof de.args.callback=="string"&&Qe("exec callback may not be a string when using the Promise interface."));let Ee=new Promise(function(Ce,je){Le.resolve=Ce,Le.reject=je,f[de.messageId]=Le,ge("Posting",de.type,"message to Worker dbId="+(De||"default")+":",de),ie.worker.postMessage(de)});return Ie&&(Ee=Ee.finally(()=>delete f[Ie])),Ee}},globalThis.sqlite3Worker1Promiser.defaultConfig={worker:function(){return new Worker(new URL("/assets/sqlite3-worker1-Ydf970DV.js",self.location.href),{type:"module"})},onerror:(...qe)=>console.error("sqlite3Worker1Promiser():",...qe)},globalThis.sqlite3Worker1Promiser.v2=(function qe(ie=qe.defaultConfig){let f;typeof ie=="function"?(f=ie,ie={}):typeof ie?.onready=="function"&&(f=ie.onready,delete ie.onready);const he=Object.create(null);ie=Object.assign(ie||Object.create(null),{onready:async function(ge){try{f&&await f(ge),he.resolve(ge)}catch(Se){he.reject(Se)}}});const ye=new Promise(function(ge,Se){he.resolve=ge,he.reject=Se});try{this.original(ie)}catch(ge){he.reject(ge)}return ye}).bind({original:sqlite3Worker1Promiser}),globalThis.sqlite3Worker1Promiser.v2.defaultConfig=globalThis.sqlite3Worker1Promiser.defaultConfig,sqlite3Worker1Promiser.v2,delete globalThis.sqlite3Worker1Promiser;async function At(qe={}){var ie,f=qe,he=!!globalThis.window,ye=!!globalThis.WorkerGlobalScope;globalThis.process?.versions?.node&&globalThis.process?.type;var ge="./this.program",Se=self.location.href,Be="";function Qe(e){return f.locateFile?f.locateFile(e,Be):Be+e}var De,We;if(he||ye){try{Be=new URL(".",Se).href}catch{}ye&&(We=e=>{var n=new XMLHttpRequest;return n.open("GET",e,!1),n.responseType="arraybuffer",n.send(null),new Uint8Array(n.response)}),De=async e=>{var n=await fetch(e,{credentials:"same-origin"});if(n.ok)return n.arrayBuffer();throw new Error(n.status+" : "+n.url)}}var de=console.log.bind(console),Le=console.error.bind(console),Ie,Ee=!1,Ce,je,et=!1;function Ct(){var e=nt.buffer;Je=new Int8Array(e),ht=new Int16Array(e),it=new Uint8Array(e),Oe=new Int32Array(e),Fe=new Uint32Array(e),Ve=new BigInt64Array(e),new BigUint64Array(e)}function _n(){if(f.wasmMemory)nt=f.wasmMemory;else{var e=f.INITIAL_MEMORY||8388608;nt=new WebAssembly.Memory({initial:e/65536,maximum:32768})}Ct()}function fn(){if(f.preRun)for(typeof f.preRun=="function"&&(f.preRun=[f.preRun]);f.preRun.length;)wn(f.preRun.shift());Nt(Dt)}function dn(){et=!0,!f.noFSInit&&!a.initialized&&a.init(),dt.__wasm_call_ctors(),a.ignorePermissions=!1}function pn(){if(f.postRun)for(typeof f.postRun=="function"&&(f.postRun=[f.postRun]);f.postRun.length;)Sn(f.postRun.shift());Nt(Rt)}function tt(e){f.onAbort?.(e),e=`Aborted(${e})`,Le(e),Ee=!0,e+=". Build with -sASSERTIONS for more info.";var n=new WebAssembly.RuntimeError(e);throw je?.(n),n}var kt;function hn(){return f.locateFile?Qe("sqlite3.wasm"):new URL("/assets/sqlite3-BVKGSWc-.wasm",self.location.href).href}function mn(e){if(e==kt&&Ie)return new Uint8Array(Ie);if(We)return We(e);throw"both async and sync fetching of the wasm failed"}async function gn(e){if(!Ie)try{var n=await De(e);return new Uint8Array(n)}catch{}return mn(e)}async function bn(e,n){try{var l=await gn(e);return await WebAssembly.instantiate(l,n)}catch(i){Le(`failed to asynchronously prepare wasm: ${i}`),tt(i)}}async function yn(e,n,l){if(!e)try{var i=fetch(n,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(i,l)}catch(t){Le(`wasm streaming compile failed: ${t}`),Le("falling back to ArrayBuffer instantiation")}return bn(n,l)}function qn(){return{env:Yt,wasi_snapshot_preview1:Yt}}async function vn(){function e(i,t){return dt=i.exports,Ar(dt),dt}function n(i){return e(i.instance)}var l=qn();return f.instantiateWasm?new Promise((i,t)=>{f.instantiateWasm(l,(r,s)=>{i(e(r))})}):(kt??=hn(),n(await yn(Ie,kt,l)))}var ht,Oe,Ve,Je,Fe,it,Nt=e=>{for(;e.length>0;)e.shift()(f)},Rt=[],Sn=e=>Rt.push(e),Dt=[],wn=e=>Dt.push(e),nt,xe={isAbs:e=>e.charAt(0)==="/",splitPath:e=>/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/.exec(e).slice(1),normalizeArray:(e,n)=>{for(var l=0,i=e.length-1;i>=0;i--){var t=e[i];t==="."?e.splice(i,1):t===".."?(e.splice(i,1),l++):l&&(e.splice(i,1),l--)}if(n)for(;l;l--)e.unshift("..");return e},normalize:e=>{var n=xe.isAbs(e),l=e.slice(-1)==="/";return e=xe.normalizeArray(e.split("/").filter(i=>!!i),!n).join("/"),!e&&!n&&(e="."),e&&l&&(e+="/"),(n?"/":"")+e},dirname:e=>{var n=xe.splitPath(e),l=n[0],i=n[1];return!l&&!i?".":(i&&(i=i.slice(0,-1)),l+i)},basename:e=>e&&e.match(/([^\/]+|\/)\/*$/)[1],join:(...e)=>xe.normalize(e.join("/")),join2:(e,n)=>xe.normalize(e+"/"+n)},En=()=>e=>(crypto.getRandomValues(e),0),jt=e=>(jt=En())(e),_t={resolve:(...e)=>{for(var n="",l=!1,i=e.length-1;i>=-1&&!l;i--){var t=i>=0?e[i]:a.cwd();if(typeof t!="string")throw new TypeError("Arguments to path.resolve must be strings");if(!t)return"";n=t+"/"+n,l=xe.isAbs(t)}return n=xe.normalizeArray(n.split("/").filter(r=>!!r),!l).join("/"),(l?"/":"")+n||"."},relative:(e,n)=>{e=_t.resolve(e).slice(1),n=_t.resolve(n).slice(1);function l(b){for(var M=0;M=0&&b[I]==="";I--);return M>I?[]:b.slice(M,I-M+1)}for(var i=l(e.split("/")),t=l(n.split("/")),r=Math.min(i.length,t.length),s=r,_=0;_{for(var t=n+l;e[n]&&!(n>=t);)++n;return n},mt=(e,n=0,l,i)=>{var t=zt(e,n,l);return Mt.decode(e.buffer?e.subarray(n,t):new Uint8Array(e.slice(n,t)))},Tt=[],vt=e=>{for(var n=0,l=0;l=55296&&i<=57343?(n+=4,++l):n+=3}return n},Bt=(e,n,l,i)=>{if(!(i>0))return 0;for(var t=l,r=l+i-1,s=0;s=r)break;n[l++]=_}else if(_<=2047){if(l+1>=r)break;n[l++]=192|_>>6,n[l++]=128|_&63}else if(_<=65535){if(l+2>=r)break;n[l++]=224|_>>12,n[l++]=128|_>>6&63,n[l++]=128|_&63}else{if(l+3>=r)break;n[l++]=240|_>>18,n[l++]=128|_>>12&63,n[l++]=128|_>>6&63,n[l++]=128|_&63,s++}}return n[l]=0,l-t},Ot=(e,n,l)=>{var i=vt(e)+1,t=new Array(i),r=Bt(e,t,0,t.length);return t.length=r,t},An=()=>{if(!Tt.length){var e=null;if(globalThis.window?.prompt&&(e=window.prompt("Input: "),e!==null&&(e+=` +`)),!e)return null;Tt=Ot(e)}return Tt.shift()},st={ttys:[],init(){},shutdown(){},register(e,n){st.ttys[e]={input:[],output:[],ops:n},a.registerDevice(e,st.stream_ops)},stream_ops:{open(e){var n=st.ttys[e.node.rdev];if(!n)throw new a.ErrnoError(43);e.tty=n,e.seekable=!1},close(e){e.tty.ops.fsync(e.tty)},fsync(e){e.tty.ops.fsync(e.tty)},read(e,n,l,i,t){if(!e.tty||!e.tty.ops.get_char)throw new a.ErrnoError(60);for(var r=0,s=0;s0&&(de(mt(e.output)),e.output=[])},ioctl_tcgets(e){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(e,n,l){return 0},ioctl_tiocgwinsz(e){return[24,80]}},default_tty1_ops:{put_char(e,n){n===null||n===10?(Le(mt(e.output)),e.output=[]):n!=0&&e.output.push(n)},fsync(e){e.output?.length>0&&(Le(mt(e.output)),e.output=[])}}},In=(e,n)=>it.fill(0,e,e+n),Wt=(e,n)=>Math.ceil(e/n)*n,Qt=e=>{e=Wt(e,65536);var n=Xt(65536,e);return n&&In(n,e),n},me={ops_table:null,mount(e){return me.createNode(null,"/",16895,0)},createNode(e,n,l,i){if(a.isBlkdev(l)||a.isFIFO(l))throw new a.ErrnoError(63);me.ops_table||={dir:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr,lookup:me.node_ops.lookup,mknod:me.node_ops.mknod,rename:me.node_ops.rename,unlink:me.node_ops.unlink,rmdir:me.node_ops.rmdir,readdir:me.node_ops.readdir,symlink:me.node_ops.symlink},stream:{llseek:me.stream_ops.llseek}},file:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr},stream:{llseek:me.stream_ops.llseek,read:me.stream_ops.read,write:me.stream_ops.write,mmap:me.stream_ops.mmap,msync:me.stream_ops.msync}},link:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr,readlink:me.node_ops.readlink},stream:{}},chrdev:{node:{getattr:me.node_ops.getattr,setattr:me.node_ops.setattr},stream:a.chrdev_stream_ops}};var t=a.createNode(e,n,l,i);return a.isDir(t.mode)?(t.node_ops=me.ops_table.dir.node,t.stream_ops=me.ops_table.dir.stream,t.contents={}):a.isFile(t.mode)?(t.node_ops=me.ops_table.file.node,t.stream_ops=me.ops_table.file.stream,t.usedBytes=0,t.contents=me.emptyFileContents??=new Uint8Array(0)):a.isLink(t.mode)?(t.node_ops=me.ops_table.link.node,t.stream_ops=me.ops_table.link.stream):a.isChrdev(t.mode)&&(t.node_ops=me.ops_table.chrdev.node,t.stream_ops=me.ops_table.chrdev.stream),t.atime=t.mtime=t.ctime=Date.now(),e&&(e.contents[n]=t,e.atime=e.mtime=e.ctime=t.atime),t},getFileDataAsTypedArray(e){return e.contents.subarray(0,e.usedBytes)},expandFileStorage(e,n){var l=e.contents.length;if(!(l>=n)){n=Math.max(n,l*(l<1024*1024?2:1.125)>>>0),l&&(n=Math.max(n,256));var i=me.getFileDataAsTypedArray(e);e.contents=new Uint8Array(n),e.contents.set(i)}},resizeFileStorage(e,n){if(e.usedBytes!=n){var l=e.contents;e.contents=new Uint8Array(n),e.contents.set(l.subarray(0,Math.min(n,e.usedBytes))),e.usedBytes=n}},node_ops:{getattr(e){var n={};return n.dev=a.isChrdev(e.mode)?e.id:1,n.ino=e.id,n.mode=e.mode,n.nlink=1,n.uid=0,n.gid=0,n.rdev=e.rdev,a.isDir(e.mode)?n.size=4096:a.isFile(e.mode)?n.size=e.usedBytes:a.isLink(e.mode)?n.size=e.link.length:n.size=0,n.atime=new Date(e.atime),n.mtime=new Date(e.mtime),n.ctime=new Date(e.ctime),n.blksize=4096,n.blocks=Math.ceil(n.size/n.blksize),n},setattr(e,n){for(const l of["mode","atime","mtime","ctime"])n[l]!=null&&(e[l]=n[l]);n.size!==void 0&&me.resizeFileStorage(e,n.size)},lookup(e,n){throw me.doesNotExistError||(me.doesNotExistError=new a.ErrnoError(44),me.doesNotExistError.stack=""),me.doesNotExistError},mknod(e,n,l,i){return me.createNode(e,n,l,i)},rename(e,n,l){var i;try{i=a.lookupNode(n,l)}catch{}if(i){if(a.isDir(e.mode))for(var t in i.contents)throw new a.ErrnoError(55);a.hashRemoveNode(i)}delete e.parent.contents[e.name],n.contents[l]=e,e.name=l,n.ctime=n.mtime=e.parent.ctime=e.parent.mtime=Date.now()},unlink(e,n){delete e.contents[n],e.ctime=e.mtime=Date.now()},rmdir(e,n){for(var l in a.lookupNode(e,n).contents)throw new a.ErrnoError(55);delete e.contents[n],e.ctime=e.mtime=Date.now()},readdir(e){return[".","..",...Object.keys(e.contents)]},symlink(e,n,l){var i=me.createNode(e,n,41471,0);return i.link=l,i},readlink(e){if(!a.isLink(e.mode))throw new a.ErrnoError(28);return e.link}},stream_ops:{read(e,n,l,i,t){var r=e.node.contents;if(t>=e.node.usedBytes)return 0;var s=Math.min(e.node.usedBytes-t,i);return n.set(r.subarray(t,t+s),l),s},write(e,n,l,i,t,r){if(n.buffer===Je.buffer&&(r=!1),!i)return 0;var s=e.node;return s.mtime=s.ctime=Date.now(),r?(s.contents=n.subarray(l,l+i),s.usedBytes=i):s.usedBytes===0&&t===0?(s.contents=n.slice(l,l+i),s.usedBytes=i):(me.expandFileStorage(s,t+i),s.contents.set(n.subarray(l,l+i),t),s.usedBytes=Math.max(s.usedBytes,t+i)),i},llseek(e,n,l){var i=n;if(l===1?i+=e.position:l===2&&a.isFile(e.node.mode)&&(i+=e.node.usedBytes),i<0)throw new a.ErrnoError(28);return i},mmap(e,n,l,i,t){if(!a.isFile(e.node.mode))throw new a.ErrnoError(43);var r,s,_=e.node.contents;if(!(t&2)&&_.buffer===Je.buffer)s=!1,r=_.byteOffset;else{if(s=!0,r=Qt(n),!r)throw new a.ErrnoError(48);_&&((l>0||l+n<_.length)&&(_.subarray?_=_.subarray(l,l+n):_=Array.prototype.slice.call(_,l,l+n)),Je.set(_,r))}return{ptr:r,allocated:s}},msync(e,n,l,i,t){return me.stream_ops.write(e,n,0,i,l,!1),0}}},kn=e=>{if(typeof e!="string")return e;var n={r:0,"r+":2,w:577,"w+":578,a:1089,"a+":1090}[e];if(typeof n>"u")throw new Error(`Unknown file open mode: ${e}`);return n},Ut=e=>(typeof e=="string"&&(e=Ot(e)),e.subarray||(e=new Uint8Array(e)),e),xt=(e,n)=>{var l=0;return e&&(l|=365),n&&(l|=146),l},Tn=async e=>{var n=await De(e);return new Uint8Array(n)},On=(...e)=>a.createDataFile(...e),ot=0,gt=null,xn=e=>{if(ot--,f.monitorRunDependencies?.(ot),ot==0&>){var n=gt;gt=null,n()}},Pn=e=>{ot++,f.monitorRunDependencies?.(ot)},Vt=[],Fn=async(e,n)=>{typeof Browser<"u"&&Browser.init();for(var l of Vt)if(l.canHandle(n))return l.handle(e,n);return e},Ht=async(e,n,l,i,t,r,s,_)=>{var c=n?_t.resolve(xe.join2(e,n)):e;Pn();try{var b=l;typeof l=="string"&&(b=await Tn(l)),b=await Fn(b,c),_?.(),r||On(e,n,b,i,t,s)}finally{xn()}},Ln=(e,n,l,i,t,r,s,_,c,b)=>{Ht(e,n,l,i,t,_,c,b).then(r).catch(s)},a={root:null,mounts:[],devices:{},streams:[],nextInode:1,nameTable:null,currentPath:"/",initialized:!1,ignorePermissions:!0,filesystems:null,syncFSRequests:0,ErrnoError:class{name="ErrnoError";constructor(e){this.errno=e}},FSStream:class{shared={};get object(){return this.node}set object(e){this.node=e}get isRead(){return(this.flags&2097155)!==1}get isWrite(){return(this.flags&2097155)!==0}get isAppend(){return this.flags&1024}get flags(){return this.shared.flags}set flags(e){this.shared.flags=e}get position(){return this.shared.position}set position(e){this.shared.position=e}},FSNode:class{node_ops={};stream_ops={};readMode=365;writeMode=146;mounted=null;constructor(e,n,l,i){e||(e=this),this.parent=e,this.mount=e.mount,this.id=a.nextInode++,this.name=n,this.mode=l,this.rdev=i,this.atime=this.mtime=this.ctime=Date.now()}get read(){return(this.mode&this.readMode)===this.readMode}set read(e){e?this.mode|=this.readMode:this.mode&=~this.readMode}get write(){return(this.mode&this.writeMode)===this.writeMode}set write(e){e?this.mode|=this.writeMode:this.mode&=~this.writeMode}get isFolder(){return a.isDir(this.mode)}get isDevice(){return a.isChrdev(this.mode)}},lookupPath(e,n={}){if(!e)throw new a.ErrnoError(44);n.follow_mount??=!0,xe.isAbs(e)||(e=a.cwd()+"/"+e);e:for(var l=0;l<40;l++){for(var i=e.split("/").filter(b=>!!b),t=a.root,r="/",s=0;s>>0)%a.nameTable.length},hashAddNode(e){var n=a.hashName(e.parent.id,e.name);e.name_next=a.nameTable[n],a.nameTable[n]=e},hashRemoveNode(e){var n=a.hashName(e.parent.id,e.name);if(a.nameTable[n]===e)a.nameTable[n]=e.name_next;else for(var l=a.nameTable[n];l;){if(l.name_next===e){l.name_next=e.name_next;break}l=l.name_next}},lookupNode(e,n){var l=a.mayLookup(e);if(l)throw new a.ErrnoError(l);for(var i=a.hashName(e.id,n),t=a.nameTable[i];t;t=t.name_next){var r=t.name;if(t.parent.id===e.id&&r===n)return t}return a.lookup(e,n)},createNode(e,n,l,i){var t=new a.FSNode(e,n,l,i);return a.hashAddNode(t),t},destroyNode(e){a.hashRemoveNode(e)},isRoot(e){return e===e.parent},isMountpoint(e){return!!e.mounted},isFile(e){return(e&61440)===32768},isDir(e){return(e&61440)===16384},isLink(e){return(e&61440)===40960},isChrdev(e){return(e&61440)===8192},isBlkdev(e){return(e&61440)===24576},isFIFO(e){return(e&61440)===4096},isSocket(e){return(e&49152)===49152},flagsToPermissionString(e){var n=["r","w","rw"][e&3];return e&512&&(n+="w"),n},nodePermissions(e,n){return a.ignorePermissions?0:n.includes("r")&&!(e.mode&292)||n.includes("w")&&!(e.mode&146)||n.includes("x")&&!(e.mode&73)?2:0},mayLookup(e){if(!a.isDir(e.mode))return 54;var n=a.nodePermissions(e,"x");return n||(e.node_ops.lookup?0:2)},mayCreate(e,n){if(!a.isDir(e.mode))return 54;try{return a.lookupNode(e,n),20}catch{}return a.nodePermissions(e,"wx")},mayDelete(e,n,l){var i;try{i=a.lookupNode(e,n)}catch(r){return r.errno}var t=a.nodePermissions(e,"wx");if(t)return t;if(l){if(!a.isDir(i.mode))return 54;if(a.isRoot(i)||a.getPath(i)===a.cwd())return 10}else if(a.isDir(i.mode))return 31;return 0},mayOpen(e,n){if(!e)return 44;if(a.isLink(e.mode))return 32;var l=a.flagsToPermissionString(n);return a.isDir(e.mode)&&(l!=="r"||n&576)?31:a.nodePermissions(e,l)},checkOpExists(e,n){if(!e)throw new a.ErrnoError(n);return e},MAX_OPEN_FDS:4096,nextfd(){for(var e=0;e<=a.MAX_OPEN_FDS;e++)if(!a.streams[e])return e;throw new a.ErrnoError(33)},getStreamChecked(e){var n=a.getStream(e);if(!n)throw new a.ErrnoError(8);return n},getStream:e=>a.streams[e],createStream(e,n=-1){return e=Object.assign(new a.FSStream,e),n==-1&&(n=a.nextfd()),e.fd=n,a.streams[n]=e,e},closeStream(e){a.streams[e]=null},dupStream(e,n=-1){var l=a.createStream(e,n);return l.stream_ops?.dup?.(l),l},doSetAttr(e,n,l){var i=e?.stream_ops.setattr,t=i?e:n;i??=n.node_ops.setattr,a.checkOpExists(i,63),i(t,l)},chrdev_stream_ops:{open(e){e.stream_ops=a.getDevice(e.node.rdev).stream_ops,e.stream_ops.open?.(e)},llseek(){throw new a.ErrnoError(70)}},major:e=>e>>8,minor:e=>e&255,makedev:(e,n)=>e<<8|n,registerDevice(e,n){a.devices[e]={stream_ops:n}},getDevice:e=>a.devices[e],getMounts(e){for(var n=[],l=[e];l.length;){var i=l.pop();n.push(i),l.push(...i.mounts)}return n},syncfs(e,n){typeof e=="function"&&(n=e,e=!1),a.syncFSRequests++,a.syncFSRequests>1&&Le(`warning: ${a.syncFSRequests} FS.syncfs operations in flight at once, probably just doing extra work`);var l=a.getMounts(a.root.mount),i=0;function t(_){return a.syncFSRequests--,n(_)}function r(_){if(_)return r.errored?void 0:(r.errored=!0,t(_));++i>=l.length&&t(null)}for(var s of l)s.type.syncfs?s.type.syncfs(s,e,r):r(null)},mount(e,n,l){var i=l==="/",t=!l,r;if(i&&a.root)throw new a.ErrnoError(10);if(!i&&!t){var s=a.lookupPath(l,{follow_mount:!1});if(l=s.path,r=s.node,a.isMountpoint(r))throw new a.ErrnoError(10);if(!a.isDir(r.mode))throw new a.ErrnoError(54)}var _={type:e,opts:n,mountpoint:l,mounts:[]},c=e.mount(_);return c.mount=_,_.root=c,i?a.root=c:r&&(r.mounted=_,r.mount&&r.mount.mounts.push(_)),c},unmount(e){var n=a.lookupPath(e,{follow_mount:!1});if(!a.isMountpoint(n.node))throw new a.ErrnoError(28);var l=n.node,i=l.mounted,t=a.getMounts(i);for(var[r,s]of Object.entries(a.nameTable))for(;s;){var _=s.name_next;t.includes(s.mount)&&a.destroyNode(s),s=_}l.mounted=null;var c=l.mount.mounts.indexOf(i);l.mount.mounts.splice(c,1)},lookup(e,n){return e.node_ops.lookup(e,n)},mknod(e,n,l){var i=a.lookupPath(e,{parent:!0}).node,t=xe.basename(e);if(!t)throw new a.ErrnoError(28);if(t==="."||t==="..")throw new a.ErrnoError(20);var r=a.mayCreate(i,t);if(r)throw new a.ErrnoError(r);if(!i.node_ops.mknod)throw new a.ErrnoError(63);return i.node_ops.mknod(i,t,n,l)},statfs(e){return a.statfsNode(a.lookupPath(e,{follow:!0}).node)},statfsStream(e){return a.statfsNode(e.node)},statfsNode(e){var n={bsize:4096,frsize:4096,blocks:1e6,bfree:5e5,bavail:5e5,files:a.nextInode,ffree:a.nextInode-1,fsid:42,flags:2,namelen:255};return e.node_ops.statfs&&Object.assign(n,e.node_ops.statfs(e.mount.opts.root)),n},create(e,n=438){return n&=4095,n|=32768,a.mknod(e,n,0)},mkdir(e,n=511){return n&=1023,n|=16384,a.mknod(e,n,0)},mkdirTree(e,n){var l=e.split("/"),i="";for(var t of l)if(t){(i||xe.isAbs(e))&&(i+="/"),i+=t;try{a.mkdir(i,n)}catch(r){if(r.errno!=20)throw r}}},mkdev(e,n,l){return typeof l>"u"&&(l=n,n=438),n|=8192,a.mknod(e,n,l)},symlink(e,n){if(!_t.resolve(e))throw new a.ErrnoError(44);var l=a.lookupPath(n,{parent:!0}).node;if(!l)throw new a.ErrnoError(44);var i=xe.basename(n),t=a.mayCreate(l,i);if(t)throw new a.ErrnoError(t);if(!l.node_ops.symlink)throw new a.ErrnoError(63);return l.node_ops.symlink(l,i,e)},rename(e,n){var l=xe.dirname(e),i=xe.dirname(n),t=xe.basename(e),r=xe.basename(n),s=a.lookupPath(e,{parent:!0}),_=s.node,c;if(s=a.lookupPath(n,{parent:!0}),c=s.node,!_||!c)throw new a.ErrnoError(44);if(_.mount!==c.mount)throw new a.ErrnoError(75);var b=a.lookupNode(_,t),M=_t.relative(e,i);if(M.charAt(0)!==".")throw new a.ErrnoError(28);if(M=_t.relative(n,l),M.charAt(0)!==".")throw new a.ErrnoError(55);var I;try{I=a.lookupNode(c,r)}catch{}if(b!==I){var S=a.isDir(b.mode),w=a.mayDelete(_,t,S);if(w)throw new a.ErrnoError(w);if(w=I?a.mayDelete(c,r,S):a.mayCreate(c,r),w)throw new a.ErrnoError(w);if(!_.node_ops.rename)throw new a.ErrnoError(63);if(a.isMountpoint(b)||I&&a.isMountpoint(I))throw new a.ErrnoError(10);if(c!==_&&(w=a.nodePermissions(_,"w"),w))throw new a.ErrnoError(w);a.hashRemoveNode(b);try{_.node_ops.rename(b,c,r),b.parent=c}catch(x){throw x}finally{a.hashAddNode(b)}}},rmdir(e){var n=a.lookupPath(e,{parent:!0}).node,l=xe.basename(e),i=a.lookupNode(n,l),t=a.mayDelete(n,l,!0);if(t)throw new a.ErrnoError(t);if(!n.node_ops.rmdir)throw new a.ErrnoError(63);if(a.isMountpoint(i))throw new a.ErrnoError(10);n.node_ops.rmdir(n,l),a.destroyNode(i)},readdir(e){var n=a.lookupPath(e,{follow:!0}).node;return a.checkOpExists(n.node_ops.readdir,54)(n)},unlink(e){var n=a.lookupPath(e,{parent:!0}).node;if(!n)throw new a.ErrnoError(44);var l=xe.basename(e),i=a.lookupNode(n,l),t=a.mayDelete(n,l,!1);if(t)throw new a.ErrnoError(t);if(!n.node_ops.unlink)throw new a.ErrnoError(63);if(a.isMountpoint(i))throw new a.ErrnoError(10);n.node_ops.unlink(n,l),a.destroyNode(i)},readlink(e){var n=a.lookupPath(e).node;if(!n)throw new a.ErrnoError(44);if(!n.node_ops.readlink)throw new a.ErrnoError(28);return n.node_ops.readlink(n)},stat(e,n){var l=a.lookupPath(e,{follow:!n}).node;return a.checkOpExists(l.node_ops.getattr,63)(l)},fstat(e){var n=a.getStreamChecked(e),l=n.node,i=n.stream_ops.getattr,t=i?n:l;return i??=l.node_ops.getattr,a.checkOpExists(i,63),i(t)},lstat(e){return a.stat(e,!0)},doChmod(e,n,l,i){a.doSetAttr(e,n,{mode:l&4095|n.mode&-4096,ctime:Date.now(),dontFollow:i})},chmod(e,n,l){var i;typeof e=="string"?i=a.lookupPath(e,{follow:!l}).node:i=e,a.doChmod(null,i,n,l)},lchmod(e,n){a.chmod(e,n,!0)},fchmod(e,n){var l=a.getStreamChecked(e);a.doChmod(l,l.node,n,!1)},doChown(e,n,l){a.doSetAttr(e,n,{timestamp:Date.now(),dontFollow:l})},chown(e,n,l,i){var t;typeof e=="string"?t=a.lookupPath(e,{follow:!i}).node:t=e,a.doChown(null,t,i)},lchown(e,n,l){a.chown(e,n,l,!0)},fchown(e,n,l){var i=a.getStreamChecked(e);a.doChown(i,i.node,!1)},doTruncate(e,n,l){if(a.isDir(n.mode))throw new a.ErrnoError(31);if(!a.isFile(n.mode))throw new a.ErrnoError(28);var i=a.nodePermissions(n,"w");if(i)throw new a.ErrnoError(i);a.doSetAttr(e,n,{size:l,timestamp:Date.now()})},truncate(e,n){if(n<0)throw new a.ErrnoError(28);var l;typeof e=="string"?l=a.lookupPath(e,{follow:!0}).node:l=e,a.doTruncate(null,l,n)},ftruncate(e,n){var l=a.getStreamChecked(e);if(n<0||(l.flags&2097155)===0)throw new a.ErrnoError(28);a.doTruncate(l,l.node,n)},utime(e,n,l){var i=a.lookupPath(e,{follow:!0}).node;a.checkOpExists(i.node_ops.setattr,63)(i,{atime:n,mtime:l})},open(e,n,l=438){if(e==="")throw new a.ErrnoError(44);n=kn(n),n&64?l=l&4095|32768:l=0;var i,t;if(typeof e=="object")i=e;else{t=e.endsWith("/");var r=a.lookupPath(e,{follow:!(n&131072),noent_okay:!0});i=r.node,e=r.path}var s=!1;if(n&64)if(i){if(n&128)throw new a.ErrnoError(20)}else{if(t)throw new a.ErrnoError(31);i=a.mknod(e,l|511,0),s=!0}if(!i)throw new a.ErrnoError(44);if(a.isChrdev(i.mode)&&(n&=-513),n&65536&&!a.isDir(i.mode))throw new a.ErrnoError(54);if(!s){var _=a.mayOpen(i,n);if(_)throw new a.ErrnoError(_)}n&512&&!s&&a.truncate(i,0),n&=-131713;var c=a.createStream({node:i,path:a.getPath(i),flags:n,seekable:!0,position:0,stream_ops:i.stream_ops,ungotten:[],error:!1});return c.stream_ops.open&&c.stream_ops.open(c),s&&a.chmod(i,l&511),c},close(e){if(a.isClosed(e))throw new a.ErrnoError(8);e.getdents&&(e.getdents=null);try{e.stream_ops.close&&e.stream_ops.close(e)}catch(n){throw n}finally{a.closeStream(e.fd)}e.fd=null},isClosed(e){return e.fd===null},llseek(e,n,l){if(a.isClosed(e))throw new a.ErrnoError(8);if(!e.seekable||!e.stream_ops.llseek)throw new a.ErrnoError(70);if(l!=0&&l!=1&&l!=2)throw new a.ErrnoError(28);return e.position=e.stream_ops.llseek(e,n,l),e.ungotten=[],e.position},read(e,n,l,i,t){if(i<0||t<0)throw new a.ErrnoError(28);if(a.isClosed(e))throw new a.ErrnoError(8);if((e.flags&2097155)===1)throw new a.ErrnoError(8);if(a.isDir(e.node.mode))throw new a.ErrnoError(31);if(!e.stream_ops.read)throw new a.ErrnoError(28);var r=typeof t<"u";if(!r)t=e.position;else if(!e.seekable)throw new a.ErrnoError(70);var s=e.stream_ops.read(e,n,l,i,t);return r||(e.position+=s),s},write(e,n,l,i,t,r){if(i<0||t<0)throw new a.ErrnoError(28);if(a.isClosed(e))throw new a.ErrnoError(8);if((e.flags&2097155)===0)throw new a.ErrnoError(8);if(a.isDir(e.node.mode))throw new a.ErrnoError(31);if(!e.stream_ops.write)throw new a.ErrnoError(28);e.seekable&&e.flags&1024&&a.llseek(e,0,2);var s=typeof t<"u";if(!s)t=e.position;else if(!e.seekable)throw new a.ErrnoError(70);var _=e.stream_ops.write(e,n,l,i,t,r);return s||(e.position+=_),_},mmap(e,n,l,i,t){if((i&2)!==0&&(t&2)===0&&(e.flags&2097155)!==2)throw new a.ErrnoError(2);if((e.flags&2097155)===1)throw new a.ErrnoError(2);if(!e.stream_ops.mmap)throw new a.ErrnoError(43);if(!n)throw new a.ErrnoError(28);return e.stream_ops.mmap(e,n,l,i,t)},msync(e,n,l,i,t){return e.stream_ops.msync?e.stream_ops.msync(e,n,l,i,t):0},ioctl(e,n,l){if(!e.stream_ops.ioctl)throw new a.ErrnoError(59);return e.stream_ops.ioctl(e,n,l)},readFile(e,n={}){n.flags=n.flags||0,n.encoding=n.encoding||"binary",n.encoding!=="utf8"&&n.encoding!=="binary"&&tt(`Invalid encoding type "${n.encoding}"`);var l=a.open(e,n.flags),i=a.stat(e).size,t=new Uint8Array(i);return a.read(l,t,0,i,0),n.encoding==="utf8"&&(t=mt(t)),a.close(l),t},writeFile(e,n,l={}){l.flags=l.flags||577;var i=a.open(e,l.flags,l.mode);n=Ut(n),a.write(i,n,0,n.byteLength,void 0,l.canOwn),a.close(i)},cwd:()=>a.currentPath,chdir(e){var n=a.lookupPath(e,{follow:!0});if(n.node===null)throw new a.ErrnoError(44);if(!a.isDir(n.node.mode))throw new a.ErrnoError(54);var l=a.nodePermissions(n.node,"x");if(l)throw new a.ErrnoError(l);a.currentPath=n.path},createDefaultDirectories(){a.mkdir("/tmp"),a.mkdir("/home"),a.mkdir("/home/web_user")},createDefaultDevices(){a.mkdir("/dev"),a.registerDevice(a.makedev(1,3),{read:()=>0,write:(i,t,r,s,_)=>s,llseek:()=>0}),a.mkdev("/dev/null",a.makedev(1,3)),st.register(a.makedev(5,0),st.default_tty_ops),st.register(a.makedev(6,0),st.default_tty1_ops),a.mkdev("/dev/tty",a.makedev(5,0)),a.mkdev("/dev/tty1",a.makedev(6,0));var e=new Uint8Array(1024),n=0,l=()=>(n===0&&(jt(e),n=e.byteLength),e[--n]);a.createDevice("/dev","random",l),a.createDevice("/dev","urandom",l),a.mkdir("/dev/shm"),a.mkdir("/dev/shm/tmp")},createSpecialDirectories(){a.mkdir("/proc");var e=a.mkdir("/proc/self");a.mkdir("/proc/self/fd"),a.mount({mount(){var n=a.createNode(e,"fd",16895,73);return n.stream_ops={llseek:me.stream_ops.llseek},n.node_ops={lookup(l,i){var t=+i,r=a.getStreamChecked(t),s={parent:null,mount:{mountpoint:"fake"},node_ops:{readlink:()=>r.path},id:t+1};return s.parent=s,s},readdir(){return Array.from(a.streams.entries()).filter(([l,i])=>i).map(([l,i])=>l.toString())}},n}},{},"/proc/self/fd")},createStandardStreams(e,n,l){e?a.createDevice("/dev","stdin",e):a.symlink("/dev/tty","/dev/stdin"),n?a.createDevice("/dev","stdout",null,n):a.symlink("/dev/tty","/dev/stdout"),l?a.createDevice("/dev","stderr",null,l):a.symlink("/dev/tty1","/dev/stderr"),a.open("/dev/stdin",0),a.open("/dev/stdout",1),a.open("/dev/stderr",1)},staticInit(){a.nameTable=new Array(4096),a.mount(me,{},"/"),a.createDefaultDirectories(),a.createDefaultDevices(),a.createSpecialDirectories(),a.filesystems={MEMFS:me}},init(e,n,l){a.initialized=!0,e??=f.stdin,n??=f.stdout,l??=f.stderr,a.createStandardStreams(e,n,l)},quit(){a.initialized=!1;for(var e of a.streams)e&&a.close(e)},findObject(e,n){var l=a.analyzePath(e,n);return l.exists?l.object:null},analyzePath(e,n){try{var l=a.lookupPath(e,{follow:!n});e=l.path}catch{}var i={isRoot:!1,exists:!1,error:0,name:null,path:null,object:null,parentExists:!1,parentPath:null,parentObject:null};try{var l=a.lookupPath(e,{parent:!0});i.parentExists=!0,i.parentPath=l.path,i.parentObject=l.node,i.name=xe.basename(e),l=a.lookupPath(e,{follow:!n}),i.exists=!0,i.path=l.path,i.object=l.node,i.name=l.node.name,i.isRoot=l.path==="/"}catch(t){i.error=t.errno}return i},createPath(e,n,l,i){e=typeof e=="string"?e:a.getPath(e);for(var t=n.split("/").reverse();t.length;){var r=t.pop();if(r){var s=xe.join2(e,r);try{a.mkdir(s)}catch(_){if(_.errno!=20)throw _}e=s}}return s},createFile(e,n,l,i,t){var r=xe.join2(typeof e=="string"?e:a.getPath(e),n),s=xt(i,t);return a.create(r,s)},createDataFile(e,n,l,i,t,r){var s=n;e&&(e=typeof e=="string"?e:a.getPath(e),s=n?xe.join2(e,n):e);var _=xt(i,t),c=a.create(s,_);if(l){l=Ut(l),a.chmod(c,_|146);var b=a.open(c,577);a.write(b,l,0,l.length,0,r),a.close(b),a.chmod(c,_)}},createDevice(e,n,l,i){var t=xe.join2(typeof e=="string"?e:a.getPath(e),n),r=xt(!!l,!!i);a.createDevice.major??=64;var s=a.makedev(a.createDevice.major++,0);return a.registerDevice(s,{open(_){_.seekable=!1},close(_){i?.buffer?.length&&i(10)},read(_,c,b,M,I){for(var S=0,w=0;wthis.length-1||I<0)){var S=I%this.chunkSize,w=I/this.chunkSize|0;return this.getter(w)[S]}}setDataGetter(I){this.getter=I}cacheLength(){var I=new XMLHttpRequest;I.open("HEAD",l,!1),I.send(null),I.status>=200&&I.status<300||I.status===304||tt("Couldn't load "+l+". Status: "+I.status);var S=Number(I.getResponseHeader("Content-length")),w,x=(w=I.getResponseHeader("Accept-Ranges"))&&w==="bytes",L=(w=I.getResponseHeader("Content-Encoding"))&&w==="gzip",H=1024*1024;x||(H=S);var g=(D,Q)=>{D>Q&&tt("invalid range ("+D+", "+Q+") or no bytes requested!"),Q>S-1&&tt("only "+S+" bytes available! programmer error!");var A=new XMLHttpRequest;return A.open("GET",l,!1),S!==H&&A.setRequestHeader("Range","bytes="+D+"-"+Q),A.responseType="arraybuffer",A.overrideMimeType&&A.overrideMimeType("text/plain; charset=x-user-defined"),A.send(null),A.status>=200&&A.status<300||A.status===304||tt("Couldn't load "+l+". Status: "+A.status),A.response!==void 0?new Uint8Array(A.response||[]):Ot(A.responseText||"")},h=this;h.setDataGetter(D=>{var Q=D*H,A=(D+1)*H-1;return A=Math.min(A,S-1),typeof h.chunks[D]>"u"&&(h.chunks[D]=g(Q,A)),typeof h.chunks[D]>"u"&&tt("doXHR failed!"),h.chunks[D]}),(L||!S)&&(H=S=1,S=this.getter(0).length,H=S,de("LazyFiles on gzip forces download of the whole file when length is accessed")),this._length=S,this._chunkSize=H,this.lengthKnown=!0}get length(){return this.lengthKnown||this.cacheLength(),this._length}get chunkSize(){return this.lengthKnown||this.cacheLength(),this._chunkSize}}if(globalThis.XMLHttpRequest){ye||tt("Cannot do synchronous binary XHRs outside webworkers in modern browsers. Use --embed-file or --preload-file in emcc");var s={isDevice:!1,contents:new r}}else var s={isDevice:!1,url:l};var _=a.createFile(e,n,s,i,t);s.contents?_.contents=s.contents:s.url&&(_.contents=null,_.url=s.url),Object.defineProperties(_,{usedBytes:{get:function(){return this.contents.length}}});var c={};for(const[M,I]of Object.entries(_.stream_ops))c[M]=(...S)=>(a.forceLoadFile(_),I(...S));function b(M,I,S,w,x){var L=M.node.contents;if(x>=L.length)return 0;var H=Math.min(L.length-x,w);if(L.slice)for(var g=0;g(a.forceLoadFile(_),b(M,I,S,w,x)),c.mmap=(M,I,S,w,x)=>{a.forceLoadFile(_);var L=Qt(I);if(!L)throw new a.ErrnoError(48);return b(M,Je,L,I,S),{ptr:L,allocated:!0}},_.stream_ops=c,_}},Cn=(e,n,l)=>{if(!e)return"";var i=zt(it,e,n);return Mt.decode(it.subarray(e,i))},ve={calculateAt(e,n,l){if(xe.isAbs(n))return n;var i;if(e===-100?i=a.cwd():i=ve.getStreamFromFD(e).path,n.length==0){if(!l)throw new a.ErrnoError(44);return i}return i+"/"+n},writeStat(e,n){Fe[e>>2]=n.dev,Fe[e+4>>2]=n.mode,Fe[e+8>>2]=n.nlink,Fe[e+12>>2]=n.uid,Fe[e+16>>2]=n.gid,Fe[e+20>>2]=n.rdev,Ve[e+24>>3]=BigInt(n.size),Oe[e+32>>2]=4096,Oe[e+36>>2]=n.blocks;var l=n.atime.getTime(),i=n.mtime.getTime(),t=n.ctime.getTime();return Ve[e+40>>3]=BigInt(Math.floor(l/1e3)),Fe[e+48>>2]=l%1e3*1e3*1e3,Ve[e+56>>3]=BigInt(Math.floor(i/1e3)),Fe[e+64>>2]=i%1e3*1e3*1e3,Ve[e+72>>3]=BigInt(Math.floor(t/1e3)),Fe[e+80>>2]=t%1e3*1e3*1e3,Ve[e+88>>3]=BigInt(n.ino),0},writeStatFs(e,n){Fe[e+4>>2]=n.bsize,Fe[e+60>>2]=n.bsize,Ve[e+8>>3]=BigInt(n.blocks),Ve[e+16>>3]=BigInt(n.bfree),Ve[e+24>>3]=BigInt(n.bavail),Ve[e+32>>3]=BigInt(n.files),Ve[e+40>>3]=BigInt(n.ffree),Fe[e+48>>2]=n.fsid,Fe[e+64>>2]=n.flags,Fe[e+56>>2]=n.namelen},doMsync(e,n,l,i,t){if(!a.isFile(n.node.mode))throw new a.ErrnoError(43);if(i&2)return 0;var r=it.slice(e,e+l);a.msync(n,r,t,l,i)},getStreamFromFD(e){return a.getStreamChecked(e)},varargs:void 0,getStr(e){return Cn(e)}};function Nn(e,n){try{return e=ve.getStr(e),a.chmod(e,n),0}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function Rn(e,n,l,i){try{if(n=ve.getStr(n),n=ve.calculateAt(e,n),l&-8)return-28;var t=a.lookupPath(n,{follow:!0}).node;if(!t)return-44;var r="";return l&4&&(r+="r"),l&2&&(r+="w"),l&1&&(r+="x"),r&&a.nodePermissions(t,r)?-2:0}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function Dn(e,n){try{return a.fchmod(e,n),0}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function jn(e,n,l){try{return a.fchown(e,n,l),0}catch(i){if(typeof a>"u"||i.name!=="ErrnoError")throw i;return-i.errno}}var St=()=>{var e=Oe[+ve.varargs>>2];return ve.varargs+=4,e},ft=St;function Mn(e,n,l){ve.varargs=l;try{var i=ve.getStreamFromFD(e);switch(n){case 0:var t=St();if(t<0)return-28;for(;a.streams[t];)t++;return a.dupStream(i,t).fd;case 1:case 2:return 0;case 3:return i.flags;case 4:var t=St();return i.flags|=t,0;case 12:var t=ft(),r=0;return ht[t+r>>1]=2,0;case 13:case 14:return 0}return-28}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function zn(e,n){try{return ve.writeStat(n,a.fstat(e))}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}var Bn=9007199254740992,Wn=-9007199254740992,bt=e=>eBn?NaN:Number(e);function Qn(e,n){n=bt(n);try{return isNaN(n)?-61:(a.ftruncate(e,n),0)}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}var lt=(e,n,l)=>Bt(e,it,n,l);function Un(e,n){try{if(n===0)return-28;var l=a.cwd(),i=vt(l)+1;return n"u"||t.name!=="ErrnoError")throw t;return-t.errno}}function Vn(e,n,l){ve.varargs=l;try{var i=ve.getStreamFromFD(e);switch(n){case 21509:return i.tty?0:-59;case 21505:if(!i.tty)return-59;if(i.tty.ops.ioctl_tcgets){var t=i.tty.ops.ioctl_tcgets(i),I=ft();Oe[I>>2]=t.c_iflag||0,Oe[I+4>>2]=t.c_oflag||0,Oe[I+8>>2]=t.c_cflag||0,Oe[I+12>>2]=t.c_lflag||0;for(var r=0;r<32;r++)Je[I+r+17]=t.c_cc[r]||0;return 0}return 0;case 21510:case 21511:case 21512:return i.tty?0:-59;case 21506:case 21507:case 21508:if(!i.tty)return-59;if(i.tty.ops.ioctl_tcsets){for(var I=ft(),s=Oe[I>>2],_=Oe[I+4>>2],c=Oe[I+8>>2],b=Oe[I+12>>2],M=[],r=0;r<32;r++)M.push(Je[I+r+17]);return i.tty.ops.ioctl_tcsets(i.tty,n,{c_iflag:s,c_oflag:_,c_cflag:c,c_lflag:b,c_cc:M})}return 0;case 21519:if(!i.tty)return-59;var I=ft();return Oe[I>>2]=0,0;case 21520:return i.tty?-28:-59;case 21537:case 21531:var I=ft();return a.ioctl(i,n,I);case 21523:if(!i.tty)return-59;if(i.tty.ops.ioctl_tiocgwinsz){var S=i.tty.ops.ioctl_tiocgwinsz(i.tty),I=ft();ht[I>>1]=S[0],ht[I+2>>1]=S[1]}return 0;case 21524:return i.tty?0:-59;case 21515:return i.tty?0:-59;default:return-28}}catch(w){if(typeof a>"u"||w.name!=="ErrnoError")throw w;return-w.errno}}function Hn(e,n){try{return e=ve.getStr(e),ve.writeStat(n,a.lstat(e))}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function Gn(e,n,l){try{return n=ve.getStr(n),n=ve.calculateAt(e,n),a.mkdir(n,l,0),0}catch(i){if(typeof a>"u"||i.name!=="ErrnoError")throw i;return-i.errno}}function $n(e,n,l,i){try{n=ve.getStr(n);var t=i&256,r=i&4096;return i=i&-6401,n=ve.calculateAt(e,n,r),ve.writeStat(l,t?a.lstat(n):a.stat(n))}catch(s){if(typeof a>"u"||s.name!=="ErrnoError")throw s;return-s.errno}}function Kn(e,n,l,i){ve.varargs=i;try{n=ve.getStr(n),n=ve.calculateAt(e,n);var t=i?St():0;return a.open(n,l,t).fd}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return-r.errno}}function Jn(e,n,l,i){try{if(n=ve.getStr(n),n=ve.calculateAt(e,n),i<=0)return-28;var t=a.readlink(n),r=Math.min(i,vt(t)),s=Je[l+r];return lt(t,l,i+1),Je[l+r]=s,r}catch(_){if(typeof a>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}function Xn(e){try{return e=ve.getStr(e),a.rmdir(e),0}catch(n){if(typeof a>"u"||n.name!=="ErrnoError")throw n;return-n.errno}}function Yn(e,n){try{return e=ve.getStr(e),ve.writeStat(n,a.stat(e))}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return-l.errno}}function Zn(e,n,l){try{if(n=ve.getStr(n),n=ve.calculateAt(e,n),!l)a.unlink(n);else if(l===512)a.rmdir(n);else return-28;return 0}catch(i){if(typeof a>"u"||i.name!=="ErrnoError")throw i;return-i.errno}}var Gt=e=>Fe[e>>2]+Oe[e+4>>2]*4294967296;function er(e,n,l,i){try{n=ve.getStr(n),n=ve.calculateAt(e,n,!0);var t=Date.now(),r,s;if(!l)r=t,s=t;else{var _=Gt(l),c=Oe[l+8>>2];c==1073741823?r=t:c==1073741822?r=null:r=_*1e3+c/(1e3*1e3),l+=16,_=Gt(l),c=Oe[l+8>>2],c==1073741823?s=t:c==1073741822?s=null:s=_*1e3+c/(1e3*1e3)}return(s??r)!==null&&a.utime(n,r,s),0}catch(b){if(typeof a>"u"||b.name!=="ErrnoError")throw b;return-b.errno}}var tr=e=>e%4===0&&(e%100!==0||e%400===0),nr=[0,31,60,91,121,152,182,213,244,274,305,335],rr=[0,31,59,90,120,151,181,212,243,273,304,334],ir=e=>(tr(e.getFullYear())?nr:rr)[e.getMonth()]+e.getDate()-1;function sr(e,n){e=bt(e);var l=new Date(e*1e3);Oe[n>>2]=l.getSeconds(),Oe[n+4>>2]=l.getMinutes(),Oe[n+8>>2]=l.getHours(),Oe[n+12>>2]=l.getDate(),Oe[n+16>>2]=l.getMonth(),Oe[n+20>>2]=l.getFullYear()-1900,Oe[n+24>>2]=l.getDay();var i=ir(l)|0;Oe[n+28>>2]=i,Oe[n+36>>2]=-(l.getTimezoneOffset()*60);var t=new Date(l.getFullYear(),0,1),r=new Date(l.getFullYear(),6,1).getTimezoneOffset(),s=t.getTimezoneOffset(),_=(r!=s&&l.getTimezoneOffset()==Math.min(s,r))|0;Oe[n+32>>2]=_}function or(e,n,l,i,t,r,s){t=bt(t);try{var _=ve.getStreamFromFD(i),c=a.mmap(_,e,t,n,l),b=c.ptr;return Oe[r>>2]=c.allocated,Fe[s>>2]=b,0}catch(M){if(typeof a>"u"||M.name!=="ErrnoError")throw M;return-M.errno}}function lr(e,n,l,i,t,r){r=bt(r);try{var s=ve.getStreamFromFD(t);l&2&&ve.doMsync(e,s,n,i,r)}catch(_){if(typeof a>"u"||_.name!=="ErrnoError")throw _;return-_.errno}}var ar=(e,n,l,i)=>{var t=new Date().getFullYear(),r=new Date(t,0,1),s=new Date(t,6,1),_=r.getTimezoneOffset(),c=s.getTimezoneOffset(),b=Math.max(_,c);Fe[e>>2]=b*60,Oe[n>>2]=+(_!=c);var M=w=>{var x=w>=0?"-":"+",L=Math.abs(w);return`UTC${x}${String(Math.floor(L/60)).padStart(2,"0")}${String(L%60).padStart(2,"0")}`},I=M(_),S=M(c);c<_?(lt(I,l,17),lt(S,i,17)):(lt(I,i,17),lt(S,l,17))},$t=()=>performance.now(),Kt=()=>Date.now(),cr=e=>e>=0&&e<=3;function ur(e,n,l){if(!cr(e))return 28;var i;e===0?i=Kt():i=$t();var t=Math.round(i*1e3*1e3);return Ve[l>>3]=BigInt(t),0}var Jt=()=>2147483648,_r=()=>Jt(),fr=e=>{var n=(e-nt.buffer.byteLength+65535)/65536|0;try{return nt.grow(n),Ct(),1}catch{}},dr=e=>{var n=it.length;e>>>=0;var l=Jt();if(e>l)return!1;for(var i=1;i<=4;i*=2){var t=n*(1+.2/i);if(t=Math.min(t,e+100663296),fr(Math.min(l,Wt(Math.max(e,t),65536))))return!0}return!1},Pt={},pr=()=>ge||"./this.program",yt=()=>{if(!yt.strings){var e={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:pr()};for(var n in Pt)Pt[n]===void 0?delete e[n]:e[n]=Pt[n];var l=[];for(var n in e)l.push(`${n}=${e[n]}`);yt.strings=l}return yt.strings},hr=(e,n)=>{var l=0,i=0;for(var t of yt()){var r=n+l;Fe[e+i>>2]=r,l+=lt(t,r,1/0)+1,i+=4}return 0},mr=(e,n)=>{var l=yt();Fe[e>>2]=l.length;var i=0;for(var t of l)i+=vt(t)+1;return Fe[n>>2]=i,0};function gr(e){try{var n=ve.getStreamFromFD(e);return a.close(n),0}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return l.errno}}function br(e,n){try{var l=0,i=0,t=0,r=ve.getStreamFromFD(e),s=r.tty?2:a.isDir(r.mode)?3:a.isLink(r.mode)?7:4;return Je[n]=s,ht[n+2>>1]=t,Ve[n+8>>3]=BigInt(l),Ve[n+16>>3]=BigInt(i),0}catch(_){if(typeof a>"u"||_.name!=="ErrnoError")throw _;return _.errno}}var yr=(e,n,l,i)=>{for(var t=0,r=0;r>2],_=Fe[n+4>>2];n+=8;var c=a.read(e,Je,s,_,i);if(c<0)return-1;if(t+=c,c<_)break}return t};function qr(e,n,l,i){try{var t=yr(ve.getStreamFromFD(e),n,l);return Fe[i>>2]=t,0}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return r.errno}}function vr(e,n,l,i){n=bt(n);try{if(isNaN(n))return 61;var t=ve.getStreamFromFD(e);return a.llseek(t,n,l),Ve[i>>3]=BigInt(t.position),t.getdents&&n===0&&l===0&&(t.getdents=null),0}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return r.errno}}function Sr(e){try{var n=ve.getStreamFromFD(e);return n.stream_ops?.fsync?.(n)}catch(l){if(typeof a>"u"||l.name!=="ErrnoError")throw l;return l.errno}}var wr=(e,n,l,i)=>{for(var t=0,r=0;r>2],_=Fe[n+4>>2];n+=8;var c=a.write(e,Je,s,_,i);if(c<0)return-1;if(t+=c,c<_)break}return t};function Er(e,n,l,i){try{var t=wr(ve.getStreamFromFD(e),n,l);return Fe[i>>2]=t,0}catch(r){if(typeof a>"u"||r.name!=="ErrnoError")throw r;return r.errno}}if(a.createPreloadedFile=Ln,a.preloadFile=Ht,a.staticInit(),_n(),f.noExitRuntime&&f.noExitRuntime,f.preloadPlugins&&(Vt=f.preloadPlugins),f.print&&(de=f.print),f.printErr&&(Le=f.printErr),f.wasmBinary&&(Ie=f.wasmBinary),f.arguments&&f.arguments,f.thisProgram&&(ge=f.thisProgram),f.preInit)for(typeof f.preInit=="function"&&(f.preInit=[f.preInit]);f.preInit.length>0;)f.preInit.shift()();f.wasmMemory=nt;var Xt;function Ar(e){f._sqlite3_status64=e.sqlite3_status64,f._sqlite3_status=e.sqlite3_status,f._sqlite3_db_status64=e.sqlite3_db_status64,f._sqlite3_msize=e.sqlite3_msize,f._sqlite3_db_status=e.sqlite3_db_status,f._sqlite3_vfs_find=e.sqlite3_vfs_find,f._sqlite3_initialize=e.sqlite3_initialize,f._sqlite3_malloc=e.sqlite3_malloc,f._sqlite3_free=e.sqlite3_free,f._sqlite3_vfs_register=e.sqlite3_vfs_register,f._sqlite3_vfs_unregister=e.sqlite3_vfs_unregister,f._sqlite3_malloc64=e.sqlite3_malloc64,f._sqlite3_realloc=e.sqlite3_realloc,f._sqlite3_realloc64=e.sqlite3_realloc64,f._sqlite3_value_text=e.sqlite3_value_text,f._sqlite3_randomness=e.sqlite3_randomness,f._sqlite3_stricmp=e.sqlite3_stricmp,f._sqlite3_strnicmp=e.sqlite3_strnicmp,f._sqlite3_uri_parameter=e.sqlite3_uri_parameter,f._sqlite3_uri_boolean=e.sqlite3_uri_boolean,f._sqlite3_serialize=e.sqlite3_serialize,f._sqlite3_prepare_v2=e.sqlite3_prepare_v2,f._sqlite3_step=e.sqlite3_step,f._sqlite3_column_int64=e.sqlite3_column_int64,f._sqlite3_reset=e.sqlite3_reset,f._sqlite3_exec=e.sqlite3_exec,f._sqlite3_column_int=e.sqlite3_column_int,f._sqlite3_finalize=e.sqlite3_finalize,f._sqlite3_file_control=e.sqlite3_file_control,f._sqlite3_column_name=e.sqlite3_column_name,f._sqlite3_column_text=e.sqlite3_column_text,f._sqlite3_column_type=e.sqlite3_column_type,f._sqlite3_errmsg=e.sqlite3_errmsg,f._sqlite3_deserialize=e.sqlite3_deserialize,f._sqlite3_clear_bindings=e.sqlite3_clear_bindings,f._sqlite3_value_blob=e.sqlite3_value_blob,f._sqlite3_value_bytes=e.sqlite3_value_bytes,f._sqlite3_value_double=e.sqlite3_value_double,f._sqlite3_value_int=e.sqlite3_value_int,f._sqlite3_value_int64=e.sqlite3_value_int64,f._sqlite3_value_subtype=e.sqlite3_value_subtype,f._sqlite3_value_pointer=e.sqlite3_value_pointer,f._sqlite3_value_type=e.sqlite3_value_type,f._sqlite3_value_nochange=e.sqlite3_value_nochange,f._sqlite3_value_frombind=e.sqlite3_value_frombind,f._sqlite3_value_dup=e.sqlite3_value_dup,f._sqlite3_value_free=e.sqlite3_value_free,f._sqlite3_result_blob=e.sqlite3_result_blob,f._sqlite3_result_error_toobig=e.sqlite3_result_error_toobig,f._sqlite3_result_error_nomem=e.sqlite3_result_error_nomem,f._sqlite3_result_double=e.sqlite3_result_double,f._sqlite3_result_error=e.sqlite3_result_error,f._sqlite3_result_int=e.sqlite3_result_int,f._sqlite3_result_int64=e.sqlite3_result_int64,f._sqlite3_result_null=e.sqlite3_result_null,f._sqlite3_result_pointer=e.sqlite3_result_pointer,f._sqlite3_result_subtype=e.sqlite3_result_subtype,f._sqlite3_result_text=e.sqlite3_result_text,f._sqlite3_result_zeroblob=e.sqlite3_result_zeroblob,f._sqlite3_result_zeroblob64=e.sqlite3_result_zeroblob64,f._sqlite3_result_error_code=e.sqlite3_result_error_code,f._sqlite3_user_data=e.sqlite3_user_data,f._sqlite3_context_db_handle=e.sqlite3_context_db_handle,f._sqlite3_vtab_nochange=e.sqlite3_vtab_nochange,f._sqlite3_vtab_in_first=e.sqlite3_vtab_in_first,f._sqlite3_vtab_in_next=e.sqlite3_vtab_in_next,f._sqlite3_aggregate_context=e.sqlite3_aggregate_context,f._sqlite3_get_auxdata=e.sqlite3_get_auxdata,f._sqlite3_set_auxdata=e.sqlite3_set_auxdata,f._sqlite3_column_count=e.sqlite3_column_count,f._sqlite3_data_count=e.sqlite3_data_count,f._sqlite3_column_blob=e.sqlite3_column_blob,f._sqlite3_column_bytes=e.sqlite3_column_bytes,f._sqlite3_column_double=e.sqlite3_column_double,f._sqlite3_column_value=e.sqlite3_column_value,f._sqlite3_column_decltype=e.sqlite3_column_decltype,f._sqlite3_column_database_name=e.sqlite3_column_database_name,f._sqlite3_column_table_name=e.sqlite3_column_table_name,f._sqlite3_column_origin_name=e.sqlite3_column_origin_name,f._sqlite3_bind_blob=e.sqlite3_bind_blob,f._sqlite3_bind_double=e.sqlite3_bind_double,f._sqlite3_bind_int=e.sqlite3_bind_int,f._sqlite3_bind_int64=e.sqlite3_bind_int64,f._sqlite3_bind_null=e.sqlite3_bind_null,f._sqlite3_bind_pointer=e.sqlite3_bind_pointer,f._sqlite3_bind_text=e.sqlite3_bind_text,f._sqlite3_bind_zeroblob=e.sqlite3_bind_zeroblob,f._sqlite3_bind_parameter_count=e.sqlite3_bind_parameter_count,f._sqlite3_bind_parameter_name=e.sqlite3_bind_parameter_name,f._sqlite3_bind_parameter_index=e.sqlite3_bind_parameter_index,f._sqlite3_db_handle=e.sqlite3_db_handle,f._sqlite3_stmt_readonly=e.sqlite3_stmt_readonly,f._sqlite3_stmt_isexplain=e.sqlite3_stmt_isexplain,f._sqlite3_stmt_explain=e.sqlite3_stmt_explain,f._sqlite3_stmt_busy=e.sqlite3_stmt_busy,f._sqlite3_next_stmt=e.sqlite3_next_stmt,f._sqlite3_stmt_status=e.sqlite3_stmt_status,f._sqlite3_sql=e.sqlite3_sql,f._sqlite3_expanded_sql=e.sqlite3_expanded_sql,f._sqlite3_preupdate_old=e.sqlite3_preupdate_old,f._sqlite3_preupdate_count=e.sqlite3_preupdate_count,f._sqlite3_preupdate_depth=e.sqlite3_preupdate_depth,f._sqlite3_preupdate_blobwrite=e.sqlite3_preupdate_blobwrite,f._sqlite3_preupdate_new=e.sqlite3_preupdate_new,f._sqlite3_value_numeric_type=e.sqlite3_value_numeric_type,f._sqlite3_set_authorizer=e.sqlite3_set_authorizer,f._sqlite3_strglob=e.sqlite3_strglob,f._sqlite3_strlike=e.sqlite3_strlike,f._sqlite3_auto_extension=e.sqlite3_auto_extension,f._sqlite3_cancel_auto_extension=e.sqlite3_cancel_auto_extension,f._sqlite3_reset_auto_extension=e.sqlite3_reset_auto_extension,f._sqlite3_prepare_v3=e.sqlite3_prepare_v3,f._sqlite3_create_module=e.sqlite3_create_module,f._sqlite3_create_module_v2=e.sqlite3_create_module_v2,f._sqlite3_drop_modules=e.sqlite3_drop_modules,f._sqlite3_declare_vtab=e.sqlite3_declare_vtab,f._sqlite3_vtab_on_conflict=e.sqlite3_vtab_on_conflict,f._sqlite3_vtab_collation=e.sqlite3_vtab_collation,f._sqlite3_vtab_in=e.sqlite3_vtab_in,f._sqlite3_vtab_rhs_value=e.sqlite3_vtab_rhs_value,f._sqlite3_vtab_distinct=e.sqlite3_vtab_distinct,f._sqlite3_keyword_name=e.sqlite3_keyword_name,f._sqlite3_keyword_count=e.sqlite3_keyword_count,f._sqlite3_keyword_check=e.sqlite3_keyword_check,f._sqlite3_complete=e.sqlite3_complete,f._sqlite3_libversion=e.sqlite3_libversion,f._sqlite3_libversion_number=e.sqlite3_libversion_number,f._sqlite3_shutdown=e.sqlite3_shutdown,f._sqlite3_last_insert_rowid=e.sqlite3_last_insert_rowid,f._sqlite3_set_last_insert_rowid=e.sqlite3_set_last_insert_rowid,f._sqlite3_changes64=e.sqlite3_changes64,f._sqlite3_changes=e.sqlite3_changes,f._sqlite3_total_changes64=e.sqlite3_total_changes64,f._sqlite3_total_changes=e.sqlite3_total_changes,f._sqlite3_txn_state=e.sqlite3_txn_state,f._sqlite3_close_v2=e.sqlite3_close_v2,f._sqlite3_busy_handler=e.sqlite3_busy_handler,f._sqlite3_progress_handler=e.sqlite3_progress_handler,f._sqlite3_busy_timeout=e.sqlite3_busy_timeout,f._sqlite3_interrupt=e.sqlite3_interrupt,f._sqlite3_is_interrupted=e.sqlite3_is_interrupted,f._sqlite3_create_function=e.sqlite3_create_function,f._sqlite3_create_function_v2=e.sqlite3_create_function_v2,f._sqlite3_create_window_function=e.sqlite3_create_window_function,f._sqlite3_overload_function=e.sqlite3_overload_function,f._sqlite3_trace_v2=e.sqlite3_trace_v2,f._sqlite3_commit_hook=e.sqlite3_commit_hook,f._sqlite3_update_hook=e.sqlite3_update_hook,f._sqlite3_rollback_hook=e.sqlite3_rollback_hook,f._sqlite3_preupdate_hook=e.sqlite3_preupdate_hook,f._sqlite3_set_errmsg=e.sqlite3_set_errmsg,f._sqlite3_error_offset=e.sqlite3_error_offset,f._sqlite3_errcode=e.sqlite3_errcode,f._sqlite3_extended_errcode=e.sqlite3_extended_errcode,f._sqlite3_errstr=e.sqlite3_errstr,f._sqlite3_limit=e.sqlite3_limit,f._sqlite3_open=e.sqlite3_open,f._sqlite3_open_v2=e.sqlite3_open_v2,f._sqlite3_create_collation=e.sqlite3_create_collation,f._sqlite3_create_collation_v2=e.sqlite3_create_collation_v2,f._sqlite3_collation_needed=e.sqlite3_collation_needed,f._sqlite3_get_autocommit=e.sqlite3_get_autocommit,f._sqlite3_table_column_metadata=e.sqlite3_table_column_metadata,f._sqlite3_extended_result_codes=e.sqlite3_extended_result_codes,f._sqlite3_uri_key=e.sqlite3_uri_key,f._sqlite3_uri_int64=e.sqlite3_uri_int64,f._sqlite3_db_name=e.sqlite3_db_name,f._sqlite3_db_filename=e.sqlite3_db_filename,f._sqlite3_db_readonly=e.sqlite3_db_readonly,f._sqlite3_compileoption_used=e.sqlite3_compileoption_used,f._sqlite3_compileoption_get=e.sqlite3_compileoption_get,f._sqlite3session_diff=e.sqlite3session_diff,f._sqlite3session_attach=e.sqlite3session_attach,f._sqlite3session_create=e.sqlite3session_create,f._sqlite3session_delete=e.sqlite3session_delete,f._sqlite3session_table_filter=e.sqlite3session_table_filter,f._sqlite3session_changeset=e.sqlite3session_changeset,f._sqlite3session_changeset_strm=e.sqlite3session_changeset_strm,f._sqlite3session_patchset_strm=e.sqlite3session_patchset_strm,f._sqlite3session_patchset=e.sqlite3session_patchset,f._sqlite3session_enable=e.sqlite3session_enable,f._sqlite3session_indirect=e.sqlite3session_indirect,f._sqlite3session_isempty=e.sqlite3session_isempty,f._sqlite3session_memory_used=e.sqlite3session_memory_used,f._sqlite3session_object_config=e.sqlite3session_object_config,f._sqlite3session_changeset_size=e.sqlite3session_changeset_size,f._sqlite3changeset_start=e.sqlite3changeset_start,f._sqlite3changeset_start_v2=e.sqlite3changeset_start_v2,f._sqlite3changeset_start_strm=e.sqlite3changeset_start_strm,f._sqlite3changeset_start_v2_strm=e.sqlite3changeset_start_v2_strm,f._sqlite3changeset_next=e.sqlite3changeset_next,f._sqlite3changeset_op=e.sqlite3changeset_op,f._sqlite3changeset_pk=e.sqlite3changeset_pk,f._sqlite3changeset_old=e.sqlite3changeset_old,f._sqlite3changeset_new=e.sqlite3changeset_new,f._sqlite3changeset_conflict=e.sqlite3changeset_conflict,f._sqlite3changeset_fk_conflicts=e.sqlite3changeset_fk_conflicts,f._sqlite3changeset_finalize=e.sqlite3changeset_finalize,f._sqlite3changeset_invert=e.sqlite3changeset_invert,f._sqlite3changeset_invert_strm=e.sqlite3changeset_invert_strm,f._sqlite3changeset_apply_v2=e.sqlite3changeset_apply_v2,f._sqlite3changeset_apply_v3=e.sqlite3changeset_apply_v3,f._sqlite3changeset_apply=e.sqlite3changeset_apply,f._sqlite3changeset_apply_v3_strm=e.sqlite3changeset_apply_v3_strm,f._sqlite3changeset_apply_v2_strm=e.sqlite3changeset_apply_v2_strm,f._sqlite3changeset_apply_strm=e.sqlite3changeset_apply_strm,f._sqlite3changegroup_new=e.sqlite3changegroup_new,f._sqlite3changegroup_add=e.sqlite3changegroup_add,f._sqlite3changegroup_output=e.sqlite3changegroup_output,f._sqlite3changegroup_add_strm=e.sqlite3changegroup_add_strm,f._sqlite3changegroup_output_strm=e.sqlite3changegroup_output_strm,f._sqlite3changegroup_delete=e.sqlite3changegroup_delete,f._sqlite3changeset_concat=e.sqlite3changeset_concat,f._sqlite3changeset_concat_strm=e.sqlite3changeset_concat_strm,f._sqlite3session_config=e.sqlite3session_config,f._sqlite3_sourceid=e.sqlite3_sourceid,f._sqlite3__wasm_pstack_ptr=e.sqlite3__wasm_pstack_ptr,f._sqlite3__wasm_pstack_restore=e.sqlite3__wasm_pstack_restore,f._sqlite3__wasm_pstack_alloc=e.sqlite3__wasm_pstack_alloc,f._sqlite3__wasm_pstack_remaining=e.sqlite3__wasm_pstack_remaining,f._sqlite3__wasm_pstack_quota=e.sqlite3__wasm_pstack_quota,f._sqlite3__wasm_test_struct=e.sqlite3__wasm_test_struct,f._sqlite3__wasm_enum_json=e.sqlite3__wasm_enum_json,f._sqlite3__wasm_vfs_unlink=e.sqlite3__wasm_vfs_unlink,f._sqlite3__wasm_db_vfs=e.sqlite3__wasm_db_vfs,f._sqlite3__wasm_db_reset=e.sqlite3__wasm_db_reset,f._sqlite3__wasm_db_export_chunked=e.sqlite3__wasm_db_export_chunked,f._sqlite3__wasm_db_serialize=e.sqlite3__wasm_db_serialize,f._sqlite3__wasm_vfs_create_file=e.sqlite3__wasm_vfs_create_file,f._sqlite3__wasm_posix_create_file=e.sqlite3__wasm_posix_create_file,f._sqlite3__wasm_kvvfsMakeKey=e.sqlite3__wasm_kvvfsMakeKey,f._sqlite3__wasm_kvvfs_methods=e.sqlite3__wasm_kvvfs_methods,f._sqlite3__wasm_vtab_config=e.sqlite3__wasm_vtab_config,f._sqlite3__wasm_db_config_ip=e.sqlite3__wasm_db_config_ip,f._sqlite3__wasm_db_config_pii=e.sqlite3__wasm_db_config_pii,f._sqlite3__wasm_db_config_s=e.sqlite3__wasm_db_config_s,f._sqlite3__wasm_config_i=e.sqlite3__wasm_config_i,f._sqlite3__wasm_config_ii=e.sqlite3__wasm_config_ii,f._sqlite3__wasm_config_j=e.sqlite3__wasm_config_j,f._sqlite3__wasm_qfmt_token=e.sqlite3__wasm_qfmt_token,f._sqlite3__wasm_kvvfs_decode=e.sqlite3__wasm_kvvfs_decode,f._sqlite3__wasm_kvvfs_encode=e.sqlite3__wasm_kvvfs_encode,f._sqlite3__wasm_init_wasmfs=e.sqlite3__wasm_init_wasmfs,f._sqlite3__wasm_test_intptr=e.sqlite3__wasm_test_intptr,f._sqlite3__wasm_test_voidptr=e.sqlite3__wasm_test_voidptr,f._sqlite3__wasm_test_int64_max=e.sqlite3__wasm_test_int64_max,f._sqlite3__wasm_test_int64_min=e.sqlite3__wasm_test_int64_min,f._sqlite3__wasm_test_int64_times2=e.sqlite3__wasm_test_int64_times2,f._sqlite3__wasm_test_int64_minmax=e.sqlite3__wasm_test_int64_minmax,f._sqlite3__wasm_test_int64ptr=e.sqlite3__wasm_test_int64ptr,f._sqlite3__wasm_test_stack_overflow=e.sqlite3__wasm_test_stack_overflow,f._sqlite3__wasm_test_str_hello=e.sqlite3__wasm_test_str_hello,f._sqlite3__wasm_SQLTester_strglob=e.sqlite3__wasm_SQLTester_strglob,f._malloc=e.malloc,f._free=e.free,f._realloc=e.realloc,Xt=e.emscripten_builtin_memalign,e._emscripten_stack_restore,e._emscripten_stack_alloc,e.emscripten_stack_get_current,e.__indirect_function_table}var Yt={__syscall_chmod:Nn,__syscall_faccessat:Rn,__syscall_fchmod:Dn,__syscall_fchown32:jn,__syscall_fcntl64:Mn,__syscall_fstat64:zn,__syscall_ftruncate64:Qn,__syscall_getcwd:Un,__syscall_ioctl:Vn,__syscall_lstat64:Hn,__syscall_mkdirat:Gn,__syscall_newfstatat:$n,__syscall_openat:Kn,__syscall_readlinkat:Jn,__syscall_rmdir:Xn,__syscall_stat64:Yn,__syscall_unlinkat:Zn,__syscall_utimensat:er,_localtime_js:sr,_mmap_js:or,_munmap_js:lr,_tzset_js:ar,clock_time_get:ur,emscripten_date_now:Kt,emscripten_get_heap_max:_r,emscripten_get_now:$t,emscripten_resize_heap:dr,environ_get:hr,environ_sizes_get:mr,fd_close:gr,fd_fdstat_get:br,fd_read:qr,fd_seek:vr,fd_sync:Sr,fd_write:Er,memory:nt};function Ft(){if(ot>0){gt=Ft;return}if(fn(),ot>0){gt=Ft;return}function e(){f.calledRun=!0,!Ee&&(dn(),Ce?.(f),f.onRuntimeInitialized?.(),pn())}f.setStatus?(f.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>f.setStatus(""),1),e()},1)):e()}var dt=await vn();return Ft(),f.runSQLite3PostLoadInit=async function(e,n,l){delete n.runSQLite3PostLoadInit,globalThis.sqlite3ApiBootstrap=async function i(t=globalThis.sqlite3ApiConfig||i.defaultConfig){if(i.sqlite3)return(i.sqlite3.config||console).warn("sqlite3ApiBootstrap() called multiple times.","Config and external initializers are ignored on calls after the first."),i.sqlite3;const r=(...d)=>Object.assign(Object.create(null),...d),s=r({exports:void 0,memory:void 0,bigIntEnabled:!!globalThis.BigInt64Array,debug:console.debug.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),log:console.log.bind(console),wasmfsOpfsDir:"/opfs",useStdAlloc:!1},t);Object.assign(s,{allocExportName:s.useStdAlloc?"malloc":"sqlite3_malloc",deallocExportName:s.useStdAlloc?"free":"sqlite3_free",reallocExportName:s.useStdAlloc?"realloc":"sqlite3_realloc"}),["exports","memory","functionTable","wasmfsOpfsDir"].forEach(d=>{typeof s[d]=="function"&&(s[d]=s[d]())});const _=r(),c=r(),b=d=>_.sqlite3_js_rc_str&&_.sqlite3_js_rc_str(d)||"Unknown result code #"+d,M=d=>typeof d=="number"&&d===(d|0)&&d<=2147483647&&d>=-2147483648;class I extends Error{constructor(...y){let F;if(y.length)if(M(y[0]))if(F=y[0],y.length===1)super(b(y[0]));else{const W=b(F);typeof y[1]=="object"?super(W,y[1]):(y[0]=W+":",super(y.join(" ")))}else y.length===2&&typeof y[1]=="object"?super(...y):super(y.join(" "));this.resultCode=F||_.SQLITE_ERROR,this.name="SQLite3Error"}}I.toss=(...d)=>{throw new I(...d)};const S=I.toss;s.wasmfsOpfsDir&&!/^\/[^/]+$/.test(s.wasmfsOpfsDir)&&S("config.wasmfsOpfsDir must be falsy or in the form '/dir-name'.");const w=function d(y){return d._max||(d._max=BigInt("0x7fffffffffffffff"),d._min=~d._max),y>=d._min&&y<=d._max},x=d=>d>=-2147483647n-1n&&d<=2147483647n,L=function d(y){return d._min||(d._min=Number.MIN_SAFE_INTEGER,d._max=Number.MAX_SAFE_INTEGER),y>=d._min&&y<=d._max},H=d=>d&&d.constructor&&M(d.constructor.BYTES_PER_ELEMENT)?d:!1,g=d=>d&&(d instanceof Uint8Array||d instanceof Int8Array||d instanceof ArrayBuffer),h=d=>d&&(d instanceof Uint8Array||d instanceof Int8Array||d instanceof ArrayBuffer),D=d=>g(d)||S("Value is not of a supported TypedArray type."),Q=function(d){return h(d)?c.typedArrayToString(d instanceof ArrayBuffer?new Uint8Array(d):d,0,d.length):Array.isArray(d)?d.join(""):(c.isPtr(d)&&(d=c.cstrToJs(d)),d)};class A extends Error{constructor(...y){y.length===2&&typeof y[1]=="object"?super(...y):y.length?super(y.join(" ")):super("Allocation failed."),this.resultCode=_.SQLITE_NOMEM,this.name="WasmAllocError"}}A.toss=(...d)=>{throw new A(...d)},Object.assign(_,{sqlite3_bind_blob:void 0,sqlite3_bind_text:void 0,sqlite3_create_function_v2:(d,y,F,W,P,X,ee,Z,te)=>{},sqlite3_create_function:(d,y,F,W,P,X,ee,Z)=>{},sqlite3_create_window_function:(d,y,F,W,P,X,ee,Z,te,E)=>{},sqlite3_prepare_v3:(d,y,F,W,P,X)=>{},sqlite3_prepare_v2:(d,y,F,W,P)=>{},sqlite3_exec:(d,y,F,W,P)=>{},sqlite3_randomness:(d,y)=>{}});const N={affirmBindableTypedArray:D,flexibleString:Q,bigIntFits32:x,bigIntFits64:w,bigIntFitsDouble:L,isBindableTypedArray:g,isInt32:M,isSQLableTypedArray:h,isTypedArray:H,isUIThread:()=>globalThis.window===globalThis&&!!globalThis.document,toss:function(...d){throw new Error(d.join(" "))},toss3:S,typedArrayPart:c.typedArrayPart,nu:r,assert:function(d,y){d||N.toss("Assertion failed:",y)},affirmDbHeader:function(d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));const y="SQLite format 3";15>d.byteLength&&S("Input does not contain an SQLite3 database header.");for(let F=0;F<15;++F)y.charCodeAt(F)!==d[F]&&S("Input does not contain an SQLite3 database header.")},affirmIsDb:function(d){d instanceof ArrayBuffer&&(d=new Uint8Array(d));const y=d.byteLength;(y<512||y%512!==0)&&S("Byte array size",y,"is invalid for an SQLite3 db."),N.affirmDbHeader(d)}};Object.assign(c,{exports:s.exports||S("Missing API config.exports (WASM module exports)."),memory:s.memory||s.exports.memory||S("API config object requires a WebAssembly.Memory object","in either config.exports.memory (exported)","or config.memory (imported)."),pointerSize:typeof s.exports.sqlite3_libversion()=="number"?4:8,bigIntEnabled:!!s.bigIntEnabled,functionTable:s.functionTable,alloc:void 0,realloc:void 0,dealloc:void 0}),c.allocFromTypedArray=function(d){d instanceof ArrayBuffer&&(d=new Uint8Array(d)),D(d);const y=c.alloc(d.byteLength||1);return c.heapForSize(d.constructor).set(d.byteLength?d:[0],Number(y)),y};{const d=s.allocExportName,y=s.deallocExportName,F=s.reallocExportName;for(const W of[d,y,F])c.exports[W]instanceof Function||S("Missing required exports[",W,"] function.");c.alloc=function W(P){return W.impl(P)||A.toss("Failed to allocate",P," bytes.")},c.alloc.impl=c.exports[d],c.realloc=function W(P,X){const ee=W.impl(c.ptr.coerce(P),X);return X?ee||A.toss("Failed to reallocate",X," bytes."):c.ptr.null},c.realloc.impl=c.exports[F],c.dealloc=function W(P){W.impl(c.ptr.coerce(P))},c.dealloc.impl=c.exports[y]}c.compileOptionUsed=function d(y){if(arguments.length){if(Array.isArray(y)){const F=r();return y.forEach(W=>{F[W]=_.sqlite3_compileoption_used(W)}),F}else if(typeof y=="object")return Object.keys(y).forEach(F=>{y[F]=_.sqlite3_compileoption_used(F)}),y}else{if(d._result)return d._result;d._opt||(d._rx=/^([^=]+)=(.+)/,d._rxInt=/^-?\d+$/,d._opt=function(ee,Z){const te=d._rx.exec(ee);Z[0]=te?te[1]:ee,Z[1]=te?d._rxInt.test(te[2])?+te[2]:te[2]:!0});const F=r(),W=[0,0];let P=0,X;for(;X=_.sqlite3_compileoption_get(P++);)d._opt(X,W),F[W[0]]=W[1];return d._result=F}return typeof y=="string"?!!_.sqlite3_compileoption_used(y):!1},c.pstack=r({restore:c.exports.sqlite3__wasm_pstack_restore,alloc:function(d){return typeof d=="string"&&!(d=c.sizeofIR(d))&&A.toss("Invalid value for pstack.alloc(",arguments[0],")"),c.exports.sqlite3__wasm_pstack_alloc(d)||A.toss("Could not allocate",d,"bytes from the pstack.")},allocChunks:function(d,y){typeof y=="string"&&!(y=c.sizeofIR(y))&&A.toss("Invalid size value for allocChunks(",arguments[1],")");const F=c.pstack.alloc(d*y),W=[F];let P=1,X=y;for(;Pd===1?c.pstack.alloc(y?8:c.ptr.size):c.pstack.allocChunks(d,y?8:c.ptr.size),call:function(d){const y=c.pstack.pointer;try{return d(J)}finally{c.pstack.restore(y)}}}),Object.defineProperties(c.pstack,{pointer:{configurable:!1,iterable:!0,writeable:!1,get:c.exports.sqlite3__wasm_pstack_ptr},quota:{configurable:!1,iterable:!0,writeable:!1,get:c.exports.sqlite3__wasm_pstack_quota},remaining:{configurable:!1,iterable:!0,writeable:!1,get:c.exports.sqlite3__wasm_pstack_remaining}}),_.sqlite3_randomness=(...d)=>{if(d.length===1&&N.isTypedArray(d[0])&&d[0].BYTES_PER_ELEMENT===1){const y=d[0];if(y.byteLength===0)return c.exports.sqlite3_randomness(0,c.ptr.null),y;const F=c.pstack.pointer;try{let W=y.byteLength,P=0;const X=c.exports.sqlite3_randomness,ee=c.heap8u(),Z=W<512?W:512,te=c.pstack.alloc(Z);do{const E=W>Z?Z:W;X(E,te),y.set(c.typedArrayPart(ee,te,c.ptr.add(te,E)),P),W-=E,P+=E}while(W>0)}catch(W){s.error("Highly unexpected (and ignored!) exception in sqlite3_randomness():",W)}finally{c.pstack.restore(F)}return y}c.exports.sqlite3_randomness(...d)},_.sqlite3_wasmfs_opfs_dir=(function(){if(this.dir!==void 0)return this.dir;const d=s.wasmfsOpfsDir;if(!d||!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!c.exports.sqlite3__wasm_init_wasmfs)return this.dir="";try{return d&&c.xCallWrapped("sqlite3__wasm_init_wasmfs","i32",["string"],d)===0?this.dir=d:this.dir=""}catch{return this.dir=""}}).bind(r()),_.sqlite3_wasmfs_filename_is_persistent=function(d){const y=_.sqlite3_wasmfs_opfs_dir();return y&&d?d.startsWith(y+"/"):!1},_.sqlite3_js_db_uses_vfs=function(d,y,F=0){try{const W=_.sqlite3_vfs_find(y);return W?d?W===_.sqlite3_js_db_vfs(d,F)?W:!1:W===_.sqlite3_vfs_find(0)?W:!1:!1}catch{return!1}},_.sqlite3_js_vfs_list=function(){const d=[];let y=_.sqlite3_vfs_find(c.ptr.null);for(;y;){const F=new _.sqlite3_vfs(y);d.push(c.cstrToJs(F.$zName)),y=F.$pNext,F.dispose()}return d},_.sqlite3_js_db_export=function(d,y=0){d=c.xWrap.testConvertArg("sqlite3*",d),d||S("Invalid sqlite3* argument."),c.bigIntEnabled||S("BigInt support is not enabled.");const F=c.scopedAllocPush();let W;try{const P=c.scopedAlloc(8+c.ptr.size),X=c.ptr.add(P,8),ee=y?c.isPtr(y)?y:c.scopedAllocCString(""+y):c.ptr.null;let Z=c.exports.sqlite3__wasm_db_serialize(d,ee,X,P,0);Z&&S("Database serialization failed with code",J.capi.sqlite3_js_rc_str(Z)),W=c.peekPtr(X);const te=c.peek(P,"i64");return Z=te?c.heap8u().slice(Number(W),Number(W)+Number(te)):new Uint8Array,Z}finally{W&&c.exports.sqlite3_free(W),c.scopedAllocPop(F)}},_.sqlite3_js_db_vfs=(d,y=c.ptr.null)=>N.sqlite3__wasm_db_vfs(d,y),_.sqlite3_js_aggregate_context=(d,y)=>_.sqlite3_aggregate_context(d,y)||(y?A.toss("Cannot allocate",y,"bytes for sqlite3_aggregate_context()"):0),_.sqlite3_js_posix_create_file=function(d,y,F){let W;y&&c.isPtr(y)?W=y:y instanceof ArrayBuffer||y instanceof Uint8Array?(W=c.allocFromTypedArray(y),(arguments.length<3||!N.isInt32(F)||F<0)&&(F=y.byteLength)):I.toss("Invalid 2nd argument for sqlite3_js_posix_create_file().");try{(!N.isInt32(F)||F<0)&&I.toss("Invalid 3rd argument for sqlite3_js_posix_create_file().");const P=N.sqlite3__wasm_posix_create_file(d,W,F);P&&I.toss("Creation of file failed with sqlite3 result code",_.sqlite3_js_rc_str(P))}finally{W&&W!==y&&c.dealloc(W)}},_.sqlite3_js_vfs_create_file=function(d,y,F,W){s.warn("sqlite3_js_vfs_create_file() is deprecated and","should be avoided because it can lead to C-level crashes.","See its documentation for alternatives.");let P;F?c.isPtr(F)?P=F:(F instanceof ArrayBuffer&&(F=new Uint8Array(F)),F instanceof Uint8Array?(P=c.allocFromTypedArray(F),(arguments.length<4||!N.isInt32(W)||W<0)&&(W=F.byteLength)):I.toss("Invalid 3rd argument type for sqlite3_js_vfs_create_file().")):P=0,(!N.isInt32(W)||W<0)&&(P&&P!==F&&c.dealloc(P),I.toss("Invalid 4th argument for sqlite3_js_vfs_create_file()."));try{const X=N.sqlite3__wasm_vfs_create_file(d,y,P,W);X&&I.toss("Creation of file failed with sqlite3 result code",_.sqlite3_js_rc_str(X))}finally{P&&P!==F&&c.dealloc(P)}},_.sqlite3_js_sql_to_string=d=>{if(typeof d=="string")return d;const y=Q(v);return y===v?void 0:y},_.sqlite3_db_config=(function(d,y,...F){switch(y){case _.SQLITE_DBCONFIG_ENABLE_FKEY:case _.SQLITE_DBCONFIG_ENABLE_TRIGGER:case _.SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER:case _.SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION:case _.SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE:case _.SQLITE_DBCONFIG_ENABLE_QPSG:case _.SQLITE_DBCONFIG_TRIGGER_EQP:case _.SQLITE_DBCONFIG_RESET_DATABASE:case _.SQLITE_DBCONFIG_DEFENSIVE:case _.SQLITE_DBCONFIG_WRITABLE_SCHEMA:case _.SQLITE_DBCONFIG_LEGACY_ALTER_TABLE:case _.SQLITE_DBCONFIG_DQS_DML:case _.SQLITE_DBCONFIG_DQS_DDL:case _.SQLITE_DBCONFIG_ENABLE_VIEW:case _.SQLITE_DBCONFIG_LEGACY_FILE_FORMAT:case _.SQLITE_DBCONFIG_TRUSTED_SCHEMA:case _.SQLITE_DBCONFIG_STMT_SCANSTATUS:case _.SQLITE_DBCONFIG_REVERSE_SCANORDER:case _.SQLITE_DBCONFIG_ENABLE_ATTACH_CREATE:case _.SQLITE_DBCONFIG_ENABLE_ATTACH_WRITE:case _.SQLITE_DBCONFIG_ENABLE_COMMENTS:case _.SQLITE_DBCONFIG_FP_DIGITS:return this.ip||(this.ip=c.xWrap("sqlite3__wasm_db_config_ip","int",["sqlite3*","int","int","*"])),this.ip(d,y,F[0],F[1]||0);case _.SQLITE_DBCONFIG_LOOKASIDE:return this.pii||(this.pii=c.xWrap("sqlite3__wasm_db_config_pii","int",["sqlite3*","int","*","int","int"])),this.pii(d,y,F[0],F[1],F[2]);case _.SQLITE_DBCONFIG_MAINDBNAME:return this.s||(this.s=c.xWrap("sqlite3__wasm_db_config_s","int",["sqlite3*","int","string:static"])),this.s(d,y,F[0]);default:return _.SQLITE_MISUSE}}).bind(r()),_.sqlite3_value_to_js=function(d,y=!0){let F;const W=_.sqlite3_value_type(d);switch(W){case _.SQLITE_INTEGER:c.bigIntEnabled?(F=_.sqlite3_value_int64(d),N.bigIntFitsDouble(F)&&(F=Number(F))):F=_.sqlite3_value_double(d);break;case _.SQLITE_FLOAT:F=_.sqlite3_value_double(d);break;case _.SQLITE_TEXT:F=_.sqlite3_value_text(d);break;case _.SQLITE_BLOB:{const P=_.sqlite3_value_bytes(d),X=_.sqlite3_value_blob(d);P&&!X&&J.WasmAllocError.toss("Cannot allocate memory for blob argument of",P,"byte(s)"),F=P?c.heap8u().slice(Number(X),Number(X)+Number(P)):null;break}case _.SQLITE_NULL:F=null;break;default:y&&S(_.SQLITE_MISMATCH,"Unhandled sqlite3_value_type():",W),F=void 0}return F},_.sqlite3_values_to_js=function(d,y,F=!0){let W;const P=[];for(W=0;Wd(y,F,"sqlite3_preupdate_new"),_.sqlite3_preupdate_old_js=(y,F)=>d(y,F,"sqlite3_preupdate_old"),_.sqlite3changeset_new_js=(y,F)=>d(y,F,"sqlite3changeset_new"),_.sqlite3changeset_old_js=(y,F)=>d(y,F,"sqlite3changeset_old")}_.sqlite3_js_retry_busy=function(d,y,F){for(let W=1;W<=d;++W)try{F&&W>1&&F(W);const P=y();if(_.SQLITE_BUSY===P){if(W===d)throw new I(P,["sqlite3_js_retry_busy() max retry attempts (",d,") reached."].join(""));continue}return P}catch(P){if(W(J.__isUnderTest||(delete J.util,delete J.StructBinder,delete J.opfs),J),W=X=>{throw s.error("an async sqlite3 initializer failed:",X),X};if(!y||!y.length)return d.isReady=F().catch(W);y=y.map(X=>X instanceof Function?async ee=>X(J):X),y.push(F);let P=Promise.resolve(J);for(;y.length;)P=P.then(y.shift());return d.isReady=P.catch(W)}).bind(i),scriptInfo:void 0};typeof l<"u"&&(J.__isUnderTest=!!l);try{i.initializers.forEach(d=>{d(J)})}catch(d){throw console.error("sqlite3 bootstrap initializer threw:",d),d}if(delete i.initializers,i.sqlite3=J,typeof e<"u"&&(e.debugModule("sqlite3ApiBootstrap() complete",J),J.scriptInfo=e),J.__isUnderTest){typeof n<"u"&&(J.config.emscripten=n);const d=J.scriptInfo?.instantiateWasm;d&&(J.wasm.module=d.module,J.wasm.instance=d.instance,J.wasm.imports=d.imports)}return delete globalThis.sqlite3ApiConfig,delete globalThis.sqlite3ApiBootstrap,delete i.defaultConfig,J.asyncPostInit().then(d=>(typeof e<"u"&&e.debugModule("sqlite3.asyncPostInit() complete",d),delete d.asyncPostInit,delete d.scriptInfo,delete d.emscripten,d))},globalThis.sqlite3ApiBootstrap.initializers=[],globalThis.sqlite3ApiBootstrap.initializersAsync=[],globalThis.sqlite3ApiBootstrap.defaultConfig=Object.create(null),globalThis.sqlite3ApiBootstrap.sqlite3=void 0,globalThis.sqlite3ApiBootstrap.initializers.push(function(i){i.version={libVersion:"3.53.0",libVersionNumber:3053e3,sourceId:"2026-04-09 11:41:38 4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",downloadVersion:353e4,scm:{"sha3-256":"4525003a53a7fc63ca75c59b22c79608659ca12f0131f52c18637f829977f20b",branch:"trunk",tags:"release major-release version-3.53.0",datetime:"2026-04-09T11:41:38.498Z"}}}),globalThis.WhWasmUtilInstaller=function(t){t.bigIntEnabled===void 0&&(t.bigIntEnabled=!!globalThis.BigInt64Array);const r=(...o)=>{throw new Error(o.join(" "))};if(!t.pointerSize&&!t.pointerIR&&t.alloc&&t.dealloc){const o=t.alloc(1);t.pointerSize=typeof o=="bigint"?8:4,t.dealloc(o)}t.pointerSize&&!t.pointerIR&&(t.pointerIR=t.pointerSize===4?"i32":"i64");const s=t.pointerIR??="i32",_=t.pointerSize??=s==="i32"?4:s==="i64"?8:0;delete t.pointerSize,delete t.pointerIR,s!=="i32"&&s!=="i64"?r("Invalid pointerIR:",s):_!==8&&_!==4&&r("Invalid pointerSize:",_);const c=t.bigIntEnabled?o=>BigInt(o||0):o=>r("BigInt support is disabled in this build."),M=_===4?o=>Number(o||0):c,I=M(0),S=function(...o){let u=M(0);for(const p of o)u+=M(p);return u};{const o=Object.create(null);Object.defineProperty(t,"ptr",{enumerable:!0,get:()=>o,set:()=>r("The ptr property is read-only.")}),(function u(p,q){return Object.defineProperty(o,p,{enumerable:!0,get:()=>q,set:()=>r("ptr["+p+"] is read-only.")}),u})("null",I)("size",_)("ir",s)("coerce",M)("add",S)("addn",s===4?S:(...u)=>Number(S(...u)))}t.exports||Object.defineProperty(t,"exports",{enumerable:!0,configurable:!0,get:()=>t.instance?.exports});const w=Object.create(null);w.heapSize=0,w.memory=null,w.freeFuncIndexes=[],w.scopedAlloc=[],w.scopedAlloc.pushPtr=o=>(w.scopedAlloc[w.scopedAlloc.length-1].push(o),o),w.utf8Decoder=new TextDecoder,w.utf8Encoder=new TextEncoder("utf-8"),t.sizeofIR=o=>{switch(o){case"i8":return 1;case"i16":return 2;case"i32":case"f32":case"float":return 4;case"i64":case"f64":case"double":return 8;case"*":return _;default:return(""+o).endsWith("*")?_:void 0}};const x=function(){if(!w.memory)w.memory=t.memory instanceof WebAssembly.Memory?t.memory:t.exports.memory;else if(w.heapSize===w.memory.buffer.byteLength)return w;const o=w.memory.buffer;return w.HEAP8=new Int8Array(o),w.HEAP8U=new Uint8Array(o),w.HEAP16=new Int16Array(o),w.HEAP16U=new Uint16Array(o),w.HEAP32=new Int32Array(o),w.HEAP32U=new Uint32Array(o),w.HEAP32F=new Float32Array(o),w.HEAP64F=new Float64Array(o),t.bigIntEnabled&&(typeof BigInt64Array<"u"?(w.HEAP64=new BigInt64Array(o),w.HEAP64U=new BigUint64Array(o)):r("BigInt support is enabled, but the BigInt64Array type is missing.")),w.heapSize=o.byteLength,w};t.heap8=()=>x().HEAP8,t.heap8u=()=>x().HEAP8U,t.heap16=()=>x().HEAP16,t.heap16u=()=>x().HEAP16U,t.heap32=()=>x().HEAP32,t.heap32u=()=>x().HEAP32U,t.heapForSize=function(o,u=!0){const p=w.memory&&w.heapSize===w.memory.buffer.byteLength?w:x();switch(o){case Int8Array:return p.HEAP8;case Uint8Array:return p.HEAP8U;case Int16Array:return p.HEAP16;case Uint16Array:return p.HEAP16U;case Int32Array:return p.HEAP32;case Uint32Array:return p.HEAP32U;case 8:return u?p.HEAP8U:p.HEAP8;case 16:return u?p.HEAP16U:p.HEAP16;case 32:return u?p.HEAP32U:p.HEAP32;case 64:if(p.HEAP64)return u?p.HEAP64U:p.HEAP64;break;default:if(t.bigIntEnabled){if(o===globalThis.BigUint64Array)return p.HEAP64U;if(o===globalThis.BigInt64Array)return p.HEAP64;break}}r("Invalid heapForSize() size: expecting 8, 16, 32,","or (if BigInt is enabled) 64.")};const L=t.functionTable;delete t.functionTable,t.functionTable=L?()=>L:()=>t.exports.__indirect_function_table,t.functionEntry=function(o){const u=t.functionTable();return o{C<128?R[m](C):R[m](C%128|128,C>>7)},rxJSig:/^(\w)\((\w*)\)$/,sigParams:R=>{const m=o._.rxJSig.exec(R);return m?m[2]:R.substr(1)},letterType:R=>o._.sigTypes[R]||r("Invalid signature letter:",R),pushSigType:(R,m)=>R.push(o._.typeCodes[o._.letterType(m)])}),typeof u=="string"){const R=p;p=u,u=R}const q=o._,z=q.sigParams(p),V=[1,96];q.uleb128Encode(V,"push",z.length);for(const R of z)q.pushSigType(V,R);return p[0]==="v"?V.push(0):(V.push(1),q.pushSigType(V,p[0])),q.uleb128Encode(V,"unshift",V.length),V.unshift(0,97,115,109,1,0,0,0,1),V.push(2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array(V)),{e:{f:u}}).exports.f};const H=function(u,p,q){if(q&&!w.scopedAlloc.length&&r("No scopedAllocPush() scope is active."),typeof u=="string"){const m=p;p=u,u=m}(typeof p!="string"||!(u instanceof Function))&&r("Invalid arguments: expecting (function,signature) or (signature,function).");const z=t.functionTable(),V=M(z.length);let R;for(;(R=w.freeFuncIndexes.pop())&&z.get(R);){R=null;continue}R||(R=M(V),z.grow(M(1)));try{return z.set(R,u),q&&w.scopedAlloc.pushPtr(R),R}catch(m){if(!(m instanceof TypeError))throw R===V&&w.freeFuncIndexes.push(V),m}try{const m=t.jsFuncToWasm(u,p);z.set(R,m),q&&w.scopedAlloc.pushPtr(R)}catch(m){throw R===V&&w.freeFuncIndexes.push(V),m}return R};t.installFunction=(o,u)=>H(o,u,!1),t.scopedInstallFunction=(o,u)=>H(o,u,!0),t.uninstallFunction=function(o){if(!o&&I!==o)return;const u=t.functionTable();w.freeFuncIndexes.push(o);const p=u.get(o);return u.set(o,null),p},t.peek=function(u,p="i8"){p.endsWith("*")&&(p=s);const q=w.memory&&w.heapSize===w.memory.buffer.byteLength?w:x(),z=Array.isArray(u)?[]:void 0;let V;do{switch(z&&(u=arguments[0].shift()),p){case"i1":case"i8":V=q.HEAP8[Number(u)>>0];break;case"i16":V=q.HEAP16[Number(u)>>1];break;case"i32":V=q.HEAP32[Number(u)>>2];break;case"float":case"f32":V=q.HEAP32F[Number(u)>>2];break;case"double":case"f64":V=Number(q.HEAP64F[Number(u)>>3]);break;case"i64":if(q.HEAP64){V=c(q.HEAP64[Number(u)>>3]);break}default:r("Invalid type for peek():",p)}z&&z.push(V)}while(z&&arguments[0].length);return z||V},t.poke=function(o,u,p="i8"){p.endsWith("*")&&(p=s);const q=w.memory&&w.heapSize===w.memory.buffer.byteLength?w:x();for(const z of Array.isArray(o)?o:[o])switch(p){case"i1":case"i8":q.HEAP8[Number(z)>>0]=u;continue;case"i16":q.HEAP16[Number(z)>>1]=u;continue;case"i32":q.HEAP32[Number(z)>>2]=u;continue;case"float":case"f32":q.HEAP32F[Number(z)>>2]=u;continue;case"double":case"f64":q.HEAP64F[Number(z)>>3]=u;continue;case"i64":if(q.HEAP64){q.HEAP64[Number(z)>>3]=c(u);continue}default:r("Invalid type for poke(): "+p)}return this},t.peekPtr=(...o)=>t.peek(o.length===1?o[0]:o,s),t.pokePtr=(o,u=0)=>t.poke(o,u,s),t.peek8=(...o)=>t.peek(o.length===1?o[0]:o,"i8"),t.poke8=(o,u)=>t.poke(o,u,"i8"),t.peek16=(...o)=>t.peek(o.length===1?o[0]:o,"i16"),t.poke16=(o,u)=>t.poke(o,u,"i16"),t.peek32=(...o)=>t.peek(o.length===1?o[0]:o,"i32"),t.poke32=(o,u)=>t.poke(o,u,"i32"),t.peek64=(...o)=>t.peek(o.length===1?o[0]:o,"i64"),t.poke64=(o,u)=>t.poke(o,u,"i64"),t.peek32f=(...o)=>t.peek(o.length===1?o[0]:o,"f32"),t.poke32f=(o,u)=>t.poke(o,u,"f32"),t.peek64f=(...o)=>t.peek(o.length===1?o[0]:o,"f64"),t.poke64f=(o,u)=>t.poke(o,u,"f64"),t.getMemValue=t.peek,t.getPtrValue=t.peekPtr,t.setMemValue=t.poke,t.setPtrValue=t.pokePtr,t.isPtr32=o=>typeof o=="number"&&o>=0&&o===(o|0),t.isPtr64=o=>typeof o=="bigint"?o>=0:t.isPtr32(o),t.isPtr=_===4?t.isPtr32:t.isPtr64,t.cstrlen=function(o){if(!o||!t.isPtr(o))return null;o=Number(o);const u=x().HEAP8U;let p=o;for(;u[p]!==0;++p);return p-o};const g=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,h=o=>o.buffer instanceof g;t.isSharedTypedArray=h;const D=(o,u,p)=>(_===8&&(typeof u=="bigint"&&(u=Number(u)),typeof p=="bigint"&&(p=Number(p))),h(o)?o.slice(u,p):o.subarray(u,p));t.typedArrayPart=D;const Q=(o,u,p)=>w.utf8Decoder.decode(D(o,u,p));t.typedArrayToString=Q,t.cstrToJs=function(o){const u=t.cstrlen(o);return u?Q(x().HEAP8U,Number(o),Number(o)+u):u===null?u:""},t.jstrlen=function(o){if(typeof o!="string")return null;const u=o.length;let p=0;for(let q=0;q=55296&&z<=57343&&(z=65536+((z&1023)<<10)|o.charCodeAt(++q)&1023),z<=127?++p:z<=2047?p+=2:z<=65535?p+=3:p+=4}return p},t.jstrcpy=function(o,u,p=0,q=-1,z=!0){if((!u||!(u instanceof Int8Array)&&!(u instanceof Uint8Array))&&r("jstrcpy() target must be an Int8Array or Uint8Array."),q=Number(q),p=Number(p),q<0&&(q=u.length-p),!(q>0)||!(p>=0))return 0;let V=0,R=o.length;const m=p,C=p+q-(z?1:0);for(;V=55296&&B<=57343&&(B=65536+((B&1023)<<10)|o.charCodeAt(++V)&1023),B<=127){if(p>=C)break;u[p++]=B}else if(B<=2047){if(p+1>=C)break;u[p++]=192|B>>6,u[p++]=128|B&63}else if(B<=65535){if(p+2>=C)break;u[p++]=224|B>>12,u[p++]=128|B>>6&63,u[p++]=128|B&63}else{if(p+3>=C)break;u[p++]=240|B>>18,u[p++]=128|B>>12&63,u[p++]=128|B>>6&63,u[p++]=128|B&63}}return z&&(u[p++]=0),p-m},t.cstrncpy=function(o,u,p){if((!o||!u)&&r("cstrncpy() does not accept NULL strings."),p<0)p=t.cstrlen(strPtr)+1;else if(!(p>0))return 0;const q=t.heap8u();let z=0,V;const R=Number(o),m=Number(u);for(;zw.utf8Encoder.encode(u?o+"\0":o);const A=(o,u)=>{(!(o.alloc instanceof Function)||!(o.dealloc instanceof Function))&&r("Object is missing alloc() and/or dealloc() function(s)","required by",u+"().")},N=function(o,u,p,q){if(A(t,q),typeof o!="string")return null;const z=w.utf8Encoder.encode(o),V=p(z.length+1);let R=V;try{const m=x().HEAP8U;return m.set(z,Number(V)),m[S(V,z.length)]=0,R=I,u?[V,z.length]:V}finally{R&&t.dealloc(R)}};t.allocCString=(o,u=!1)=>N(o,u,t.alloc,"allocCString()"),t.scopedAllocPush=function(){A(t,"scopedAllocPush");const o=[];return w.scopedAlloc.push(o),o},t.scopedAllocPop=function(o){A(t,"scopedAllocPop");const u=arguments.length?w.scopedAlloc.indexOf(o):w.scopedAlloc.length-1;u<0&&r("Invalid state object for scopedAllocPop()."),arguments.length===0&&(o=w.scopedAlloc[u]),w.scopedAlloc.splice(u,1);for(let p;p=o.pop();)t.functionEntry(p)?t.uninstallFunction(p):t.dealloc(p)},t.scopedAlloc=function(o){w.scopedAlloc.length||r("No scopedAllocPush() scope is active.");const u=M(t.alloc(o));return w.scopedAlloc.pushPtr(u)},Object.defineProperty(t.scopedAlloc,"level",{configurable:!1,enumerable:!1,get:()=>w.scopedAlloc.length,set:()=>r("The 'active' property is read-only.")}),t.scopedAllocCString=(o,u=!1)=>N(o,u,t.scopedAlloc,"scopedAllocCString()");const J=function(o,u){const p=t[o?"scopedAlloc":"alloc"]((u.length+1)*t.ptr.size);let q=0;return u.forEach(z=>{t.pokePtr(S(p,t.ptr.size*q++),t[o?"scopedAllocCString":"allocCString"](""+z))}),t.pokePtr(S(p,t.ptr.size*q),0),p};t.scopedAllocMainArgv=o=>J(!0,o),t.allocMainArgv=o=>J(!1,o),t.cArgvToJs=(o,u)=>{const p=[];for(let q=0;qd(o,u,"alloc"),t.scopedAllocPtr=(o=1,u=!0)=>d(o,u,"scopedAlloc"),t.xGet=function(o){return t.exports[o]||r("Cannot find exported symbol:",o)};const y=(o,u)=>r(o+"() requires",u,"argument(s).");t.xCall=function(o,...u){const p=o instanceof Function?o:t.xGet(o);return p instanceof Function||r("Exported symbol",o,"is not a function."),p.length!==u.length&&y(p===o?p.name:o,p.length),arguments.length===2&&Array.isArray(arguments[1])?p.apply(null,arguments[1]):p.apply(null,u)},w.xWrap=Object.create(null),w.xWrap.convert=Object.create(null),w.xWrap.convert.arg=new Map,w.xWrap.convert.result=new Map;const F=w.xWrap.convert.arg,W=w.xWrap.convert.result,P=M;F.set("i64",c).set("i32",o=>o|0).set("i16",o=>(o|0)&65535).set("i8",o=>(o|0)&255).set("f32",o=>Number(o).valueOf()).set("float",F.get("f32")).set("f64",F.get("f32")).set("double",F.get("f64")).set("int",F.get("i32")).set("null",o=>o).set(null,F.get("null")).set("**",P).set("*",P),W.set("*",P).set("pointer",P).set("number",o=>Number(o)).set("void",o=>{}).set(void 0,W.get("void")).set("null",o=>o).set(null,W.get("null"));for(const o of["i8","i16","i32","i64","int","f32","float","f64","double"])F.set(o+"*",P),W.set(o+"*",P),W.set(o,F.get(o)||r("Maintenance required: missing arg converter for",o));const X=o=>typeof o=="string"?t.scopedAllocCString(o):M(o);F.set("string",X).set("utf8",X),W.set("string",o=>t.cstrToJs(o)).set("utf8",W.get("string")).set("string:dealloc",o=>{try{return o?t.cstrToJs(o):null}finally{t.dealloc(o)}}).set("utf8:dealloc",W.get("string:dealloc")).set("json",o=>JSON.parse(t.cstrToJs(o))).set("json:dealloc",o=>{try{return o?JSON.parse(t.cstrToJs(o)):null}finally{t.dealloc(o)}});const ee=class{constructor(o){this.name=o.name||"unnamed adapter"}convertArg(o,u,p){r("AbstractArgAdapter must be subclassed.")}};F.FuncPtrAdapter=class rt extends ee{constructor(u){super(u),F.FuncPtrAdapter.warnOnUse&&console.warn("xArg.FuncPtrAdapter is an internal-only API","and is not intended to be invoked from","client-level code. Invoked with:",u),this.name=u.name||"unnamed",this.signature=u.signature,u.contextKey instanceof Function&&(this.contextKey=u.contextKey,u.bindScope||(u.bindScope="context")),this.bindScope=u.bindScope||r("FuncPtrAdapter options requires a bindScope (explicit or implied)."),rt.bindScopes.indexOf(u.bindScope)<0&&r("Invalid options.bindScope ("+u.bindMod+") for FuncPtrAdapter. Expecting one of: ("+rt.bindScopes.join(", ")+")"),this.isTransient=this.bindScope==="transient",this.isContext=this.bindScope==="context",this.isPermanent=this.bindScope==="permanent",this.singleton=this.bindScope==="singleton"?[]:void 0,this.callProxy=u.callProxy instanceof Function?u.callProxy:void 0}contextKey(u,p){return this}contextMap(u){const p=this.__cmap||(this.__cmap=new Map);let q=p.get(u);return q===void 0&&p.set(u,q=[]),q}convertArg(u,p,q){let z=this.singleton;if(!z&&this.isContext&&(z=this.contextMap(this.contextKey(p,q))),z&&z.length===2&&z[0]===u)return z[1];if(u instanceof Function){this.callProxy&&(u=this.callProxy(u));const V=H(u,this.signature,this.isTransient);if(rt.debugFuncInstall&&rt.debugOut("FuncPtrAdapter installed",this,this.contextKey(p,q),"@"+V,u),z){if(z[1]){rt.debugFuncInstall&&rt.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(p,q),"@"+z[1],u);try{w.scopedAlloc.pushPtr(z[1])}catch{}}z[0]=arguments[0]||I,z[1]=V}return V}else if(t.isPtr(u)||u===null||u===void 0){if(z&&z[1]&&z[1]!==u){rt.debugFuncInstall&&rt.debugOut("FuncPtrAdapter uninstalling",this,this.contextKey(p,q),"@"+z[1],u);try{w.scopedAlloc.pushPtr(z[1])}catch{}z[0]=z[1]=u||I}return u||I}else throw new TypeError("Invalid FuncPtrAdapter argument type. Expecting a function pointer or a "+(this.name?this.name+" ":"")+"function matching signature "+this.signature+".")}},F.FuncPtrAdapter.warnOnUse=!1,F.FuncPtrAdapter.debugFuncInstall=!1,F.FuncPtrAdapter.debugOut=console.debug.bind(console),F.FuncPtrAdapter.bindScopes=["transient","context","singleton","permanent"];const Z=o=>F.get(o)||r("Argument adapter not found:",o),te=o=>W.get(o)||r("Result adapter not found:",o);w.xWrap.convertArg=(o,...u)=>Z(o)(...u),w.xWrap.convertArgNoCheck=(o,...u)=>F.get(o)(...u),w.xWrap.convertResult=(o,u)=>o===null?u:o?te(o)(u):void 0,w.xWrap.convertResultNoCheck=(o,u)=>o===null?u:o?W.get(o)(u):void 0,t.xWrap=function o(u,p,...q){arguments.length===3&&Array.isArray(arguments[2])&&(q=arguments[2]),t.isPtr(u)&&(u=t.functionEntry(u)||r("Function pointer not found in WASM function table."));const z=u instanceof Function,V=z?u:t.xGet(u);if(z&&(u=V.name||"unnamed function"),q.length!==V.length&&y(u,V.length),V.length===0&&(p===null||p==="null"))return V;te(p);for(const m of q)m instanceof ee?F.set(m,(...C)=>m.convertArg(...C)):Z(m);const R=w.xWrap;return V.length===0?(...m)=>m.length?y(u,V.length):R.convertResult(p,V.call(null)):function(...m){m.length!==V.length&&y(u,V.length);const C=t.scopedAllocPush();try{let B=0;for(o.debug&&console.debug("xWrap() preparing: resultType ",p,"xf",V,"argTypes",q,"args",m);Bfetch(t.uri,{credentials:"same-origin"}),s=this,_=function(c){if(t.wasmUtilTarget){const b=(...I)=>{throw new Error(I.join(" "))},M=t.wasmUtilTarget;if(M.module=c.module,M.instance=c.instance,M.instance.exports.memory||(M.memory=t?.imports?.env?.memory||b("Missing 'memory' object!")),!M.alloc&&c.instance.exports.malloc){const I=c.instance.exports;M.alloc=function(S){return I.malloc(S)||b("Allocation of",S,"bytes failed.")},M.dealloc=function(S){S&&I.free(S)}}s(M)}return c.config=t,t.onload&&t.onload(c),c};return WebAssembly.instantiateStreaming?()=>WebAssembly.instantiateStreaming(r(),t.imports||{}).then(_):()=>r().then(c=>c.arrayBuffer()).then(c=>WebAssembly.instantiate(c,t.imports||{})).then(_)}).bind(globalThis.WhWasmUtilInstaller),globalThis.Jaccwabyt=function i(t){const r=(...T)=>{throw new Error(T.join(" "))};{let T=t.heap;T instanceof WebAssembly.Memory?T=(function(){return new Uint8Array(this.buffer)}).bind(T):T instanceof Function||r("config.heap must be WebAssembly.Memory instance or","a function which returns one."),t.heap=T}["alloc","dealloc"].forEach(function(T){t[T]instanceof Function||r("Config option '"+T+"' must be a function.")});const s=i,_=t.heap,c=t.alloc,b=t.dealloc;t.realloc;const M=t.log||console.debug.bind(console),I=t.memberPrefix||"",S=t.memberSuffix||"",w=globalThis.BigInt,x=globalThis.BigInt64Array,L=t.bigIntEnabled??!!x;let H;const g=t.pointerSize||t.ptrSize||(typeof(H=c(1))=="bigint"?8:4),h=t.pointerIR||t.ptrIR||(g===4?"i32":"i64");H&&(b(H),H=void 0),g!==4&&g!==8&&r("Invalid pointer size:",g),h!=="i32"&&h!=="i64"&&r("Invalid pointer representation:",h);const D=L&&w?T=>w(T||0):T=>r("BigInt support is disabled in this build."),Q=h=="i32"?Number:D,A=Q(0),N=function(...T){let U=A;for(let K=0;KT[1]==="(",F=T=>T==="p"||T==="P"||T==="s",W=T=>T==="P",P=T=>T?y(T)?"p":T[0]:void 0,X=function(T){switch(P(T)){case"c":case"C":return"i8";case"i":return"i32";case"p":case"P":case"s":return h;case"j":return"i64";case"f":return"float";case"d":return"double"}r("Unhandled signature IR:",T)},ee=function(T){switch(P(T)){case"c":case"C":return 1;case"i":return 4;case"p":case"P":case"s":return g;case"j":return 8;case"f":return 4;case"d":return 8}r("Unhandled signature sizeof:",T)},Z=x?()=>!0:()=>r("BigInt64Array is not available."),te=function(T){switch(P(T)){case"p":case"P":case"s":switch(g){case 4:return"getInt32";case 8:return Z()&&"getBigInt64"}break;case"i":return"getInt32";case"c":return"getInt8";case"C":return"getUint8";case"j":return Z()&&"getBigInt64";case"f":return"getFloat32";case"d":return"getFloat64"}r("Unhandled DataView getter for signature:",T)},E=function(T){switch(P(T)){case"p":case"P":case"s":switch(g){case 4:return"setInt32";case 8:return Z()&&"setBigInt64"}break;case"i":return"setInt32";case"c":return"setInt8";case"C":return"setUint8";case"j":return Z()&&"setBigInt64";case"f":return"setFloat32";case"d":return"setFloat64"}r("Unhandled DataView setter for signature:",T)},o=function(T){switch(P(T)){case"i":case"f":case"c":case"C":case"d":return Number;case"j":return D;case"p":case"P":case"s":switch(g){case 4:return Number;case 8:return D}break}r("Unhandled DataView set wrapper for signature:",T)},u=(T,U)=>T+"::"+U,p=function(T,U){return()=>r(u(T,U),"is read-only.")},q=function T(U,K=!0){let re=T.map.get(U);return!re&&K&&T.map.set(U,re=T.create(U)),re};q.map=new WeakMap,q.create=T=>Object.assign(Object.create(null),{o:T,p:void 0,ownsPointer:!1,zod:!1,xb:0});const z=T=>q.map.delete(T),V=T=>typeof T=="number"&&T===(T|0)&&T>=0,m=g===4?V:T=>typeof T=="bigint"&&T>=0||V(T),C=T=>m(T)&&T>0,B=function(T,U,K){const re=q(U,!1);if(re){if(z(U),!K&&!(K=re.p)){console.warn("Cannot(?) happen: __freeStruct() found no instanceInfo");return}if(Array.isArray(U.ondispose)){let ue;for(;ue=U.ondispose.pop();)try{ue instanceof Function?ue.call(U):ue instanceof Ge?ue.dispose():m(ue)&&b(ue)}catch(Te){console.warn("ondispose() for",T.structName,"@",K,"threw. NOT propagating it.",Te)}}else if(U.ondispose instanceof Function)try{U.ondispose()}catch(ue){console.warn("ondispose() for",T.structName,"@",K,"threw. NOT propagating it.",ue)}delete U.ondispose,T.debugFlags.__flags.dealloc&&M("debug.dealloc:",re.ownsPointer?"":"EXTERNAL",T.structName,"instance:",T.structInfo.sizeof,"bytes @"+K),re.ownsPointer&&((re.zod||T.structInfo.zeroOnDispose)&&_().fill(0,Number(K),Number(K)+T.structInfo.sizeof+re.xb),b(K))}},Y=()=>({configurable:!1,writable:!1,iterable:!1}),ne=T=>({...Y(),value:T}),ae=function(U,K,re){let ue;const Te=Ae=>{C(Ae)||r("Invalid pointer value",arguments[0],"for",U.structName,"constructor.")};arguments.length>=3?re&&typeof re=="object"?(ue=re,re=ue?.wrap):(Te(re),ue={wrap:re}):ue={};const Me=!re;let He=0,$e=!1;if(re)Te(re),$e=!!ue?.takeOwnership;else{const Ae=ue?.extraBytes??0;(Ae<0||Ae!==(Ae|0))&&r("Invalid extraBytes value:",ue?.extraBytes),He=U.structInfo.sizeof+Ae,re=c(He)||r("Allocation of",U.structName,"structure failed."),$e=!0}try{ue?.debugFlags&&K.debugFlags(ue.debugFlags),U.debugFlags.__flags.alloc&&M("debug.alloc:",Me?"":"EXTERNAL",U.structName,"instance:",U.structInfo.sizeof,"bytes @"+re),Me&&_().fill(0,Number(re),Number(re)+He);const Ae=q(K);Ae.p=re,Ae.ownsPointer=$e,Ae.xb=He?He-U.structInfo.sizeof:0,Ae.zod=!!ue?.zeroOnDispose,ue?.ondispose&&ue.ondispose!==re&&K.addOnDispose(ue.ondispose)}catch(Ae){throw B(U,K,re),Ae}},ce=function T(U){return T.rxSig1??=/^[ipPsjfdcC]$/,T.rxSig2??=/^[vipPsjfdcC]\([ipPsjfdcC]*\)$/,T.rxSig1.test(U)||T.rxSig2.test(U)},ke=(function(T){let U=this.get(T);return U||(U=[Object.create(null),Object.create(null),Object.create(null)],this.set(T,U)),U}).bind(new WeakMap),Ne=function(T,U,K,re){const ue=ke(T)[U];return arguments.length===3?ue[K]:re?ue[K]=re:delete ue[K]},Xe=function(T,...U){return Ne(this,0,T,...U)},at=function(T,U){ce(U)&&r(T,"(",U,") collides with a data type signature.")},O=function(T,...U){return at("Setter adaptor",T),Ne(this,1,T,...U)},j=function(T,...U){return at("Struct adaptor",T),Ne(this,2,T,...U)},G=function(T,U){const K=typeof U=="string"?Ne(T,2,U):U;return typeof K!="object"&&r("Invalid struct mapping object. Arg =",U,JSON.stringify(K)),K},se=ne(T=>I+T+S),le=function(T,U,K=!0){let re=T.members[U];if(!re&&(I||S)){for(const ue of Object.values(T.members))if(ue.key===U){re=ue;break}!re&&K&&r(u(T.name||T.structName,U),"is not a mapped struct member.")}return re},_e=function T(U,K,re=!1){T._||(T._=Te=>Te.replace(/[^vipPsjrdcC]/g,"").replace(/[pPscC]/g,"i"));const ue=le(U.structInfo,K,!0);return re?T._(ue.signature):ue.signature},oe=ne(function(){const T=[];for(const U of Object.keys(this.structInfo.members))T.push(this.memberKey(U));return T}),pe=new TextDecoder("utf-8"),we=new TextEncoder,Pe=typeof SharedArrayBuffer>"u"?function(){}:SharedArrayBuffer,be=function(T,U,K){return g===8&&(U=Number(U),K=Number(K)),pe.decode(T.buffer instanceof Pe?T.slice(U,K):T.subarray(U,K))},Ue=function(T,U,K=!1){const re=le(T.structInfo,U,K);return re&&re.signature.length===1&&re.signature[0]==="s"?re:!1},Ye=function(T){T.signature!=="s"&&r("Invalid member type signature for C-string value:",JSON.stringify(T))},pt=function(U,K){const re=le(U.structInfo,K,!0);Ye(re);const ue=U[re.key];if(!ue)return null;let Te=ue;const Me=_();for(;Me[Te]!==0;++Te);return ue===Te?"":be(Me,ue,Te)},Ze=function(T,...U){T.ondispose?Array.isArray(T.ondispose)||(T.ondispose=[T.ondispose]):T.ondispose=[],T.ondispose.push(...U)},ct=function(T){const U=we.encode(T),K=c(U.length+1);K||r("Allocation error while duplicating string:",T);const re=_();return re.set(U,Number(K)),re[N(K,U.length)]=0,K},qt=function(T,U,K){const re=le(T.structInfo,U,!0);Ye(re);const ue=ct(K);return T[re.key]=ue,Ze(T,ue),T},Ge=function(U,K){arguments[2]!==ne&&r("Do not call the StructType constructor","from client-level code."),Object.defineProperties(this,{structName:ne(U),structInfo:ne(K)})};Ge.prototype=Object.create(null,{dispose:ne(function(){B(this.constructor,this)}),lookupMember:ne(function(T,U=!0){return le(this.structInfo,T,U)}),memberToJsString:ne(function(T){return pt(this,T)}),memberIsString:ne(function(T,U=!0){return Ue(this,T,U)}),memberKey:se,memberKeys:oe,memberSignature:ne(function(T,U=!1){return _e(this,T,U)}),memoryDump:ne(function(){const T=this.pointer;return T?new Uint8Array(_().slice(Number(T),Number(T)+this.structInfo.sizeof)):null}),extraBytes:{configurable:!1,enumerable:!1,get:function(){return q(this,!1)?.xb??0}},zeroOnDispose:{configurable:!1,enumerable:!1,get:function(){return q(this,!1)?.zod??!!this.structInfo.zeroOnDispose}},pointer:{configurable:!1,enumerable:!1,get:function(){return q(this,!1)?.p},set:()=>r("Cannot assign the 'pointer' property of a struct.")},setMemberCString:ne(function(T,U){return qt(this,T,U)})}),Object.assign(Ge.prototype,{addOnDispose:function(...T){return Ze(this,...T),this}}),Object.defineProperties(Ge,{allocCString:ne(ct),isA:ne(T=>T instanceof Ge),hasExternalPointer:ne(T=>{const U=q(T,!1);return!!(U?.p&&!U?.ownsPointer)}),memberKey:se});const wt=function(T){return T.get||(T.adaptGet?Ke.adaptGet(T.adaptGet):void 0)},Zt=function(T){return T.set||(T.adaptSet?Ke.adaptSet(T.adaptSet):void 0)},Ir=function T(U,K,re){const ue=T.innerStructs??=new Map,Te=U.memberKey(K);re.signature!==void 0&&r("'signature' cannot be used on an embedded struct (",U.structName,".",Te,")."),Zt(re)&&r("'set' and 'adaptSet' are not permitted for nested struct members."),re.structName??=U.structName+"::"+K,re.key=Te,re.name=K,re.constructor=this.call(this,re.structName,re);const Me=wt(re),He=Object.assign(Object.create(null),{configurable:!1,enumerable:!1,set:p(U.structName,Te),get:function(){const $e=this.debugFlags.__flags,Ae=this.pointer,ze=Ae+"."+Te;let fe=ue.get(ze);return $e.getter&&M("debug.getter: k =",ze),fe||(fe=new re.constructor(N(Ae,re.offset)),ue.set(ze,fe),this.addOnDispose(()=>fe.dispose()),fe.addOnDispose(()=>ue.delete(ze))),Me&&(fe=Me.apply(this,[fe,Te])),$e.getter&&M("debug.getter: result =",fe),fe}});Object.defineProperty(U.prototype,Te,He)},kr=function T(U,K,re){if(re=G(this,re),re.members)return Ir.call(this,U,K,re);if(!T.cache){T.cache={getters:{},setters:{},sw:{}};const ze=["i","c","C","p","P","s","f","d","v()"];L&&ze.push("j"),ze.forEach(function(fe){T.cache.getters[fe]=te(fe),T.cache.setters[fe]=E(fe),T.cache.sw[fe]=o(fe)}),T.sigCheck=function(fe,Re,Et,tn){Object.prototype.hasOwnProperty.call(fe,Et)&&r(fe.structName,"already has a property named",Et+"."),ce(tn)||r("Malformed signature for",u(fe.structName,Re)+":",tn)}}const ue=U.memberKey(K);T.sigCheck(U.prototype,K,ue,re.signature),re.key=ue,re.name=K;const Te=P(re.signature),Me=u(U.structName,ue),He=U.debugFlags.__flags,$e=wt(re),Ae=Object.create(null);if(Ae.configurable=!1,Ae.enumerable=!1,Ae.get=function(){He.getter&&M("debug.getter:",T.cache.getters[Te],"for",X(Te),Me,"@",this.pointer,"+",re.offset,"sz",re.sizeof);let ze=new DataView(_().buffer,Number(this.pointer)+re.offset,re.sizeof)[T.cache.getters[Te]](0,d);return $e&&(ze=$e.apply(this,[ue,ze])),He.getter&&M("debug.getter:",Me,"result =",ze),ze},re.readOnly)Ae.set=p(U.prototype.structName,ue);else{const ze=Zt(re);Ae.set=function(fe){He.setter&&M("debug.setter:",T.cache.setters[Te],"for",X(Te),Me,"@",this.pointer,"+",re.offset,"sz",re.sizeof,fe),this.pointer||r("Cannot set native property on a disposed",this.structName,"instance."),ze&&(fe=ze.apply(this,[ue,fe])),fe==null?fe=A:F(re.signature)&&!m(fe)&&(W(re.signature)&&fe instanceof Ge?(fe=fe.pointer||A,He.setter&&M("debug.setter:",Me,"resolved to",fe)):r("Invalid value for pointer-type",Me+".")),new DataView(_().buffer,Number(this.pointer)+re.offset,re.sizeof)[T.cache.setters[Te]](0,T.cache.sw[Te](fe),d)}}Object.defineProperty(U.prototype,ue,Ae)},en=function T(U,K,re=Object.create(null)){const ue=function fe(Re){this instanceof fe||r("The",U,"constructor may only be called via 'new'."),ae(fe,this,...arguments)},Te=this,Me=fe=>typeof fe=="string"&&ce(fe)?{signature:fe}:G(Te,fe);arguments.length===1?(K=Me(U),U=K.structName||K.name):arguments.length===2?(K=Me(K),K.name??=U):K=Me(K),U??=K.structName,U??=re.structName,U||r("One of 'name' or 'structName' are required."),K.adapt&&(Object.keys(K.adapt.struct||{}).forEach(fe=>{j.call(T,fe,K.adapt.struct[fe])}),Object.keys(K.adapt.set||{}).forEach(fe=>{O.call(T,fe,K.adapt.set[fe])}),Object.keys(K.adapt.get||{}).forEach(fe=>{Xe.call(T,fe,K.adapt.get[fe])})),!K.members&&!K.sizeof&&(K.sizeof=ee(K.signature));const He=ne(s.__makeDebugFlags(Ke.debugFlags));Object.defineProperties(ue,{debugFlags:He,isA:ne(fe=>fe instanceof ue),memberKey:se,memberKeys:oe,structInfo:ne(K),structName:ne(U),ptrAdd:ne(N)}),ue.prototype=new Ge(U,K,ne),Object.defineProperties(ue.prototype,{debugFlags:He,constructor:ne(ue),ptrAdd:ne(J)});let $e=!1,Ae=0;const ze=!!K.autoCalcSizeOffset;return ze||K.sizeof||r(U,"description is missing its sizeof property."),K.offset??=0,Object.keys(K.members||{}).forEach(fe=>{let Re=Me(K.members[fe]);!Re.members&&!Re.sizeof&&(Re.sizeof=ee(Re.signature),Re.sizeof||r(u(U,fe),"is missing a sizeof property.",Re)),Re.offset===void 0&&(ze?Re.offset=Ae:r(u(U,fe),"is missing its offset.",JSON.stringify(Re))),K.members[fe]=Re,(!$e||$e.offset{throw new Error(g.join(" "))},r=i.capi,s=i.wasm,_=i.util;globalThis.WhWasmUtilInstaller(s),delete globalThis.WhWasmUtilInstaller;const c={core:[["sqlite3_aggregate_context","void*","sqlite3_context*","int"],["sqlite3_bind_double","int","sqlite3_stmt*","int","f64"],["sqlite3_bind_int","int","sqlite3_stmt*","int","int"],["sqlite3_bind_null",void 0,"sqlite3_stmt*","int"],["sqlite3_bind_parameter_count","int","sqlite3_stmt*"],["sqlite3_bind_parameter_index","int","sqlite3_stmt*","string"],["sqlite3_bind_parameter_name","string","sqlite3_stmt*","int"],["sqlite3_bind_pointer","int","sqlite3_stmt*","int","*","string:static","*"],["sqlite3_bind_zeroblob","int","sqlite3_stmt*","int","int"],["sqlite3_busy_handler","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({signature:"i(pi)",contextKey:(g,h)=>g[0]}),"*"]],["sqlite3_busy_timeout","int","sqlite3*","int"],["sqlite3_changes","int","sqlite3*"],["sqlite3_clear_bindings","int","sqlite3_stmt*"],["sqlite3_collation_needed","int","sqlite3*","*","*"],["sqlite3_column_blob","*","sqlite3_stmt*","int"],["sqlite3_column_bytes","int","sqlite3_stmt*","int"],["sqlite3_column_count","int","sqlite3_stmt*"],["sqlite3_column_decltype","string","sqlite3_stmt*","int"],["sqlite3_column_double","f64","sqlite3_stmt*","int"],["sqlite3_column_int","int","sqlite3_stmt*","int"],["sqlite3_column_name","string","sqlite3_stmt*","int"],["sqlite3_column_type","int","sqlite3_stmt*","int"],["sqlite3_column_value","sqlite3_value*","sqlite3_stmt*","int"],["sqlite3_commit_hook","void*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_commit_hook",signature:"i(p)",contextKey:g=>g[0]}),"*"]],["sqlite3_compileoption_get","string","int"],["sqlite3_compileoption_used","int","string"],["sqlite3_complete","int","string:flexible"],["sqlite3_context_db_handle","sqlite3*","sqlite3_context*"],["sqlite3_data_count","int","sqlite3_stmt*"],["sqlite3_db_filename","string","sqlite3*","string"],["sqlite3_db_handle","sqlite3*","sqlite3_stmt*"],["sqlite3_db_name","string","sqlite3*","int"],["sqlite3_db_readonly","int","sqlite3*","string"],["sqlite3_db_status","int","sqlite3*","int","*","*","int"],["sqlite3_errcode","int","sqlite3*"],["sqlite3_errmsg","string","sqlite3*"],["sqlite3_error_offset","int","sqlite3*"],["sqlite3_errstr","string","int"],["sqlite3_exec","int",["sqlite3*","string:flexible",new s.xWrap.FuncPtrAdapter({signature:"i(pipp)",bindScope:"transient",callProxy:g=>{let h;return(D,Q,A,N)=>{try{const J=s.cArgvToJs(Q,A);return h||(h=s.cArgvToJs(Q,N)),g(J,h)|0}catch(J){return J.resultCode||r.SQLITE_ERROR}}}}),"*","**"]],["sqlite3_expanded_sql","string","sqlite3_stmt*"],["sqlite3_extended_errcode","int","sqlite3*"],["sqlite3_extended_result_codes","int","sqlite3*","int"],["sqlite3_file_control","int","sqlite3*","string","int","*"],["sqlite3_finalize","int","sqlite3_stmt*"],["sqlite3_free",void 0,"*"],["sqlite3_get_autocommit","int","sqlite3*"],["sqlite3_get_auxdata","*","sqlite3_context*","int"],["sqlite3_initialize",void 0],["sqlite3_interrupt",void 0,"sqlite3*"],["sqlite3_is_interrupted","int","sqlite3*"],["sqlite3_keyword_count","int"],["sqlite3_keyword_name","int",["int","**","*"]],["sqlite3_keyword_check","int",["string","int"]],["sqlite3_libversion","string"],["sqlite3_libversion_number","int"],["sqlite3_limit","int",["sqlite3*","int","int"]],["sqlite3_malloc","*","int"],["sqlite3_next_stmt","sqlite3_stmt*",["sqlite3*","sqlite3_stmt*"]],["sqlite3_open","int","string","*"],["sqlite3_open_v2","int","string","*","int","string"],["sqlite3_realloc","*","*","int"],["sqlite3_reset","int","sqlite3_stmt*"],["sqlite3_result_blob",void 0,"sqlite3_context*","*","int","*"],["sqlite3_result_double",void 0,"sqlite3_context*","f64"],["sqlite3_result_error",void 0,"sqlite3_context*","string","int"],["sqlite3_result_error_code",void 0,"sqlite3_context*","int"],["sqlite3_result_error_nomem",void 0,"sqlite3_context*"],["sqlite3_result_error_toobig",void 0,"sqlite3_context*"],["sqlite3_result_int",void 0,"sqlite3_context*","int"],["sqlite3_result_null",void 0,"sqlite3_context*"],["sqlite3_result_pointer",void 0,"sqlite3_context*","*","string:static","*"],["sqlite3_result_subtype",void 0,"sqlite3_value*","int"],["sqlite3_result_text",void 0,"sqlite3_context*","string","int","*"],["sqlite3_result_zeroblob",void 0,"sqlite3_context*","int"],["sqlite3_rollback_hook","void*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_rollback_hook",signature:"v(p)",contextKey:g=>g[0]}),"*"]],["sqlite3_set_auxdata",void 0,["sqlite3_context*","int","*","*"]],["sqlite3_set_errmsg","int","sqlite3*","int","string"],["sqlite3_shutdown",void 0],["sqlite3_sourceid","string"],["sqlite3_sql","string","sqlite3_stmt*"],["sqlite3_status","int","int","*","*","int"],["sqlite3_step","int","sqlite3_stmt*"],["sqlite3_stmt_busy","int","sqlite3_stmt*"],["sqlite3_stmt_readonly","int","sqlite3_stmt*"],["sqlite3_stmt_status","int","sqlite3_stmt*","int","int"],["sqlite3_strglob","int","string","string"],["sqlite3_stricmp","int","string","string"],["sqlite3_strlike","int","string","string","int"],["sqlite3_strnicmp","int","string","string","int"],["sqlite3_table_column_metadata","int","sqlite3*","string","string","string","**","**","*","*","*"],["sqlite3_total_changes","int","sqlite3*"],["sqlite3_trace_v2","int",["sqlite3*","int",new s.xWrap.FuncPtrAdapter({name:"sqlite3_trace_v2::callback",signature:"i(ippp)",contextKey:(g,h)=>g[0]}),"*"]],["sqlite3_txn_state","int",["sqlite3*","string"]],["sqlite3_uri_boolean","int","sqlite3_filename","string","int"],["sqlite3_uri_key","string","sqlite3_filename","int"],["sqlite3_uri_parameter","string","sqlite3_filename","string"],["sqlite3_user_data","void*","sqlite3_context*"],["sqlite3_value_blob","*","sqlite3_value*"],["sqlite3_value_bytes","int","sqlite3_value*"],["sqlite3_value_double","f64","sqlite3_value*"],["sqlite3_value_dup","sqlite3_value*","sqlite3_value*"],["sqlite3_value_free",void 0,"sqlite3_value*"],["sqlite3_value_frombind","int","sqlite3_value*"],["sqlite3_value_int","int","sqlite3_value*"],["sqlite3_value_nochange","int","sqlite3_value*"],["sqlite3_value_numeric_type","int","sqlite3_value*"],["sqlite3_value_pointer","*","sqlite3_value*","string:static"],["sqlite3_value_subtype","int","sqlite3_value*"],["sqlite3_value_type","int","sqlite3_value*"],["sqlite3_vfs_find","*","string"],["sqlite3_vfs_register","int","sqlite3_vfs*","int"],["sqlite3_vfs_unregister","int","sqlite3_vfs*"]],int64:[["sqlite3_bind_int64","int",["sqlite3_stmt*","int","i64"]],["sqlite3_changes64","i64",["sqlite3*"]],["sqlite3_column_int64","i64",["sqlite3_stmt*","int"]],["sqlite3_deserialize","int","sqlite3*","string","*","i64","i64","int"],["sqlite3_last_insert_rowid","i64",["sqlite3*"]],["sqlite3_malloc64","*","i64"],["sqlite3_msize","i64","*"],["sqlite3_overload_function","int",["sqlite3*","string","int"]],["sqlite3_realloc64","*","*","i64"],["sqlite3_result_int64",void 0,"*","i64"],["sqlite3_result_zeroblob64","int","*","i64"],["sqlite3_serialize","*","sqlite3*","string","*","int"],["sqlite3_set_last_insert_rowid",void 0,["sqlite3*","i64"]],["sqlite3_status64","int","int","*","*","int"],["sqlite3_db_status64","int","sqlite3*","int","*","*","int"],["sqlite3_total_changes64","i64",["sqlite3*"]],["sqlite3_update_hook","*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_update_hook::callback",signature:"v(pippj)",contextKey:g=>g[0],callProxy:g=>(h,D,Q,A,N)=>{g(h,D,s.cstrToJs(Q),s.cstrToJs(A),N)}}),"*"]],["sqlite3_uri_int64","i64",["sqlite3_filename","string","i64"]],["sqlite3_value_int64","i64","sqlite3_value*"]],wasmInternal:[["sqlite3__wasm_db_reset","int","sqlite3*"],["sqlite3__wasm_db_vfs","sqlite3_vfs*","sqlite3*","string"],["sqlite3__wasm_vfs_create_file","int","sqlite3_vfs*","string","*","int"],["sqlite3__wasm_posix_create_file","int","string","*","int"],["sqlite3__wasm_vfs_unlink","int","sqlite3_vfs*","string"],["sqlite3__wasm_qfmt_token","string:dealloc","string","int"]]};if(s.exports.sqlite3_progress_handler&&c.core.push(["sqlite3_progress_handler",void 0,["sqlite3*","int",new s.xWrap.FuncPtrAdapter({name:"xProgressHandler",signature:"i(p)",bindScope:"context",contextKey:(g,h)=>g[0]}),"*"]]),s.exports.sqlite3_stmt_explain&&c.core.push(["sqlite3_stmt_explain","int","sqlite3_stmt*","int"],["sqlite3_stmt_isexplain","int","sqlite3_stmt*"]),s.exports.sqlite3_set_authorizer&&c.core.push(["sqlite3_set_authorizer","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_set_authorizer::xAuth",signature:"i(pissss)",contextKey:(g,h)=>g[0],callProxy:g=>(h,D,Q,A,N,J)=>{try{return Q=Q&&s.cstrToJs(Q),A=A&&s.cstrToJs(A),N=N&&s.cstrToJs(N),J=J&&s.cstrToJs(J),g(h,D,Q,A,N,J)|0}catch(d){return d.resultCode||r.SQLITE_ERROR}}}),"*"]]),s.exports.sqlite3_column_origin_name&&c.core.push(["sqlite3_column_database_name","string","sqlite3_stmt*","int"],["sqlite3_column_origin_name","string","sqlite3_stmt*","int"],["sqlite3_column_table_name","string","sqlite3_stmt*","int"]),s.bigIntEnabled&&s.exports.sqlite3_declare_vtab&&c.int64.push(["sqlite3_create_module","int",["sqlite3*","string","sqlite3_module*","*"]],["sqlite3_create_module_v2","int",["sqlite3*","string","sqlite3_module*","*","*"]],["sqlite3_declare_vtab","int",["sqlite3*","string:flexible"]],["sqlite3_drop_modules","int",["sqlite3*","**"]],["sqlite3_vtab_collation","string","sqlite3_index_info*","int"],["sqlite3_vtab_distinct","int","sqlite3_index_info*"],["sqlite3_vtab_in","int","sqlite3_index_info*","int","int"],["sqlite3_vtab_in_first","int","sqlite3_value*","**"],["sqlite3_vtab_in_next","int","sqlite3_value*","**"],["sqlite3_vtab_nochange","int","sqlite3_context*"],["sqlite3_vtab_on_conflict","int","sqlite3*"],["sqlite3_vtab_rhs_value","int","sqlite3_index_info*","int","**"]),s.bigIntEnabled&&s.exports.sqlite3_preupdate_hook&&c.int64.push(["sqlite3_preupdate_blobwrite","int","sqlite3*"],["sqlite3_preupdate_count","int","sqlite3*"],["sqlite3_preupdate_depth","int","sqlite3*"],["sqlite3_preupdate_hook","*",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"sqlite3_preupdate_hook",signature:"v(ppippjj)",contextKey:g=>g[0],callProxy:g=>(h,D,Q,A,N,J,d)=>{g(h,D,Q,s.cstrToJs(A),s.cstrToJs(N),J,d)}}),"*"]],["sqlite3_preupdate_new","int",["sqlite3*","int","**"]],["sqlite3_preupdate_old","int",["sqlite3*","int","**"]]),s.bigIntEnabled&&s.exports.sqlite3changegroup_add&&s.exports.sqlite3session_create&&s.exports.sqlite3_preupdate_hook){const g={signature:"i(ps)",callProxy:h=>(D,Q)=>{try{return h(D,s.cstrToJs(Q))|0}catch(A){return A.resultCode||r.SQLITE_ERROR}}};c.int64.push(["sqlite3changegroup_add","int",["sqlite3_changegroup*","int","void*"]],["sqlite3changegroup_add_strm","int",["sqlite3_changegroup*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changegroup_delete",void 0,["sqlite3_changegroup*"]],["sqlite3changegroup_new","int",["**"]],["sqlite3changegroup_output","int",["sqlite3_changegroup*","int*","**"]],["sqlite3changegroup_output_strm","int",["sqlite3_changegroup*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply","int",["sqlite3*","int","void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_strm","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*"]],["sqlite3changeset_apply_v2","int",["sqlite3*","int","void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v2_strm","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",bindScope:"transient",...g}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3","int",["sqlite3*","int","void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_apply_v3_strm","int",["sqlite3*",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xFilter",signature:"i(pp)",bindScope:"transient"}),new s.xWrap.FuncPtrAdapter({name:"xConflict",signature:"i(pip)",bindScope:"transient"}),"void*","**","int*","int"]],["sqlite3changeset_concat","int",["int","void*","int","void*","int*","**"]],["sqlite3changeset_concat_strm","int",[new s.xWrap.FuncPtrAdapter({name:"xInputA",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xInputB",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_conflict","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_finalize","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_fk_conflicts","int",["sqlite3_changeset_iter*","int*"]],["sqlite3changeset_invert","int",["int","void*","int*","**"]],["sqlite3changeset_invert_strm","int",[new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppi)",bindScope:"transient"}),"void*"]],["sqlite3changeset_new","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_next","int",["sqlite3_changeset_iter*"]],["sqlite3changeset_old","int",["sqlite3_changeset_iter*","int","**"]],["sqlite3changeset_op","int",["sqlite3_changeset_iter*","**","int*","int*","int*"]],["sqlite3changeset_pk","int",["sqlite3_changeset_iter*","**","int*"]],["sqlite3changeset_start","int",["**","int","*"]],["sqlite3changeset_start_strm","int",["**",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3changeset_start_v2","int",["**","int","*","int"]],["sqlite3changeset_start_v2_strm","int",["**",new s.xWrap.FuncPtrAdapter({name:"xInput",signature:"i(ppp)",bindScope:"transient"}),"void*","int"]],["sqlite3session_attach","int",["sqlite3_session*","string"]],["sqlite3session_changeset","int",["sqlite3_session*","int*","**"]],["sqlite3session_changeset_size","i64",["sqlite3_session*"]],["sqlite3session_changeset_strm","int",["sqlite3_session*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_config","int",["int","void*"]],["sqlite3session_create","int",["sqlite3*","string","**"]],["sqlite3session_diff","int",["sqlite3_session*","string","string","**"]],["sqlite3session_enable","int",["sqlite3_session*","int"]],["sqlite3session_indirect","int",["sqlite3_session*","int"]],["sqlite3session_isempty","int",["sqlite3_session*"]],["sqlite3session_memory_used","i64",["sqlite3_session*"]],["sqlite3session_object_config","int",["sqlite3_session*","int","void*"]],["sqlite3session_patchset","int",["sqlite3_session*","*","**"]],["sqlite3session_patchset_strm","int",["sqlite3_session*",new s.xWrap.FuncPtrAdapter({name:"xOutput",signature:"i(ppp)",bindScope:"transient"}),"void*"]],["sqlite3session_table_filter",void 0,["sqlite3_session*",new s.xWrap.FuncPtrAdapter({name:"xFilter",...g,contextKey:(h,D)=>h[0]}),"*"]])}i.StructBinder=globalThis.Jaccwabyt({heap:s.heap8u,alloc:s.alloc,dealloc:s.dealloc,bigIntEnabled:s.bigIntEnabled,pointerIR:s.ptr.ir,memberPrefix:"$"}),delete globalThis.Jaccwabyt;{const g=s.xWrap.argAdapter("string");s.xWrap.argAdapter("string:flexible",A=>g(_.flexibleString(A))),s.xWrap.argAdapter("string:static",(function(A){return s.isPtr(A)?A:(A=""+A,this[A]||(this[A]=s.allocCString(A)))}).bind(Object.create(null)));const h=s.xWrap.argAdapter("*"),D=function(){};s.xWrap.argAdapter("sqlite3_filename",h)("sqlite3_context*",h)("sqlite3_value*",h)("void*",h)("sqlite3_changegroup*",h)("sqlite3_changeset_iter*",h)("sqlite3_session*",h)("sqlite3_stmt*",A=>h(A instanceof(i?.oo1?.Stmt||D)?A.pointer:A))("sqlite3*",A=>h(A instanceof(i?.oo1?.DB||D)?A.pointer:A))("sqlite3_vfs*",A=>typeof A=="string"?r.sqlite3_vfs_find(A)||i.SQLite3Error.toss(r.SQLITE_NOTFOUND,"Unknown sqlite3_vfs name:",A):h(A instanceof(r.sqlite3_vfs||D)?A.pointer:A)),s.exports.sqlite3_declare_vtab&&s.xWrap.argAdapter("sqlite3_index_info*",A=>h(A instanceof(r.sqlite3_index_info||D)?A.pointer:A))("sqlite3_module*",A=>h(A instanceof(r.sqlite3_module||D)?A.pointer:A));const Q=s.xWrap.resultAdapter("*");s.xWrap.resultAdapter("sqlite3*",Q)("sqlite3_context*",Q)("sqlite3_stmt*",Q)("sqlite3_value*",Q)("sqlite3_vfs*",Q)("void*",Q);for(const A of c.core)r[A[0]]=s.xWrap.apply(null,A);for(const A of c.wasmInternal)_[A[0]]=s.xWrap.apply(null,A);for(const A of c.int64)r[A[0]]=s.bigIntEnabled?s.xWrap.apply(null,A):()=>t(A[0]+"() is unavailable due to lack","of BigInt support in this build.");delete c.core,delete c.int64,delete c.wasmInternal,_.sqlite3__wasm_db_error=function(A,N,J){return A?(N instanceof i.WasmAllocError?(N=r.SQLITE_NOMEM,J=0):N instanceof Error&&(J=J||""+N,N=N.resultCode||r.SQLITE_ERROR),r.sqlite3_set_errmsg(A,N,J)||N):r.SQLITE_MISUSE}}{const g=s.xCall("sqlite3__wasm_enum_json");g||t("Maintenance required: increase sqlite3__wasm_enum_json()'s","static buffer size!"),s.ctype=JSON.parse(s.cstrToJs(g));const h=["access","authorizer","blobFinalizers","changeset","config","dataTypes","dbConfig","dbStatus","encodings","fcntl","flock","ioCap","limits","openFlags","prepareFlags","resultCodes","sqlite3Status","stmtStatus","syncFlags","trace","txnState","udfFlags","version"];s.bigIntEnabled&&h.push("serialize","session","vtab");for(const A of h)for(const N of Object.entries(s.ctype[A]))r[N[0]]=N[1];s.functionEntry(r.SQLITE_WASM_DEALLOC)||t("Internal error: cannot resolve exported function","entry SQLITE_WASM_DEALLOC (=="+r.SQLITE_WASM_DEALLOC+").");const D=Object.create(null);for(const A of Object.entries(s.ctype.resultCodes))D[A[1]]=A[0];r.sqlite3_js_rc_str=A=>D[A];const Q=Object.assign(Object.create(null),{WasmTestStruct:!0,sqlite3_index_info:!s.bigIntEnabled,sqlite3_index_constraint:!s.bigIntEnabled,sqlite3_index_orderby:!s.bigIntEnabled,sqlite3_index_constraint_usage:!s.bigIntEnabled});for(const A of s.ctype.structs)Q[A.name]||(r[A.name]=i.StructBinder(A));if(r.sqlite3_index_info){for(const A of["sqlite3_index_constraint","sqlite3_index_orderby","sqlite3_index_constraint_usage"])r.sqlite3_index_info[A]=r[A],delete r[A];r.sqlite3_vtab_config=s.xWrap("sqlite3__wasm_vtab_config","int",["sqlite3*","int","int"])}}const b=(g,h,D)=>_.sqlite3__wasm_db_error(g,r.SQLITE_MISUSE,h+"() requires "+D+" argument"+(D===1?"":"s")+"."),M=g=>_.sqlite3__wasm_db_error(g,r.SQLITE_FORMAT,"SQLITE_UTF8 is the only supported encoding."),I=g=>s.xWrap.argAdapter("sqlite3*")(g),S=g=>s.isPtr(g)?s.cstrToJs(g):g,w=(function(g,h){g=I(g);let D=this.dbMap.get(g);if(h)!D&&h>0&&this.dbMap.set(g,D=Object.create(null));else return this.dbMap.delete(g),D;return D}).bind(Object.assign(Object.create(null),{dbMap:new Map}));w.addCollation=function(g,h){const D=w(g,1);D.collation||(D.collation=new Set),D.collation.add(S(h).toLowerCase())},w._addUDF=function(g,h,D,Q){h=S(h).toLowerCase();let A=Q.get(h);A||Q.set(h,A=new Set),A.add(D<0?-1:D)},w.addFunction=function(g,h,D){const Q=w(g,1);Q.udf||(Q.udf=new Map),this._addUDF(g,h,D,Q.udf)},s.exports.sqlite3_create_window_function&&(w.addWindowFunc=function(g,h,D){const Q=w(g,1);Q.wudf||(Q.wudf=new Map),this._addUDF(g,h,D,Q.wudf)}),w.cleanup=function(g){g=I(g);for(const Q of[["sqlite3_busy_handler",3],["sqlite3_commit_hook",3],["sqlite3_preupdate_hook",3],["sqlite3_progress_handler",4],["sqlite3_rollback_hook",3],["sqlite3_set_authorizer",3],["sqlite3_trace_v2",4],["sqlite3_update_hook",3]]){const[A,N]=Q;if(!s.exports[A])continue;const J=[g];J.length=N;try{r[A](...J)}catch(d){i.config.warn("close-time call of",A+"(",J,") threw:",d)}}const h=w(g,0);if(!h)return;if(h.collation){for(const Q of h.collation)try{r.sqlite3_create_collation_v2(g,Q,r.SQLITE_UTF8,0,0,0)}catch{}delete h.collation}let D;for(D=0;D<2;++D){const Q=D?h.wudf:h.udf;if(!Q)continue;const A=D?r.sqlite3_create_window_function:r.sqlite3_create_function_v2;for(const N of Q){const J=N[0],d=N[1],y=[g,J,0,r.SQLITE_UTF8,0,0,0,0,0];D&&y.push(0);for(const F of d)try{y[2]=F,A.apply(null,y)}catch{}d.clear()}Q.clear()}delete h.udf,delete h.wudf};{const g=s.xWrap("sqlite3_close_v2","int","sqlite3*");r.sqlite3_close_v2=function(h){if(arguments.length!==1)return b(h,"sqlite3_close_v2",1);if(h)try{w.cleanup(h)}catch{}return g(h)}}if(r.sqlite3session_create){const g=s.xWrap("sqlite3session_delete",void 0,["sqlite3_session*"]);r.sqlite3session_delete=function(h){if(arguments.length!==1)return b(pDb,"sqlite3session_delete",1);h&&r.sqlite3session_table_filter(h,0,0),g(h)}}{const g=(D,Q)=>"argv["+Q+"]:"+D[0]+":"+s.cstrToJs(D[1]).toLowerCase(),h=s.xWrap("sqlite3_create_collation_v2","int",["sqlite3*","string","int","*",new s.xWrap.FuncPtrAdapter({name:"xCompare",signature:"i(pipip)",contextKey:g}),new s.xWrap.FuncPtrAdapter({name:"xDestroy",signature:"v(p)",contextKey:g})]);r.sqlite3_create_collation_v2=function(D,Q,A,N,J,d){if(arguments.length!==6)return b(D,"sqlite3_create_collation_v2",6);if((A&15)===0)A|=r.SQLITE_UTF8;else if(r.SQLITE_UTF8!==(A&15))return M(D);try{const y=h(D,Q,A,N,J,d);return y===0&&J instanceof Function&&w.addCollation(D,Q),y}catch(y){return _.sqlite3__wasm_db_error(D,y)}},r.sqlite3_create_collation=(D,Q,A,N,J)=>arguments.length===5?r.sqlite3_create_collation_v2(D,Q,A,N,J,0):b(D,"sqlite3_create_collation",5)}{const g=function(A,N){return A[0]+":"+(A[2]<0?-1:A[2])+":"+N+":"+s.cstrToJs(A[1]).toLowerCase()},h=Object.assign(Object.create(null),{xInverseAndStep:{signature:"v(pip)",contextKey:g,callProxy:A=>(N,J,d)=>{try{A(N,...r.sqlite3_values_to_js(J,d))}catch(y){r.sqlite3_result_error_js(N,y)}}},xFinalAndValue:{signature:"v(p)",contextKey:g,callProxy:A=>N=>{try{r.sqlite3_result_js(N,A(N))}catch(J){r.sqlite3_result_error_js(N,J)}}},xFunc:{signature:"v(pip)",contextKey:g,callProxy:A=>(N,J,d)=>{try{r.sqlite3_result_js(N,A(N,...r.sqlite3_values_to_js(J,d)))}catch(y){r.sqlite3_result_error_js(N,y)}}},xDestroy:{signature:"v(p)",contextKey:g,callProxy:A=>N=>{try{A(N)}catch(J){console.error("UDF xDestroy method threw:",J)}}}}),D=s.xWrap("sqlite3_create_function_v2","int",["sqlite3*","string","int","int","*",new s.xWrap.FuncPtrAdapter({name:"xFunc",...h.xFunc}),new s.xWrap.FuncPtrAdapter({name:"xStep",...h.xInverseAndStep}),new s.xWrap.FuncPtrAdapter({name:"xFinal",...h.xFinalAndValue}),new s.xWrap.FuncPtrAdapter({name:"xDestroy",...h.xDestroy})]),Q=s.exports.sqlite3_create_window_function?s.xWrap("sqlite3_create_window_function","int",["sqlite3*","string","int","int","*",new s.xWrap.FuncPtrAdapter({name:"xStep",...h.xInverseAndStep}),new s.xWrap.FuncPtrAdapter({name:"xFinal",...h.xFinalAndValue}),new s.xWrap.FuncPtrAdapter({name:"xValue",...h.xFinalAndValue}),new s.xWrap.FuncPtrAdapter({name:"xInverse",...h.xInverseAndStep}),new s.xWrap.FuncPtrAdapter({name:"xDestroy",...h.xDestroy})]):void 0;r.sqlite3_create_function_v2=function A(N,J,d,y,F,W,P,X,ee){if(A.length!==arguments.length)return b(N,"sqlite3_create_function_v2",A.length);if((y&15)===0)y|=r.SQLITE_UTF8;else if(r.SQLITE_UTF8!==(y&15))return M(N);try{const Z=D(N,J,d,y,F,W,P,X,ee);return Z===0&&(W instanceof Function||P instanceof Function||X instanceof Function||ee instanceof Function)&&w.addFunction(N,J,d),Z}catch(Z){return console.error("sqlite3_create_function_v2() setup threw:",Z),_.sqlite3__wasm_db_error(N,Z,"Creation of UDF threw: "+Z)}},r.sqlite3_create_function=function A(N,J,d,y,F,W,P,X){return A.length===arguments.length?r.sqlite3_create_function_v2(N,J,d,y,F,W,P,X,0):b(N,"sqlite3_create_function",A.length)},Q?r.sqlite3_create_window_function=function A(N,J,d,y,F,W,P,X,ee,Z){if(A.length!==arguments.length)return b(N,"sqlite3_create_window_function",A.length);if((y&15)===0)y|=r.SQLITE_UTF8;else if(r.SQLITE_UTF8!==(y&15))return M(N);try{const te=Q(N,J,d,y,F,W,P,X,ee,Z);return te===0&&(W instanceof Function||P instanceof Function||X instanceof Function||ee instanceof Function||Z instanceof Function)&&w.addWindowFunc(N,J,d),te}catch(te){return console.error("sqlite3_create_window_function() setup threw:",te),_.sqlite3__wasm_db_error(N,te,"Creation of UDF threw: "+te)}}:delete r.sqlite3_create_window_function,r.sqlite3_create_function_v2.udfSetResult=r.sqlite3_create_function.udfSetResult=r.sqlite3_result_js,r.sqlite3_create_window_function&&(r.sqlite3_create_window_function.udfSetResult=r.sqlite3_result_js),r.sqlite3_create_function_v2.udfConvertArgs=r.sqlite3_create_function.udfConvertArgs=r.sqlite3_values_to_js,r.sqlite3_create_window_function&&(r.sqlite3_create_window_function.udfConvertArgs=r.sqlite3_values_to_js),r.sqlite3_create_function_v2.udfSetError=r.sqlite3_create_function.udfSetError=r.sqlite3_result_error_js,r.sqlite3_create_window_function&&(r.sqlite3_create_window_function.udfSetError=r.sqlite3_result_error_js)}{const g=(D,Q)=>(typeof D=="string"?Q=-1:_.isSQLableTypedArray(D)?(Q=D.byteLength,D=s.typedArrayToString(D instanceof ArrayBuffer?new Uint8Array(D):D)):Array.isArray(D)&&(D=D.join(""),Q=-1),[D,Q]),h={basic:s.xWrap("sqlite3_prepare_v3","int",["sqlite3*","string","int","int","**","**"]),full:s.xWrap("sqlite3_prepare_v3","int",["sqlite3*","*","int","int","**","**"])};r.sqlite3_prepare_v3=function D(Q,A,N,J,d,y){if(D.length!==arguments.length)return b(Q,"sqlite3_prepare_v3",D.length);const[F,W]=g(A,Number(N));switch(typeof F){case"string":return h.basic(Q,F,W,J,d,null);case typeof s.ptr.null:return h.full(Q,s.ptr.coerce(F),W,J,d,y);default:return _.sqlite3__wasm_db_error(Q,r.SQLITE_MISUSE,"Invalid SQL argument type for sqlite3_prepare_v2/v3(). typeof="+typeof F)}},r.sqlite3_prepare_v2=function D(Q,A,N,J,d){return D.length===arguments.length?r.sqlite3_prepare_v3(Q,A,N,0,J,d):b(Q,"sqlite3_prepare_v2",D.length)}}{const g=s.xWrap("sqlite3_bind_text","int",["sqlite3_stmt*","int","string","int","*"]),h=s.xWrap("sqlite3_bind_blob","int",["sqlite3_stmt*","int","*","int","*"]);r.sqlite3_bind_text=function D(Q,A,N,J,d){if(D.length!==arguments.length)return b(r.sqlite3_db_handle(Q),"sqlite3_bind_text",D.length);if(s.isPtr(N)||N===null)return g(Q,A,N,J,d);N instanceof ArrayBuffer?N=new Uint8Array(N):Array.isArray(pMem)&&(N=pMem.join(""));let y,F;try{if(_.isSQLableTypedArray(N))y=s.allocFromTypedArray(N),F=N.byteLength;else if(typeof N=="string")[y,F]=s.allocCString(N);else return _.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),r.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_text().");return g(Q,A,y,F,r.SQLITE_WASM_DEALLOC)}catch(W){return s.dealloc(y),_.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),W)}},r.sqlite3_bind_blob=function D(Q,A,N,J,d){if(D.length!==arguments.length)return b(r.sqlite3_db_handle(Q),"sqlite3_bind_blob",D.length);if(s.isPtr(N)||N===null)return h(Q,A,N,J,d);N instanceof ArrayBuffer?N=new Uint8Array(N):Array.isArray(N)&&(N=N.join(""));let y,F;try{if(_.isBindableTypedArray(N))y=s.allocFromTypedArray(N),F=J>=0?J:N.byteLength;else if(typeof N=="string")[y,F]=s.allocCString(N);else return _.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),r.SQLITE_MISUSE,"Invalid 3rd argument type for sqlite3_bind_blob().");return h(Q,A,y,F,r.SQLITE_WASM_DEALLOC)}catch(W){return s.dealloc(y),_.sqlite3__wasm_db_error(r.sqlite3_db_handle(Q),W)}}}if(!r.sqlite3_column_text){const g=s.xWrap.argAdapter("sqlite3_stmt*"),h=s.xWrap.argAdapter("int"),D=s.xWrap.argAdapter("sqlite3_value*"),Q=(A,N)=>s.typedArrayToString(s.heap8u(),Number(A),Number(A)+N);r.sqlite3_column_text=function(A,N){const J=g(A),d=h(N),y=s.exports.sqlite3_column_text(J,d);return y?Q(y,s.exports.sqlite3_column_bytes(J,d)):null},r.sqlite3_value_text=function(A){const N=D(A),J=s.exports.sqlite3_value_text(N);return J?Q(J,s.exports.sqlite3_value_bytes(N)):null}}r.sqlite3_config=function(g,...h){if(arguments.length<2)return r.SQLITE_MISUSE;switch(g){case r.SQLITE_CONFIG_COVERING_INDEX_SCAN:case r.SQLITE_CONFIG_MEMSTATUS:case r.SQLITE_CONFIG_SMALL_MALLOC:case r.SQLITE_CONFIG_SORTERREF_SIZE:case r.SQLITE_CONFIG_STMTJRNL_SPILL:case r.SQLITE_CONFIG_URI:return s.exports.sqlite3__wasm_config_i(g,h[0]);case r.SQLITE_CONFIG_LOOKASIDE:return s.exports.sqlite3__wasm_config_ii(g,h[0],h[1]);case r.SQLITE_CONFIG_MEMDB_MAXSIZE:return s.exports.sqlite3__wasm_config_j(g,h[0]);case r.SQLITE_CONFIG_GETMALLOC:case r.SQLITE_CONFIG_GETMUTEX:case r.SQLITE_CONFIG_GETPCACHE2:case r.SQLITE_CONFIG_GETPCACHE:case r.SQLITE_CONFIG_HEAP:case r.SQLITE_CONFIG_LOG:case r.SQLITE_CONFIG_MALLOC:case r.SQLITE_CONFIG_MMAP_SIZE:case r.SQLITE_CONFIG_MULTITHREAD:case r.SQLITE_CONFIG_MUTEX:case r.SQLITE_CONFIG_PAGECACHE:case r.SQLITE_CONFIG_PCACHE2:case r.SQLITE_CONFIG_PCACHE:case r.SQLITE_CONFIG_PCACHE_HDRSZ:case r.SQLITE_CONFIG_PMASZ:case r.SQLITE_CONFIG_SERIALIZED:case r.SQLITE_CONFIG_SINGLETHREAD:case r.SQLITE_CONFIG_SQLLOG:case r.SQLITE_CONFIG_WIN32_HEAPSIZE:default:return r.SQLITE_NOTFOUND}};{const g=new Set;r.sqlite3_auto_extension=function(h){if(h instanceof Function)h=s.installFunction("i(ppp)",h);else if(arguments.length!==1||!s.isPtr(h))return r.SQLITE_MISUSE;const D=s.exports.sqlite3_auto_extension(h);return h!==arguments[0]&&(D===0?g.add(h):s.uninstallFunction(h)),D},r.sqlite3_cancel_auto_extension=function(h){return!h||arguments.length!==1||!s.isPtr(h)?0:s.exports.sqlite3_cancel_auto_extension(h)},r.sqlite3_reset_auto_extension=function(){s.exports.sqlite3_reset_auto_extension();for(const h of g)s.uninstallFunction(h);g.clear()}}s.xWrap.FuncPtrAdapter.warnOnUse=!0;const x=i.StructBinder,L=function g(h,D,Q,A=g.installMethodArgcCheck){if(h instanceof x.StructType?!(Q instanceof Function)&&!s.isPtr(Q)&&t("Usage error: expecting a Function or WASM pointer to one."):t("Usage error: target object is-not-a StructType."),arguments.length===1)return(y,F)=>g(h,y,F,A);g.argcProxy||(g.argcProxy=function(y,F,W,P){return function(...X){return W.length!==arguments.length&&t("Argument mismatch for",y.structInfo.name+"::"+F+": Native signature is:",P),W.apply(this,X)}},g.removeFuncList=function(){this.ondispose.__removeFuncList&&(this.ondispose.__removeFuncList.forEach((y,F)=>{if(s.isPtr(y))try{s.uninstallFunction(y)}catch{}}),delete this.ondispose.__removeFuncList)});const N=h.memberSignature(D);N.length<2&&t("Member",D,"does not have a function pointer signature:",N);const J=h.memberKey(D),d=A&&!s.isPtr(Q)?g.argcProxy(h,J,Q,N):Q;if(s.isPtr(d))d&&!s.functionEntry(d)&&t("Pointer",d,"is not a WASM function table entry."),h[J]=d;else{const y=s.installFunction(d,N);h[J]=y,(!h.ondispose||!h.ondispose.__removeFuncList)&&(h.addOnDispose("ondispose.__removeFuncList handler",g.removeFuncList),h.ondispose.__removeFuncList=[]),h.ondispose.__removeFuncList.push(J,y)}return(y,F)=>g(h,y,F,A)};L.installMethodArgcCheck=!1;const H=function(g,h,D=L.installMethodArgcCheck){const Q=new Map;for(const A of Object.keys(h)){const N=h[A],J=Q.get(N);if(J){const d=g.memberKey(A);g[d]=g[g.memberKey(J)]}else L(g,A,N,D),Q.set(N,A)}return g};x.StructType.prototype.installMethod=function(h,D,Q=L.installMethodArgcCheck){return arguments.length<3&&h&&typeof h=="object"?H(this,...arguments):L(this,...arguments)},x.StructType.prototype.installMethods=function(g,h=L.installMethodArgcCheck){return H(this,g,h)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){const t=(...E)=>{throw new i.SQLite3Error(...E)},r=i.capi,s=i.wasm,_=i.util,c=function(E){return(...o)=>E("sqlite3.oo1:",...o)};i.__isUnderTest?c(console.debug.bind(console)):c(i.config.debug),i.__isUnderTest?c(console.warn.bind(console)):c(i.config.warn),i.__isUnderTest?c(console.error.bind(console)):c(i.config.error);const b=new WeakMap,M=new Set,I=new WeakMap,S=(E,o,u)=>{const p=Object.getOwnPropertyDescriptor(E,o);return p?p.value:u},w=function(E,o){return o&&(E instanceof g&&(E=E.pointer),t(o,"sqlite3 result code",o+":",E?r.sqlite3_errmsg(E):r.sqlite3_errstr(o))),arguments[0]},x=s.installFunction("i(ippp)",(function(E,o,u,p){r.SQLITE_TRACE_STMT===E&&console.log("SQL TRACE #"+ ++this.counter,"via sqlite3@"+o+"["+r.sqlite3_db_filename(o,null)+"]",s.cstrToJs(p))}).bind({counter:0})),L=Object.create(null),H=function E(...o){const u=E.normalizeArgs(...o);let p;if(p=u["sqlite3*"])u["sqlite3*:takeOwnership"]||M.add(this),this.filename=r.sqlite3_db_filename(p,"main");else{let q=u.filename,z=u.vfs,V=u.flags;(typeof q!="string"&&!s.isPtr(q)||typeof V!="string"||z&&typeof z!="string"&&!s.isPtr(z))&&(i.config.error("Invalid DB ctor args",u,arguments),t("Invalid arguments for DB constructor:",arguments,"opts:",u));let R=0;V.indexOf("c")>=0&&(R|=r.SQLITE_OPEN_CREATE|r.SQLITE_OPEN_READWRITE),V.indexOf("w")>=0&&(R|=r.SQLITE_OPEN_READWRITE),R===0&&(R|=r.SQLITE_OPEN_READONLY),R|=r.SQLITE_OPEN_EXRESCODE;const m=s.pstack.pointer;try{const C=s.pstack.allocPtr();let B=r.sqlite3_open_v2(q,C,R,z||s.ptr.null);p=s.peekPtr(C),w(p,B),r.sqlite3_extended_result_codes(p,1),V.indexOf("t")>=0&&r.sqlite3_trace_v2(p,r.SQLITE_TRACE_STMT,x,p)}catch(C){throw p&&r.sqlite3_close_v2(p),C}finally{s.pstack.restore(m)}this.filename=s.isPtr(q)?s.cstrToJs(q):q}if(b.set(this,p),I.set(this,Object.create(null)),!u["sqlite3*"])try{const q=L[r.sqlite3_js_db_vfs(p)||t("Internal error: cannot get VFS for new db handle.")];q&&(q instanceof Function?q(this,i):w(p,r.sqlite3_exec(p,q,0,0,0)))}catch(q){throw this.close(),q}};H.setVfsPostOpenCallback=function(E,o){o instanceof Function||t("dbCtorHelper.setVfsPostOpenCallback() should not be used with a non-function argument.",arguments),L[E]=o},H.normalizeArgs=function(E=":memory:",o="c",u=null){const p={};return arguments.length===1&&arguments[0]&&typeof arguments[0]=="object"?(Object.assign(p,arguments[0]),p.flags===void 0&&(p.flags="c"),p.vfs===void 0&&(p.vfs=null),p.filename===void 0&&(p.filename=":memory:")):(p.filename=E,p.flags=o,p.vfs=u),p};const g=function(...E){H.apply(this,E)};g.dbCtorHelper=H;const h={null:1,number:2,string:3,boolean:4,blob:5};s.bigIntEnabled&&(h.bigint=h.number);const D=function(){h!==arguments[2]&&t(r.SQLITE_MISUSE,"Do not call the Stmt constructor directly. Use DB.prepare()."),this.db=arguments[0],b.set(this,arguments[1]),arguments.length>3&&!arguments[3]&&M.add(this)},Q=function(E){return E.pointer||t("DB has been closed."),E},A=function(E,o){return(o!==(o|0)||o<0||o>=E.columnCount)&&t("Column index",o,"is out of range."),E},N=function(E,o){const u=Object.create(null);switch(u.opt=Object.create(null),o.length){case 1:typeof o[0]=="string"||_.isSQLableTypedArray(o[0])||Array.isArray(o[0])?u.sql=o[0]:o[0]&&typeof o[0]=="object"&&(u.opt=o[0],u.sql=u.opt.sql);break;case 2:u.sql=o[0],u.opt=o[1];break;default:t("Invalid argument count for exec().")}u.sql=_.flexibleString(u.sql),typeof u.sql!="string"&&t("Missing SQL argument or unsupported SQL value type.");const p=u.opt;switch(p.returnValue){case"resultRows":p.resultRows||(p.resultRows=[]),u.returnVal=()=>p.resultRows;break;case"saveSql":p.saveSql||(p.saveSql=[]),u.returnVal=()=>p.saveSql;break;case void 0:case"this":u.returnVal=()=>E;break;default:t("Invalid returnValue value:",p.returnValue)}if(!p.callback&&!p.returnValue&&p.rowMode!==void 0&&(p.resultRows||(p.resultRows=[]),u.returnVal=()=>p.resultRows),p.callback||p.resultRows)switch(p.rowMode===void 0?"array":p.rowMode){case"object":u.cbArg=(q,z)=>{z.columnNames||(z.columnNames=q.getColumnNames([]));const V=q.get([]),R=Object.create(null);for(const m in z.columnNames)R[z.columnNames[m]]=V[m];return R};break;case"array":u.cbArg=q=>q.get([]);break;case"stmt":Array.isArray(p.resultRows)&&t("exec(): invalid rowMode for a resultRows array: must","be one of 'array', 'object',","a result column number, or column name reference."),u.cbArg=q=>q;break;default:if(_.isInt32(p.rowMode)){u.cbArg=q=>q.get(p.rowMode);break}else if(typeof p.rowMode=="string"&&p.rowMode.length>1&&p.rowMode[0]==="$"){const q=p.rowMode.substr(1);u.cbArg=z=>{const V=z.get(Object.create(null))[q];return V===void 0?t(r.SQLITE_NOTFOUND,"exec(): unknown result column:",q):V};break}t("Invalid rowMode:",p.rowMode)}return u},J=(E,o,u,...p)=>{const q=E.prepare(o);try{const z=q.bind(u).step()?q.get(...p):void 0;return q.reset(),z}finally{q.finalize()}},d=(E,o,u,p)=>E.exec({sql:o,bind:u,rowMode:p,returnValue:"resultRows"});g.checkRc=(E,o)=>w(E,o),g.prototype={isOpen:function(){return!!this.pointer},affirmOpen:function(){return Q(this)},close:function(){const E=this.pointer;if(E){if(this.onclose&&this.onclose.before instanceof Function)try{this.onclose.before(this)}catch{}if(Object.keys(I.get(this)).forEach((o,u)=>{if(u&&u.pointer)try{u.finalize()}catch{}}),b.delete(this),I.delete(this),M.delete(this)||r.sqlite3_close_v2(E),this.onclose&&this.onclose.after instanceof Function)try{this.onclose.after(this)}catch{}delete this.filename}},changes:function(E=!1,o=!1){const u=Q(this).pointer;return E?o?r.sqlite3_total_changes64(u):r.sqlite3_total_changes(u):o?r.sqlite3_changes64(u):r.sqlite3_changes(u)},dbFilename:function(E="main"){return r.sqlite3_db_filename(Q(this).pointer,E)},dbName:function(E=0){return r.sqlite3_db_name(Q(this).pointer,E)},dbVfsName:function(E=0){let o;const u=r.sqlite3_js_db_vfs(Q(this).pointer,E);if(u){const p=new r.sqlite3_vfs(u);try{o=s.cstrToJs(p.$zName)}finally{p.dispose()}}return o},prepare:function(E){Q(this);const o=s.pstack.pointer;let u,p;try{u=s.pstack.alloc(8),g.checkRc(this,r.sqlite3_prepare_v2(this.pointer,E,-1,u,null)),p=s.peekPtr(u)}finally{s.pstack.restore(o)}p||t("Cannot prepare empty SQL.");const q=new D(this,p,h);return I.get(this)[p]=q,q},exec:function(){Q(this);const E=N(this,arguments);if(!E.sql)return t("exec() requires an SQL string.");const o=E.opt,u=o.callback,p=Array.isArray(o.resultRows)?o.resultRows:void 0;let q,z=o.bind,V=!!(E.cbArg||o.columnNames||p);const R=s.scopedAllocPush(),m=Array.isArray(o.saveSql)?o.saveSql:void 0;try{const C=_.isSQLableTypedArray(E.sql);let B=C?E.sql.byteLength:s.jstrlen(E.sql);const Y=s.scopedAlloc(2*s.ptr.size+(B+1)),ne=s.ptr.add(Y,s.ptr.size);let ae=s.ptr.add(ne,s.ptr.size);const ce=s.ptr.add(ae,B);for(C?s.heap8().set(E.sql,ae):s.jstrcpy(E.sql,s.heap8(),ae,B,!1),s.poke8(s.ptr.add(ae,B),0);ae&&s.peek8(ae);){s.pokePtr([Y,ne],0),g.checkRc(this,r.sqlite3_prepare_v3(this.pointer,ae,B,0,Y,ne));const ke=s.peekPtr(Y);if(ae=s.peekPtr(ne),B=Number(s.ptr.add(ce,-ae)),!!ke){if(m&&m.push(r.sqlite3_sql(ke).trim()),q=new D(this,ke,h),z&&q.parameterCount&&(q.bind(z),z=null),V&&q.columnCount){let Ne=Array.isArray(o.columnNames)?0:1;if(V=!1,E.cbArg||p){const Xe=Object.create(null);for(;q.step();X.delete(q)){Ne++===0&&q.getColumnNames(Xe.columnNames=o.columnNames||[]),X.add(q);const at=E.cbArg(q,Xe);if(p&&p.push(at),u&&u.call(o,at,q)===!1)break}X.delete(q)}Ne===0&&q.getColumnNames(o.columnNames)}else q.step();q.reset().finalize(),q=null}}}finally{q&&(X.delete(q),q.finalize()),s.scopedAllocPop(R)}return E.returnVal()},createFunction:function(o,u,p){const q=Xe=>Xe instanceof Function;switch(arguments.length){case 1:p=o,o=p.name,u=p.xFunc||0;break;case 2:q(u)||(p=u,u=p.xFunc||0);break}p||(p={}),typeof o!="string"&&t("Invalid arguments: missing function name.");let z=p.xStep||0,V=p.xFinal||0;const R=p.xValue||0,m=p.xInverse||0;let C;q(u)?(C=!1,(q(z)||q(V))&&t("Ambiguous arguments: scalar or aggregate?"),z=V=null):q(z)?(q(V)||t("Missing xFinal() callback for aggregate or window UDF."),u=null):q(V)?t("Missing xStep() callback for aggregate or window UDF."):t("Missing function-type properties."),C===!1?(q(R)||q(m))&&t("xValue and xInverse are not permitted for non-window UDFs."):q(R)?(q(m)||t("xInverse must be provided if xValue is."),C=!0):q(m)&&t("xValue must be provided if xInverse is.");const B=p.pApp;B!=null&&!s.isPtr(B)&&t("Invalid value for pApp property. Must be a legal WASM pointer value.");const Y=p.xDestroy||0;Y&&!q(Y)&&t("xDestroy property must be a function.");let ne=0;S(p,"deterministic")&&(ne|=r.SQLITE_DETERMINISTIC),S(p,"directOnly")&&(ne|=r.SQLITE_DIRECTONLY),S(p,"innocuous")&&(ne|=r.SQLITE_INNOCUOUS),o=o.toLowerCase();const ae=u||z,ce=S(p,"arity"),ke=typeof ce=="number"?ce:ae.length?ae.length-1:0;let Ne;return C?Ne=r.sqlite3_create_window_function(this.pointer,o,ke,r.SQLITE_UTF8|ne,B||0,z,V,R,m,Y):Ne=r.sqlite3_create_function_v2(this.pointer,o,ke,r.SQLITE_UTF8|ne,B||0,u,z,V,Y),g.checkRc(this,Ne),this},selectValue:function(E,o,u){return J(this,E,o,0,u)},selectValues:function(E,o,u){const p=this.prepare(E),q=[];try{for(p.bind(o);p.step();)q.push(p.get(0,u));p.reset()}finally{p.finalize()}return q},selectArray:function(E,o){return J(this,E,o,[])},selectObject:function(E,o){return J(this,E,o,{})},selectArrays:function(E,o){return d(this,E,o,"array")},selectObjects:function(E,o){return d(this,E,o,"object")},openStatementCount:function(){return this.pointer?Object.keys(I.get(this)).length:0},transaction:function(E){let o="BEGIN";arguments.length>1&&(/[^a-zA-Z]/.test(arguments[0])&&t(r.SQLITE_MISUSE,"Invalid argument for BEGIN qualifier."),o+=" "+arguments[0],E=arguments[1]),Q(this).exec(o);try{const u=E(this);return this.exec("COMMIT"),u}catch(u){throw this.exec("ROLLBACK"),u}},savepoint:function(E){Q(this).exec("SAVEPOINT oo1");try{const o=E(this);return this.exec("RELEASE oo1"),o}catch(o){throw this.exec("ROLLBACK to SAVEPOINT oo1; RELEASE SAVEPOINT oo1"),o}},checkRc:function(E){return w(this,E)}},g.wrapHandle=function(E,o=!1){if(!E||!s.isPtr(E))throw new i.SQLite3Error(r.SQLITE_MISUSE,"Argument must be a WASM sqlite3 pointer");return new g({"sqlite3*":E,"sqlite3*:takeOwnership":!!o})};const y=function(E){return E.pointer||t("Stmt has been closed."),E},F=function(E){let o=h[E==null?"null":typeof E];switch(o){case h.boolean:case h.null:case h.number:case h.string:return o;case h.bigint:return s.bigIntEnabled?o:void 0;default:return _.isBindableTypedArray(E)?h.blob:void 0}},W=function(E){return F(E)||t("Unsupported bind() argument type:",typeof E)},P=function(E,o){const u=typeof o=="number"?o:r.sqlite3_bind_parameter_index(E.pointer,o);return u===0||!_.isInt32(u)?t("Invalid bind() parameter name: "+o):(u<1||u>E.parameterCount)&&t("Bind index",o,"is out of range."),u},X=new Set,ee=new Set,Z=function(E,o){return X.has(E)&&t("Operation is illegal when statement is locked:",o),E},te=function E(o,u,p,q){Z(y(o),"bind()"),E._||(E._tooBigInt=V=>t("BigInt value is too big to store without precision loss:",V),E._={string:function(V,R,m,C){const[B,Y]=s.allocCString(m,!0);return(C?r.sqlite3_bind_blob:r.sqlite3_bind_text)(V.pointer,R,B,Y,r.SQLITE_WASM_DEALLOC)}}),W(q),u=P(o,u);let z=0;switch(q==null?h.null:p){case h.null:z=r.sqlite3_bind_null(o.pointer,u);break;case h.string:z=E._.string(o,u,q,!1);break;case h.number:{let V;_.isInt32(q)?V=r.sqlite3_bind_int:typeof q=="bigint"?_.bigIntFits64(q)?s.bigIntEnabled?V=r.sqlite3_bind_int64:_.bigIntFitsDouble(q)?(q=Number(q),V=r.sqlite3_bind_double):E._tooBigInt(q):E._tooBigInt(q):(q=Number(q),s.bigIntEnabled&&Number.isInteger(q)?V=r.sqlite3_bind_int64:V=r.sqlite3_bind_double),z=V(o.pointer,u,q);break}case h.boolean:z=r.sqlite3_bind_int(o.pointer,u,q?1:0);break;case h.blob:{if(typeof q=="string"){z=E._.string(o,u,q,!0);break}else q instanceof ArrayBuffer?q=new Uint8Array(q):_.isBindableTypedArray(q)||t("Binding a value as a blob requires","that it be a string, Uint8Array, Int8Array, or ArrayBuffer.");const V=s.alloc(q.byteLength||1);s.heap8().set(q.byteLength?q:[0],Number(V)),z=r.sqlite3_bind_blob(o.pointer,u,V,q.byteLength,r.SQLITE_WASM_DEALLOC);break}default:i.config.warn("Unsupported bind() argument type:",q),t("Unsupported bind() argument type: "+typeof q)}return z&&g.checkRc(o.db.pointer,z),o};D.prototype={finalize:function(){const E=this.pointer;if(E){Z(this,"finalize()");const o=M.delete(this)?0:r.sqlite3_finalize(E);return delete I.get(this.db)[E],b.delete(this),X.delete(this),ee.delete(this),delete this.parameterCount,delete this.db,o}},clearBindings:function(){return Z(y(this),"clearBindings()"),r.sqlite3_clear_bindings(this.pointer),ee.delete(this),this},reset:function(E){Z(this,"reset()"),E&&this.clearBindings();const o=r.sqlite3_reset(y(this).pointer);return ee.delete(this),w(this.db,o),this},bind:function(){y(this);let E,o;switch(arguments.length){case 1:E=1,o=arguments[0];break;case 2:E=arguments[0],o=arguments[1];break;default:t("Invalid bind() arguments.")}return o===void 0?this:(this.parameterCount||t("This statement has no bindable parameters."),ee.delete(this),o===null?te(this,E,h.null,o):Array.isArray(o)?(arguments.length!==1&&t("When binding an array, an index argument is not permitted."),o.forEach((u,p)=>te(this,p+1,W(u),u)),this):(o instanceof ArrayBuffer&&(o=new Uint8Array(o)),typeof o=="object"&&!_.isBindableTypedArray(o)?(arguments.length!==1&&t("When binding an object, an index argument is not permitted."),Object.keys(o).forEach(u=>te(this,u,W(o[u]),o[u])),this):te(this,E,W(o),o)))},bindAsBlob:function(E,o){y(this),arguments.length===1&&(o=E,E=1);const u=W(o);return h.string!==u&&h.blob!==u&&h.null!==u&&t("Invalid value type for bindAsBlob()"),te(this,E,h.blob,o)},step:function(){Z(this,"step()");const E=r.sqlite3_step(y(this).pointer);switch(E){case r.SQLITE_DONE:return ee.delete(this),!1;case r.SQLITE_ROW:return ee.add(this),!0;default:ee.delete(this),i.config.warn("sqlite3_step() rc=",E,r.sqlite3_js_rc_str(E),"SQL =",r.sqlite3_sql(this.pointer)),g.checkRc(this.db.pointer,E)}},stepReset:function(){return this.step(),this.reset()},stepFinalize:function(){try{const E=this.step();return this.reset(),E}finally{try{this.finalize()}catch{}}},get:function(E,o){if(ee.has(y(this))||t("Stmt.step() has not (recently) returned true."),Array.isArray(E)){let u=0;const p=this.columnCount;for(;u=Number.MIN_SAFE_INTEGER&&u<=Number.MAX_SAFE_INTEGER?Number(u).valueOf():u}else{const u=r.sqlite3_column_double(this.pointer,E);return(u>Number.MAX_SAFE_INTEGER||ut("The pointer property is read-only.")};Object.defineProperty(D.prototype,"pointer",E),Object.defineProperty(g.prototype,"pointer",E)}Object.defineProperty(D.prototype,"columnCount",{enumerable:!1,get:function(){return r.sqlite3_column_count(this.pointer)},set:()=>t("The columnCount property is read-only.")}),Object.defineProperty(D.prototype,"parameterCount",{enumerable:!1,get:function(){return r.sqlite3_bind_parameter_count(this.pointer)},set:()=>t("The parameterCount property is read-only.")}),D.wrapHandle=function(E,o,u=!1){if(!(E instanceof g)||!E.pointer)throw new i.SQLite3Error(i.SQLITE_MISUSE,"First argument must be an opened sqlite3.oo1.DB instance");if(!o||!s.isPtr(o))throw new i.SQLite3Error(i.SQLITE_MISUSE,"Second argument must be a WASM sqlite3_stmt pointer");return new D(E,o,h,!!u)},i.oo1={DB:g,Stmt:D}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){const t=i.util;i.initWorker1API=(function(){const r=(...x)=>{throw new Error(x.join(" "))};globalThis.WorkerGlobalScope instanceof Function||r("initWorker1API() must be run from a Worker thread.");const s=this.sqlite3||r("Missing this.sqlite3 object."),_=s.oo1.DB,c=function(x){let L=b.idMap.get(x);return L||(L="db#"+ ++b.idSeq+":"+Math.floor(Math.random()*1e8)+":"+Math.floor(Math.random()*1e8),b.idMap.set(x,L),L)},b={dbList:[],idSeq:0,idMap:new WeakMap,xfer:[],open:function(x){const L=new _(x);return this.dbs[c(L)]=L,this.dbList.indexOf(L)<0&&this.dbList.push(L),L},close:function(x,L){if(x){delete this.dbs[c(x)];const H=x.filename,g=t.sqlite3__wasm_db_vfs(x.pointer,0);x.close();const h=this.dbList.indexOf(x);h>=0&&this.dbList.splice(h,1),L&&H&&g&&t.sqlite3__wasm_vfs_unlink(g,H)}},post:function(x,L){L&&L.length?(globalThis.postMessage(x,Array.from(L)),L.length=0):globalThis.postMessage(x)},dbs:Object.create(null),getDb:function(x,L=!0){return this.dbs[x]||(L?r("Unknown (or closed) DB ID:",x):void 0)}},M=function(x=b.dbList[0]){return x&&x.pointer?x:r("DB is not opened.")},I=function(x,L=!0){const H=b.getDb(x.dbId,!1)||b.dbList[0];return L?M(H):H},S=function(){return b.dbList[0]&&c(b.dbList[0])},w={open:function(x){const L=Object.create(null),H=x.args||Object.create(null);H.simulateError&&r("Throwing because of simulateError flag.");const g=Object.create(null);L.vfs=H.vfs,L.filename=H.filename||"";const h=b.open(L);return g.filename=h.filename,g.persistent=!!s.capi.sqlite3_js_db_uses_vfs(h.pointer,"opfs"),g.dbId=c(h),g.vfs=h.dbVfsName(),g},close:function(x){const L=I(x,!1),H={filename:L&&L.filename};if(L){const g=x.args&&typeof x.args=="object"?!!x.args.unlink:!1;b.close(L,g)}return H},exec:function(x){const L=typeof x.args=="string"?{sql:x.args}:x.args||Object.create(null);L.rowMode==="stmt"?r("Invalid rowMode for 'exec': stmt mode","does not work in the Worker API."):L.sql||r("'exec' requires input SQL.");const H=I(x);(L.callback||Array.isArray(L.resultRows))&&(H._blobXfer=b.xfer);const g=L.callback;let h=0;const D=!!L.columnNames;typeof g=="string"&&(D||(L.columnNames=[]),L.callback=function(Q,A){b.post({type:g,columnNames:L.columnNames,rowNumber:++h,row:Q},b.xfer)});try{const Q=L.countChanges?H.changes(!0,L.countChanges===64):void 0;H.exec(L),Q!==void 0&&(L.changeCount=H.changes(!0,L.countChanges===64)-Q);const A=L.lastInsertRowId?s.capi.sqlite3_last_insert_rowid(H):void 0;A!==void 0&&(L.lastInsertRowId=A),L.callback instanceof Function&&(L.callback=g,b.post({type:g,columnNames:L.columnNames,rowNumber:null,row:void 0}))}finally{delete H._blobXfer,L.callback&&(L.callback=g)}return L},"config-get":function(){const x=Object.create(null),L=s.config;return["bigIntEnabled"].forEach(function(H){Object.getOwnPropertyDescriptor(L,H)&&(x[H]=L[H])}),x.version=s.version,x.vfsList=s.capi.sqlite3_js_vfs_list(),x},export:function(x){const L=I(x),H={byteArray:s.capi.sqlite3_js_db_export(L.pointer),filename:L.filename,mimetype:"application/x-sqlite3"};return b.xfer.push(H.byteArray.buffer),H},toss:function(x){r("Testing worker exception")}};globalThis.onmessage=async function(x){x=x.data;let L,H=x.dbId,g=x.type;const h=performance.now();try{w.hasOwnProperty(g)&&w[g]instanceof Function?L=await w[g](x):r("Unknown db worker message type:",x.type)}catch(D){g="error",L={operation:x.type,message:D.message,errorClass:D.name,input:x},D.stack&&(L.stack=typeof D.stack=="string"?D.stack.split(/\n\s*/):D.stack)}H||(H=L.dbId||S()),b.post({type:g,dbId:H,messageId:x.messageId,workerReceivedTime:h,workerRespondTime:performance.now(),departureTime:x.departureTime,result:L},b.xfer)},globalThis.postMessage({type:"sqlite3-api",result:"worker1-ready"})}).bind({sqlite3:i})}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){const t=i.wasm,r=i.capi,s=i.util.toss3,_=Object.create(null);i.vfs=_,r.sqlite3_vfs.prototype.registerVfs=function(c=!1){this instanceof i.capi.sqlite3_vfs||s("Expecting a sqlite3_vfs-type argument.");const b=r.sqlite3_vfs_register(this,c?1:0);return b&&s("sqlite3_vfs_register(",this,") failed with rc",b),this.pointer!==r.sqlite3_vfs_find(this.$zName)&&s("BUG: sqlite3_vfs_find(vfs.$zName) failed for just-installed VFS",this),this},_.installVfs=function(c){let b=0;const M=["io","vfs"];for(const I of M){const S=c[I];S&&(++b,S.struct.installMethods(S.methods,!!S.applyArgcCheck),I==="vfs"&&(!S.struct.$zName&&typeof S.name=="string"&&S.struct.addOnDispose(S.struct.$zName=t.allocCString(S.name)),S.struct.registerVfs(!!S.asDefault)))}return b||s("Misuse: installVfs() options object requires at least","one of:",M),this}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(!i.wasm.exports.sqlite3_declare_vtab)return;const t=i.wasm,r=i.capi,s=i.util.toss3,_=Object.create(null);i.vtab=_;const c=r.sqlite3_index_info;c.prototype.nthConstraint=function(I,S=!1){if(I<0||I>=this.$nConstraint)return!1;const w=t.ptr.add(this.$aConstraint,c.sqlite3_index_constraint.structInfo.sizeof*I);return S?w:new c.sqlite3_index_constraint(w)},c.prototype.nthConstraintUsage=function(I,S=!1){if(I<0||I>=this.$nConstraint)return!1;const w=t.ptr.add(this.$aConstraintUsage,c.sqlite3_index_constraint_usage.structInfo.sizeof*I);return S?w:new c.sqlite3_index_constraint_usage(w)},c.prototype.nthOrderBy=function(I,S=!1){if(I<0||I>=this.$nOrderBy)return!1;const w=t.ptr.add(this.$aOrderBy,c.sqlite3_index_orderby.structInfo.sizeof*I);return S?w:new c.sqlite3_index_orderby(w)};const b=function(I,S){return(function(w,x=!1){if(arguments.length===0&&(w=new S),w instanceof S)return this.set(w.pointer,w),w;t.isPtr(w)||i.SQLite3Error.toss("Invalid argument to",I+"()");let L=this.get(w);return x&&this.delete(w),L}).bind(new Map)},M=function(I,S){const w=b(I,S);return Object.assign(Object.create(null),{StructType:S,create:x=>{const L=w();return t.pokePtr(x,L.pointer),L},get:x=>w(x),unget:x=>w(x,!0),dispose:x=>w(x,!0)?.dispose?.()})};_.xVtab=M("xVtab",r.sqlite3_vtab),_.xCursor=M("xCursor",r.sqlite3_vtab_cursor),_.xIndexInfo=I=>new r.sqlite3_index_info(I),_.xError=function I(S,w,x){if(I.errorReporter instanceof Function)try{I.errorReporter("sqlite3_module::"+S+"(): "+w.message)}catch{}let L;return w instanceof i.WasmAllocError?L=r.SQLITE_NOMEM:arguments.length>2?L=x:w instanceof i.SQLite3Error&&(L=w.resultCode),L||r.SQLITE_ERROR},_.xError.errorReporter=i.config.error.bind(i.config),_.xRowid=(I,S)=>t.poke(I,S,"i64"),_.setupModule=function(I){let S=!1;const w=this instanceof r.sqlite3_module?this:I.struct||(S=new r.sqlite3_module);try{const x=I.methods||s("Missing 'methods' object.");for(const L of Object.entries({xConnect:"xCreate",xDisconnect:"xDestroy"})){const H=L[0],g=L[1];x[H]===!0?x[H]=x[g]:x[g]===!0&&(x[g]=x[H])}if(I.catchExceptions){const L=function(h,D){return["xConnect","xCreate"].indexOf(h)>=0?function(Q,A,N,J,d,y){try{return D(...arguments)||0}catch(F){return F instanceof i.WasmAllocError||(t.dealloc(t.peekPtr(y)),t.pokePtr(y,t.allocCString(F.message))),_.xError(h,F)}}:function(...Q){try{return D(...Q)||0}catch(A){return _.xError(h,A)}}},H=["xCreate","xConnect","xBestIndex","xDisconnect","xDestroy","xOpen","xClose","xFilter","xNext","xEof","xColumn","xRowid","xUpdate","xBegin","xSync","xCommit","xRollback","xFindFunction","xRename","xSavepoint","xRelease","xRollbackTo","xShadowName"],g=Object.create(null);for(const h of H){const D=x[h];if(D instanceof Function)h==="xConnect"&&x.xCreate===D?g[h]=x.xCreate:h==="xCreate"&&x.xConnect===D?g[h]=x.xConnect:g[h]=L(h,D);else continue}w.installMethods(g,!1)}else w.installMethods(x,!!I.applyArgcCheck);if(w.$iVersion===0){let L;typeof I.iVersion=="number"?L=I.iVersion:w.$xIntegrity?L=4:w.$xShadowName?L=3:w.$xSavePoint||w.$xRelease||w.$xRollbackTo?L=2:L=1,w.$iVersion=L}}catch(x){throw S&&S.dispose(),x}return w},r.sqlite3_module.prototype.setupModule=function(I){return _.setupModule.call(this,I)}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(i.config.disable?.vfs?.kvvfs)return;const t=i.capi,r=t.sqlite3_kvvfs_methods,s=t.KVVfsFile,_=i.capi.sqlite3_vfs_find("kvvfs");if(delete t.sqlite3_kvvfs_methods,delete t.KVVfsFile,!_)return;const c=i.util,b=i.wasm,M=c.toss3,I=new r(b.exports.sqlite3__wasm_kvvfs_methods());c.assert(32<=I.$nKeySize,"unexpected kvvfsMethods.$nKeySize: "+I.$nKeySize);const S=Object.assign(Object.create(null),{rxJournalSuffix:/-journal$/,zKeyJrnl:b.allocCString("jrnl"),zKeySz:b.allocCString("sz"),keySize:I.$nKeySize,buffer:Object.assign(Object.create(null),{n:I.$nBufferSize,pool:Object.create(null)})});S.memBuffer=(O=0)=>S.buffer.pool[O]??=b.alloc(S.buffer.n),S.memBufferFree=O=>{const j=S.buffer.pool[O];j&&(b.dealloc(j),delete S.buffer.pool[O])};const w=()=>{},x=i.__isUnderTest?(...O)=>i.config.debug?.("kvvfs:",...O):w,L=(...O)=>i.config.warn?.("kvvfs:",...O),H=(...O)=>i.config.error?.("kvvfs:",...O);class g{#e=Object.create(null);#i=null;#s=0;constructor(){this.clear()}#t(){return this.#i??=Object.keys(this.#e)}key(j){return j<0||j>=this.#s?null:this.#t()[j]}getItem(j){return this.#e[j]??null}setItem(j,G){j in this.#e||(++this.#s,this.#i=null),this.#e[j]=""+G}removeItem(j){j in this.#e&&(delete this.#e[j],--this.#s,this.#i=null)}clear(){this.#e=Object.create(null),this.#i=null,this.#s=0}get length(){return this.#s}}const h=O=>O==="local"||O==="session",D=O=>h(O)?"kvvfs-"+O+"-":"",Q=function(O,j=!1){if(h(O))return;const G=new Blob([O]).size;G||M(t.SQLITE_MISUSE,"Empty name is not permitted.");let $=S.keySize-1;S.rxJournalSuffix.test(O)?j||M(t.SQLITE_MISUSE,"Storage names may not have a '-journal' suffix."):["-wal","-shm"].filter(le=>O.endsWith(le)).length?M(t.SQLITE_MISUSE,"Storage names may not have a -wal or -shm suffix."):$-=8,G>$&&M(t.SQLITE_RANGE,"Storage name is too long. Limit =",$);let se;for(se=0;seObject.assign(Object.create(null),{jzClass:O,refc:1,deleteAtRefc0:!1,storage:j||new g,keyPrefix:D(O),files:[],listeners:void 0}),N=i.kvvfs=Object.create(null);i.__isUnderTest&&(N.log=Object.assign(Object.create(null),{xOpen:!1,xClose:!1,xWrite:!1,xRead:!1,xSync:!1,xAccess:!1,xFileControl:!1,xRcrdRead:!1,xRcrdWrite:!1,xRcrdDelete:!1}));const J=function(O){const j=S.rxJournalSuffix.test(O.jzClass)?O.jzClass.replace(S.rxJournalSuffix,""):O.jzClass+"-journal";N?.log?.xClose&&x("cleaning up storage handles [",O.jzClass,j,"]",O),delete S.storagePool[O.jzClass],delete S.storagePool[j],i.__isUnderTest||(delete O.storage,delete O.refc)},d=O=>S.storagePool[O.jzClass]=S.storagePool[O.jzClass+"-journal"]=O,y=".";S.storagePool=Object.assign(Object.create(null),{[y]:A(y)}),globalThis.Storage&&(globalThis.localStorage instanceof globalThis.Storage&&(S.storagePool.local=A("local",globalThis.localStorage)),globalThis.sessionStorage instanceof globalThis.Storage&&(S.storagePool.session=A("session",globalThis.sessionStorage))),S.builtinStorageNames=Object.keys(S.storagePool);const F=O=>S.builtinStorageNames.indexOf(O)>-1;for(const O of Object.keys(S.storagePool)){const j=S.storagePool[O];S.storagePool[O+"-journal"]=j}S.setError=(O=void 0,j=t.SQLITE_ERROR)=>O?(S.lastError=O,O.resultCode|0||j):(delete S.lastError,0),S.popError=()=>{const O=S.lastError;return delete S.lastError,O};const W=O=>{L("kvvfs.listener handler threw:",O)},P=b.exports.sqlite3__wasm_kvvfs_decode,X=b.exports.sqlite3__wasm_kvvfs_encode,ee=async function(O,j,...G){try{j.keyPrefix&&G[0]&&(G[0]=G[0].replace(j.keyPrefix,""));let $,se,le,_e;for(const oe of j.listeners){const pe=Object.create(null);pe.storageName=j.jzClass,pe.type=O,oe.decodePages;const we=oe.events[O];if(we){if(!oe.includeJournal&&G[0]==="jrnl")continue;if(O==="write"&&oe.decodePages&&+G[0]>0){if(pe.data=[G[0]],_e?.[G[0]]){pe.data[1]=_e[G[0]];continue}$??=new TextEncoder("utf-8"),se??=S.memBuffer(10),le??=S.memBuffer(11);const Pe=$.encode(G[1]),be=b.heap8u();be.set(Pe,Number(se)),be[b.ptr.addn(se,Pe.length)]=0;const Ue=P(se,le,S.buffer.n);if(Ue>0)_e??=Object.create(null),_e[G[0]]=pe.data[1]=be.slice(Number(le),b.ptr.addn(le,Ue));else continue}else pe.data=G.length?G.length===1?G[0]:G:void 0;try{we(pe)?.catch?.(W)}catch(Pe){L("notifyListeners [",j.jzClass,"]",O,Pe)}}}}catch($){W($)}},Z=O=>typeof O=="string"?S.storagePool[O]:S.storagePool[b.cstrToJs(O)],te=b.exports.sqlite3__wasm_kvvfsMakeKey,E=(O,j,G)=>j&&O.keyPrefix?te(j,G):G,o=(O,j,G)=>b.cstrToJs(E(O,j,G)),u=O=>+O.storage.getItem(O.keyPrefix+"sz"),p=new Map,q={vfs:Object.create(null),ioDb:Object.create(null),ioJrnl:Object.create(null)},z=new t.sqlite3_vfs(I.$pVfs),V=new t.sqlite3_io_methods(I.$pIoDb),R=new t.sqlite3_io_methods(I.$pIoJrnl),m=Object.create(null),C=Object.assign(Object.create(null),{pFileHandles:p,cache:S,storageForZClass:Z,KVVfsStorage:g,disablePageSizeChange:!0});N.log&&(N.internal=C);const B={recordHandler:{xRcrdRead:(O,j,G,$)=>{try{const se=b.cstrToJs(O),le=Z(se);if(!le)return-1;const _e=o(le,O,j);N?.log?.xRcrdRead&&L("xRcrdRead",se,_e,$,le);const oe=le.storage.getItem(_e);if(oe===null)return-1;const pe=oe.length;if($<=0)return pe;if($===1)return b.poke(G,0),pe;$+1{try{const $=Z(O),se=o($,O,j),le=b.cstrToJs(G);return N?.log?.xRcrdWrite&&L("xRcrdWrite",se,$),$.storage.setItem(se,le),$.listeners&&ee("write",$,se,le),0}catch($){return H("kvrecordWrite()",$),S.setError($,t.SQLITE_IOERR)}},xRcrdDelete:(O,j)=>{try{const G=Z(O),$=o(G,O,j);return N?.log?.xRcrdDelete&&L("xRcrdDelete",$,G),G.storage.removeItem($),G.listeners&&ee("delete",G,$),0}catch(G){return H("kvrecordDelete()",G),S.setError(G,t.SQLITE_IOERR)}}},vfs:{xOpen:function(O,j,G,$,se){S.popError();let le;try{j||(le=b.allocCString(""+G+"."+(Math.random()*1e5|0)),j=le);const _e=b.cstrToJs(j);N?.log?.xOpen&&x("xOpen",_e,"flags =",$),Q(_e,!0),$&(t.SQLITE_OPEN_MAIN_DB|t.SQLITE_OPEN_TEMP_DB|t.SQLITE_OPEN_TRANSIENT_DB)&&S.rxJournalSuffix.test(_e)&&M(t.SQLITE_ERROR,"DB files may not have a '-journal' suffix.");let oe=Z(_e);!oe&&!($&t.SQLITE_OPEN_CREATE)&&M(t.SQLITE_ERROR,"Storage not found:",_e);const pe=q.vfs.xOpen(O,j,G,$,se);if(pe)return pe;let we=!!(t.SQLITE_OPEN_DELETEONCLOSE&$);b.isPtr(arguments[1])&&t.sqlite3_uri_boolean(j,"delete-on-close",0)&&(we=!0);const Pe=new s(G);if(c.assert(Pe.$zClass,"Missing f.$zClass"),Pe.addOnDispose(le),le=void 0,oe)++oe.refc,oe.files.push(Pe),b.poke32(se,$);else{b.poke32(se,$|t.SQLITE_OPEN_CREATE),c.assert(!Pe.$isJournal,"Opening a journal before its db? "+_e);const be=_e.replace(S.rxJournalSuffix,"");oe=A(be),d(oe),oe.files.push(Pe),oe.deleteAtRefc0=we,N?.log?.xOpen&&x("xOpen installed storage handle [",be,be+"-journal","]",oe)}return p.set(G,{store:oe,file:Pe,jzClass:_e}),oe.listeners&&ee("open",oe,oe.files.length),0}catch(_e){return L("xOpen:",_e),S.setError(_e)}finally{le&&b.dealloc(le)}},xDelete:function(O,j,G){S.popError();try{const $=b.cstrToJs(j);return S.rxJournalSuffix.test($)&&m.xRcrdDelete(j,S.zKeyJrnl),0}catch($){return L("xDelete",$),S.setError($)}},xAccess:function(O,j,G,$){S.popError();try{const se=Z(j),le=se?.jzClass||b.cstrToJs(j);if(N?.log?.xAccess&&x("xAccess",le,"flags =",G,"*pResOut =",b.peek32($),"store =",se),!se)try{Q(le)}catch{return b.poke32($,0),0}if(se){const _e=se.keyPrefix+(S.rxJournalSuffix.test(le)?"jrnl":"1"),oe=se.storage.getItem(_e)?0:1;b.poke32($,oe)}else b.poke32($,0);return 0}catch(se){return H("xAccess",se),S.setError(se)}},xRandomness:function(O,j,G){const $=b.heap8u();let se=0;const le=Number(G);for(;sej&&b.poke8(b.ptr.add(G,j,-1),0),x("set xGetLastError",$.message),$.resultCode|0||t.SQLITE_IOERR}catch{return t.SQLITE_NOMEM}finally{b.scopedAllocPop(se)}}return 0}},ioDb:{xClose:function(O){S.popError();try{const j=p.get(O);if(N?.log?.xClose&&x("xClose",O,j),j){p.delete(O);const G=j.store;G.files=G.files.filter($=>$!==j.file),--G.refc<=0&&G.deleteAtRefc0&&J(G),q.ioDb.xClose(O),j.file.dispose(),G.listeners&&ee("close",G,G.files.length)}return 0}catch(j){return H("xClose",j),S.setError(j)}},xFileControl:function(O,j,G){S.popError();try{const $=p.get(O);if(c.assert($,"Missing KVVfsFile handle"),N?.log?.xFileControl&&x("xFileControl",$,"op =",j),j===t.SQLITE_FCNTL_PRAGMA&&C.disablePageSizeChange){const le=b.peekPtr(b.ptr.add(G,b.ptr.size));if(b.cstrToJs(le)==="page_size"){N?.log?.xFileControl&&x("xFileControl pragma",b.cstrToJs(le));const _e=b.peekPtr(b.ptr.add(G,2*b.ptr.size));if(_e)return N?.log?.xFileControl&&L("xFileControl pragma",$,"NOT setting page size to",b.cstrToJs(_e)),$.file.$szPage=-1,0;if($.file.$szPage>0)return N?.log?.xFileControl&&L("xFileControl",$,"getting page size",$.file.$szPage),b.pokePtr(G,b.allocCString(""+$.file.$szPage)),0}}const se=q.ioDb.xFileControl(O,j,G);return se==0&&t.SQLITE_FCNTL_SYNC===j&&$.store.listeners&&ee("sync",$.store,!1),se}catch($){return H("xFileControl",$),S.setError($)}},xSync:function(O,j){S.popError();try{const G=p.get(O);N?.log?.xSync&&x("xSync",G),c.assert(G,"Missing KVVfsFile handle");const $=q.ioDb.xSync(O,j);return $==0&&G.store.listeners&&ee("sync",G.store,!0),$}catch(G){return H("xSync",G),S.setError(G)}}},ioJrnl:{xClose:!0}};try{c.assert(S.buffer.n>1024*129,"Heap buffer is not large enough");for(const O of Object.entries(B.recordHandler)){const j=O[0],G=O[1];m[j]=G,I[I.memberKey(j)]=b.installFunction(I.memberSignature(j),G)}for(const O of Object.entries(B.vfs)){const j=O[0],G=O[1],$=z.memberKey(j),se=z.structInfo.members[j]||c.toss("Missing pVfs.structInfo[",j,"]");q.vfs[j]=b.functionEntry(z[$]),z[$]=b.installFunction(se.signature,G)}for(const O of Object.entries(B.ioDb)){const j=O[0],G=O[1],$=V.memberKey(j);q.ioDb[j]=b.functionEntry(V[$])||c.toss("Missing native pIoDb[",$,"]"),V[$]=b.installFunction(V.memberSignature(j),G)}for(const O of Object.entries(B.ioJrnl)){const j=O[0],G=O[1],$=R.memberKey(j);q.ioJrnl[j]=b.functionEntry(R[$])||c.toss("Missing native pIoJrnl[",$,"]"),G===!0?R[$]=V[$]||c.toss("Missing copied pIoDb[",$,"]"):R[$]=b.installFunction(R.memberSignature(j),G)}}finally{I.dispose(),z.dispose(),V.dispose(),R.dispose()}const Y=function O(j){if(j==="")return O("local")+O("session");const G=Z(j);if(!G)return 0;G.files.length&&(globalThis.localStorage===G.storage||globalThis.sessionStorage===G.storage||M(t.SQLITE_ACCESS,"Cannot clear in-use database storage."));const $=G.storage,se=[];let le,_e=$.length;for(le=0;le<_e;++le){const oe=$.key(le);(!G.keyPrefix||oe.startsWith(G.keyPrefix))&&se.push(oe)}return se.forEach(oe=>$.removeItem(oe)),se.length},ne=function O(j){if(j==="")return O("local")+O("session");const G=Z(j);if(!G)return 0;const $=G.storage;let se,le=0;for(se=0;se<$.length;++se){const _e=$.key(se);(!G.keyPrefix||_e.startsWith(G.keyPrefix))&&(le+=_e.length,le+=$.getItem(_e).length)}return le*2},ae=function(...j){let G;j.length===1&&typeof j[0]=="object"?G=j[0]:j.length&&(G=Object.assign(Object.create(null),{name:j[0]}));const $=G?Z(G.name):null;$||M(t.SQLITE_NOTFOUND,"There is no kvvfs storage named",G?.name);const se=$.storage,le=Object.assign(Object.create(null),{name:$.jzClass,timestamp:Date.now(),pages:[]}),_e=Object.create(null),oe=$.keyPrefix,pe=oe?/^kvvfs-[^-]+-(\w+)/:void 0;let we=0,Pe=se.length;for(;we+be).sort().forEach(be=>le.pages.push(_e[be])),le},ce=function(O,j=!1){!O?.timestamp||!O.name||O.size===void 0||!Array.isArray(O.pages)?M(t.SQLITE_MISUSE,"Malformed export object."):(!O.size||O.size!==(O.size|0)||O.size>=2147483647)&&M(t.SQLITE_RANGE,"Invalid db size: "+O.size),Q(O.name);let G=Z(O.name);const $=!G;G?(j?!G.files||!G.jzClass?M(t.SQLITE_ERROR,"Internal storage object",O.name,"seems to be malformed."):G.files.length&&M(t.SQLITE_IOERR_ACCESS,"Cannot import db storage while it is in use."):M(t.SQLITE_ACCESS,"Storage '"+O.name+"' already exists and","overwrite was not specified."),Y(O.name)):G=A(O.name);const se=D(O.name);let le;try{const _e=G.storage;_e.setItem(se+"sz",O.size),O.journal&&_e.setItem(se+"jrnl",O.journal),O.pages[0]instanceof Uint8Array?O.pages.forEach((oe,pe)=>{const we=oe.length;le??=S.memBuffer(1);const Pe=S.memBuffer(0),be=b.heap8u();be.set(oe,Number(Pe)),be[b.ptr.addn(Pe,we)]=0;const Ue=X(Pe,we,le);c.assert(Ue_e.setItem(se+(pe+1),oe)),$&&d(G)}catch{if(!$)try{Y(O.name)}catch{}}finally{le&&S.memBufferFree(1)}return this},ke=function(O){let j=Z(O);if(j){++j.refc;return}Q(O),d(A(O))},Ne=function(O){const j=Z(O);return!j||h(j.jzClass)||F(j.jzClass)||S.rxJournalSuffix.test(O)?!1:j.refc>j.files.length||j.files.length===0?(--j.refc<=0&&J(j),!0):!1},Xe=function(O){(!O||typeof O!="object")&&M(t.SQLITE_MISUSE,"Expecting a listener object.");let j=Z(O.storage);j||(O.storage&&O.reserve?(ke(O.storage),j=Z(O.storage),c.assert(j,"Unexpectedly cannot fetch reserved storage "+O.storage)):M(t.SQLITE_NOTFOUND,"No such storage:",O.storage)),O.events&&(j.listeners??=[]).push(O)},at=function(O){const j=Z(O?.storage);if(j?.listeners&&O.events){const G=j.listeners.length;j.listeners=j.listeners.filter(se=>se!==O);const $=G>j.listeners.length;return j.listeners.length||(j.listeners=void 0),$}return!1};if(i.kvvfs.reserve=ke,i.kvvfs.import=ce,i.kvvfs.export=ae,i.kvvfs.unlink=Ne,i.kvvfs.listen=Xe,i.kvvfs.unlisten=at,i.kvvfs.exists=O=>!!Z(O),i.kvvfs.estimateSize=ne,i.kvvfs.clear=Y,globalThis.Storage&&(t.sqlite3_js_kvvfs_size=(O="")=>ne(O),t.sqlite3_js_kvvfs_clear=(O="")=>Y(O)),i.oo1?.DB){const O=i.oo1.DB;i.oo1.JsStorageDb=function(G=i.oo1.JsStorageDb.defaultStorageName){const $=O.dbCtorHelper.normalizeArgs(...arguments);switch($.vfs="kvvfs",$.filename){case":sessionStorage:":$.filename="session";break;case":localStorage:":$.filename="local";break}const se=/(file:(\/\/)?)([^?]+)/.exec($.filename);Q(se?se[3]:$.filename),O.dbCtorHelper.call(this,$)},i.oo1.JsStorageDb.defaultStorageName=S.storagePool.session?"session":y;const j=i.oo1.JsStorageDb;j.prototype=Object.create(O.prototype),j.clearStorage=Y,j.prototype.clearStorage=function(){return j.clearStorage(this.affirmOpen().dbFilename(),!0)},j.storageSize=ne,j.prototype.storageSize=function(){return j.storageSize(this.affirmOpen().dbFilename(),!0)}}if(i.__isUnderTest&&i.vtab){const O=Object.assign(Object.create(null),{rowid:{type:"INTEGER"},name:{type:"TEXT"},nRef:{type:"INTEGER"},nOpen:{type:"INTEGER"},isTransient:{type:"INTEGER"},dbSize:{type:"INTEGER"}});Object.keys(O).forEach((_e,oe)=>O[_e].colId=oe);const j=i.vtab,G=Object.assign(Object.create(null),{row:function(){return S.storagePool[this.names[this.rowid]]}});Object.assign(Object.create(G),{rowid:0,names:Object.keys(S.storagePool).filter(_e=>!S.rxJournalSuffix.test(_e))});const $=function(_e,oe){const pe=_e instanceof t.sqlite3_vtab_cursor?_e:j.xCursor.get(_e);return(oe||!pe.vTabState)&&(pe.vTabState=Object.assign(Object.create(G),{rowid:0,names:Object.keys(S.storagePool).filter(we=>!S.rxJournalSuffix.test(we))})),pe.vTabState},se=()=>{},le=function _e(){return _e.mod??=new i.capi.sqlite3_module().setupModule({catchExceptions:!0,methods:{xConnect:function(oe,pe,we,Pe,be,Ue){try{const Ye=[];Object.keys(O).forEach(Ze=>{Ye.push(Ze+" "+O[Ze].type)});const pt=t.sqlite3_declare_vtab(oe,"CREATE TABLE ignored("+Ye.join(",")+")");if(pt===0){const Ze=j.xVtab.create(be);c.assert(Ze===j.xVtab.get(b.peekPtr(be)),"output pointer check failed")}return pt}catch(Ye){return j.xError("xConnect",Ye,t.SQLITE_ERROR)}},xCreate:b.ptr.null,xDisconnect:function(oe){return j.xVtab.dispose(oe),0},xOpen:function(oe,pe){return j.xCursor.create(pe),0},xClose:function(oe){const pe=j.xCursor.unget(oe);return delete pe.vTabState,pe.dispose(),0},xNext:function(oe){const pe=j.xCursor.get(oe);return++$(pe).rowid,0},xColumn:function(oe,pe,we){const Pe=$(oe),be=Pe.row();switch(c.assert(be,"Unexpected xColumn call"),we){case O.rowid.colId:t.sqlite3_result_int(pe,Pe.rowid);break;case O.name.colId:t.sqlite3_result_text(pe,be.jzClass,-1,t.SQLITE_TRANSIENT);break;case O.nRef.colId:t.sqlite3_result_int(pe,be.refc);break;case O.nOpen.colId:t.sqlite3_result_int(pe,be.files.length);break;case O.isTransient.colId:t.sqlite3_result_int(pe,!!be.deleteAtRefc0);break;case O.dbSize.colId:t.sqlite3_result_int(pe,u(be));break;default:return t.sqlite3_result_error(pe,"Invalid column id: "+we),t.SQLITE_RANGE}return 0},xRowid:function(oe,pe){const we=$(oe);return j.xRowid(pe,we.rowid),0},xEof:function(oe){const pe=$(oe);return se("xEof?="+!pe.row(),...arguments),!pe.row()},xFilter:function(oe,pe,we,Pe,be){return $(oe,!0),0},xBestIndex:function(oe,pe){const we=new t.sqlite3_index_info(pe);return we.$estimatedRows=S.storagePool.size,we.$estimatedCost=1,we.dispose(),0}}})};i.kvvfs.create_module=function(_e,oe="sqlite_kvvfs"){return t.sqlite3_create_module(_e,oe,le(),b.ptr.null)}}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(i.config.disable?.vfs?.opfs&&i.config.disable.vfs["opfs-vfs"])return;const t=i.util.toss;i.capi;const r=i.util;i.wasm;const s=i.opfs=Object.create(null);s.thisThreadHasOPFS=()=>globalThis.FileSystemHandle&&globalThis.FileSystemDirectoryHandle&&globalThis.FileSystemFileHandle&&globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle&&navigator?.storage?.getDirectory,s.getRootDir=async function c(){return c.promise??=navigator.storage.getDirectory().then(b=>(s.rootDirectory=b,b)).catch(b=>{throw delete c.promise,b})},s.getResolvedPath=function(c,b){const M=new URL(c,"file://irrelevant").pathname;return b?M.split("/").filter(I=>!!I):M},s.getDirForFilename=async function(b,M=!1){const I=s.getResolvedPath(b,!0),S=I.pop();let w=await s.getRootDir();for(const x of I)x&&(w=await w.getDirectoryHandle(x,{create:!!M}));return[w,S]},s.mkdir=async function(c){try{return await s.getDirForFilename(c+"/filepart",!0),!0}catch{return!1}},s.entryExists=async function(c){try{const[b,M]=await s.getDirForFilename(c);return await b.getFileHandle(M),!0}catch{return!1}},s.randomFilename=function c(b=16){c._chars||(c._chars="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012346789",c._n=c._chars.length);const M=[];let I=0;for(;I=15&&(r.affirmDbHeader(x),L=!0),S.write(x,{at:w}),w+=x.byteLength;if((w<512||w%512!==0)&&t("Input size",w,"is not correct for an SQLite database."),!L){const H=new Uint8Array(20);S.read(H,{at:0}),r.affirmDbHeader(H)}return S.write(new Uint8Array([1,1]),{at:18}),w}catch(H){throw await S.close(),S=void 0,await M.removeEntry(I).catch(()=>{}),H}finally{S&&await S.close()}};s.importDb=async function(c,b){if(b instanceof Function)return _(c,b);b instanceof ArrayBuffer&&(b=new Uint8Array(b)),r.affirmIsDb(b);const M=b.byteLength,[I,S]=await s.getDirForFilename(c,!0);let w,x=0;try{return w=await(await I.getFileHandle(S,{create:!0})).createSyncAccessHandle(),w.truncate(0),x=w.write(b,{at:0}),x!=M&&t("Expected to write "+M+" bytes but wrote "+x+"."),w.write(new Uint8Array([1,1]),{at:18}),x}catch(L){throw w&&(await w.close(),w=void 0),await I.removeEntry(S).catch(()=>{}),L}finally{w&&await w.close()}},s.vfsInstallationFeatureCheck=function(c){!globalThis.SharedArrayBuffer||!globalThis.Atomics?t("Cannot install OPFS: Missing SharedArrayBuffer and/or Atomics.","The server must emit the COOP/COEP response headers to enable those.","See https://sqlite.org/wasm/doc/trunk/persistence.md#coop-coep"):typeof WorkerGlobalScope>"u"?t("The OPFS sqlite3_vfs cannot run in the main thread","because it requires Atomics.wait()."):!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle?.prototype?.createSyncAccessHandle||!navigator?.storage?.getDirectory?t("Missing required OPFS APIs."):c==="opfs-wl"&&!globalThis.Atomics.waitAsync&&t("The",c,"VFS requires Atomics.waitAsync(), which is not available.")},s.initOptions=function(b,M){const I=new URL(globalThis.location.href).searchParams;if(!I.has(b+"-disable")){try{s.vfsInstallationFeatureCheck(b)}catch{return}return M=r.nu(M),M.vfsName=b,M.verbose??=I.has("opfs-verbose")?+I.get("opfs-verbose"):1,M.sanityChecks??=I.has("opfs-sanity-check"),s.proxyUri||(s.proxyUri="sqlite3-opfs-async-proxy.js",i.scriptInfo?.sqlite3Dir&&(s.proxyUri=i.scriptInfo.sqlite3Dir+s.proxyUri)),M.proxyUri??=s.proxyUri,typeof M.proxyUri=="function"&&(M.proxyUri=M.proxyUri()),s.options=M}},s.createVfsState=function(){const c=r.nu(),b=s.options;c.verbose=b.verbose;const M=[i.config.error,i.config.warn,i.config.log],I=b.vfsName||t("Maintenance required: missing VFS name"),S=(P,...X)=>{c.verbose>P&&M[P](I+":",...X)},w=(...P)=>S(2,...P),x=(...P)=>S(1,...P),L=(...P)=>S(0,...P),H=i.capi,g=i.wasm,h=c.vfs=new H.sqlite3_vfs,D=h.ioMethods=new H.sqlite3_io_methods;D.$iVersion=1,h.$iVersion=2,h.$szOsFile=H.sqlite3_file.structInfo.sizeof,h.$mxPathname=1024,h.$zName=g.allocCString(I),h.addOnDispose("$zName",h.$zName,D),h.metrics=r.nu({counters:r.nu(),dump:function(){let P,X=0,ee=0,Z=0;for(P in c.opIds){const te=Q[P];X+=te.count,ee+=te.time,Z+=te.wait,te.avgTime=te.count&&te.time?te.time/te.count:0,te.avgWait=te.count&&te.wait?te.wait/te.count:0}i.config.log(globalThis.location.href,"metrics for",globalThis.location.href,":",Q,` +Total of`,X,"op(s) for",ee,"ms (incl. "+Z+" ms of waiting on the async side)"),i.config.log("Serialization metrics:",h.metrics.counters.s11n),h.worker?.postMessage?.({type:"opfs-async-metrics"})},reset:function(){let P;const X=te=>te.count=te.time=te.wait=0,ee=h.metrics.counters;for(P in c.opIds)X(ee[P]=Object.create(null));let Z=ee.s11n=Object.create(null);Z=Z.serialize=Object.create(null),Z.count=Z.time=0,Z=ee.s11n.deserialize=Object.create(null),Z.count=Z.time=0}}),c.asyncIdleWaitTime=150,c.asyncS11nExceptions=1,c.fileBufferSize=1024*64,c.sabS11nOffset=c.fileBufferSize,c.sabS11nSize=h.$mxPathname*2,c.sabIO=new SharedArrayBuffer(c.fileBufferSize+c.sabS11nSize),c.opIds=Object.create(null);{let P=0;c.opIds.whichOp=P++,c.opIds.rc=P++,c.opIds.xAccess=P++,c.opIds.xClose=P++,c.opIds.xDelete=P++,c.opIds.xDeleteNoWait=P++,c.opIds.xFileSize=P++,c.opIds.xLock=P++,c.opIds.xOpen=P++,c.opIds.xRead=P++,c.opIds.xSleep=P++,c.opIds.xSync=P++,c.opIds.xTruncate=P++,c.opIds.xUnlock=P++,c.opIds.xWrite=P++,c.opIds.mkdir=P++,c.opIds["opfs-async-metrics"]=P++,c.opIds["opfs-async-shutdown"]=P++,c.opIds.retry=P++,c.sabOP=new SharedArrayBuffer(P*4)}c.sq3Codes=Object.create(null);for(const P of["SQLITE_ACCESS_EXISTS","SQLITE_ACCESS_READWRITE","SQLITE_BUSY","SQLITE_CANTOPEN","SQLITE_ERROR","SQLITE_IOERR","SQLITE_IOERR_ACCESS","SQLITE_IOERR_CLOSE","SQLITE_IOERR_DELETE","SQLITE_IOERR_FSYNC","SQLITE_IOERR_LOCK","SQLITE_IOERR_READ","SQLITE_IOERR_SHORT_READ","SQLITE_IOERR_TRUNCATE","SQLITE_IOERR_UNLOCK","SQLITE_IOERR_WRITE","SQLITE_LOCK_EXCLUSIVE","SQLITE_LOCK_NONE","SQLITE_LOCK_PENDING","SQLITE_LOCK_RESERVED","SQLITE_LOCK_SHARED","SQLITE_LOCKED","SQLITE_MISUSE","SQLITE_NOTFOUND","SQLITE_OPEN_CREATE","SQLITE_OPEN_DELETEONCLOSE","SQLITE_OPEN_MAIN_DB","SQLITE_OPEN_READONLY","SQLITE_LOCK_NONE","SQLITE_LOCK_SHARED","SQLITE_LOCK_RESERVED","SQLITE_LOCK_PENDING","SQLITE_LOCK_EXCLUSIVE"])c.sq3Codes[P]=H[P]??t("Maintenance required: not found:",P);c.opfsFlags=Object.assign(Object.create(null),{OPFS_UNLOCK_ASAP:1,OPFS_UNLINK_BEFORE_OPEN:2,defaultUnlockAsap:!1}),h.metrics.reset();const Q=h.metrics.counters,A=h.opRun=(P,...X)=>{const ee=c.opIds[P]||t(h.vfsName+": Invalid op ID:",P);c.s11n.serialize(...X),Atomics.store(c.sabOPView,c.opIds.rc,-1),Atomics.store(c.sabOPView,c.opIds.whichOp,ee),Atomics.notify(c.sabOPView,c.opIds.whichOp);const Z=performance.now();for(;Atomics.wait(c.sabOPView,c.opIds.rc,-1)!=="not-equal";);const te=Atomics.load(c.sabOPView,c.opIds.rc);if(Q[P].wait+=performance.now()-Z,te&&c.asyncS11nExceptions){const E=c.s11n.deserialize();E&&L(P+"() async error:",...E)}return te},N=Object.create(null);N.op=void 0,N.start=void 0;const J=h.mTimeStart=P=>{N.start=performance.now(),N.op=P,++Q[P].count},d=h.mTimeEnd=()=>Q[N.op].time+=performance.now()-N.start,y=h.__openFiles=Object.create(null);h.ioSyncWrappers=r.nu({xCheckReservedLock:function(P,X){return g.poke(X,0,"i32"),0},xClose:function(P){J("xClose");let X=0;const ee=y[P];return ee&&(delete y[P],X=A("xClose",P),ee.sq3File&&ee.sq3File.dispose()),d(),X},xDeviceCharacteristics:function(P){return H.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(P,X,ee){return H.SQLITE_NOTFOUND},xFileSize:function(P,X){J("xFileSize");let ee=A("xFileSize",P);if(ee==0)try{const Z=c.s11n.deserialize()[0];g.poke(X,Z,"i64")}catch(Z){L("Unexpected error reading xFileSize() result:",Z),ee=c.sq3Codes.SQLITE_IOERR}return d(),ee},xRead:function(P,X,ee,Z){J("xRead");const te=y[P];let E;try{E=A("xRead",P,ee,Number(Z)),(E===0||H.SQLITE_IOERR_SHORT_READ===E)&&g.heap8u().set(te.sabView.subarray(0,ee),Number(X))}catch(o){L("xRead(",arguments,") failed:",o,te),E=H.SQLITE_IOERR_READ}return d(),E},xSync:function(P,X){J("xSync");const ee=A("xSync",P,X);return d(),ee},xTruncate:function(P,X){J("xTruncate");const ee=A("xTruncate",P,Number(X));return d(),ee},xWrite:function(P,X,ee,Z){J("xWrite");const te=y[P];let E;try{te.sabView.set(g.heap8u().subarray(Number(X),Number(X)+ee)),E=A("xWrite",P,ee,Number(Z))}catch(o){L("xWrite(",arguments,") failed:",o,te),E=H.SQLITE_IOERR_WRITE}return d(),E}}),h.vfsSyncWrappers={xAccess:function(P,X,ee,Z){J("xAccess");const te=A("xAccess",g.cstrToJs(X));return g.poke(Z,te?0:1,"i32"),d(),0},xCurrentTime:function(P,X){return g.poke(X,24405875e-1+new Date().getTime()/864e5,"double"),0},xCurrentTimeInt64:function(P,X){return g.poke(X,24405875e-1*864e5+new Date().getTime(),"i64"),0},xDelete:function(P,X,ee){J("xDelete");const Z=A("xDelete",g.cstrToJs(X),ee,!1);return d(),Z},xFullPathname:function(P,X,ee,Z){return g.cstrncpy(Z,X,ee)te[typeof u]||t("Maintenance required: this value type cannot be serialized.",u),o=u=>{switch(u){case te.number.id:return te.number;case te.bigint.id:return te.bigint;case te.boolean.id:return te.boolean;case te.string.id:return te.string;default:t("Invalid type ID:",u)}};return c.s11n.deserialize=function(u=!1){performance.now();const p=ee[0],q=p?[]:null;if(p){const z=[];let V=1,R,m,C;for(R=0;R(te=!0,h.dispose(),Z(R)),o=()=>{try{X(i,h)}catch(R){return E(R)}return te=!1,ee(i)},u=s.options;u.proxyUri+(u.proxyUri.indexOf("?")<0?"?":"&")+I;const p=new URL("/assets/sqlite3-opfs-async-proxy-D_xnb1D8.js",self.location.href);p.searchParams.set("vfs",I);const q=h.worker=new Worker(p.toString());let z=setTimeout(()=>{te===void 0&&E(new Error("Timeout while waiting for OPFS async proxy worker."))},4e3);q._originalOnError=q.onerror,q.onerror=function(R){L("Error initializing OPFS asyncer:",R),E(new Error("Loading OPFS async Worker failed for unknown reasons."))},h.opRun;const V=function(){const R=g.scopedAllocPush(),m=new H.sqlite3_file;try{const C=m.pointer,B=H.SQLITE_OPEN_CREATE|H.SQLITE_OPEN_READWRITE|H.SQLITE_OPEN_MAIN_DB,Y=g.scopedAlloc(8),ne="/sanity/check/file"+randomFilename(8),ae=g.scopedAllocCString(ne);let ce;if(c.s11n.serialize("This is ä string."),ce=c.s11n.deserialize(),w("deserialize() says:",ce),ce[0]!=="This is ä string."&&t("String d13n error."),h.vfsSyncWrappers.xAccess(h.pointer,ae,0,Y),ce=g.peek(Y,"i32"),w("xAccess(",ne,") exists ?=",ce),ce=h.vfsSyncWrappers.xOpen(h.pointer,ae,C,B,Y),w("open rc =",ce,"state.sabOPView[xOpen] =",c.sabOPView[c.opIds.xOpen]),ce!==0){L("open failed with code",ce);return}h.vfsSyncWrappers.xAccess(h.pointer,ae,0,Y),ce=g.peek(Y,"i32"),ce||t("xAccess() failed to detect file."),ce=h.ioSyncWrappers.xSync(m.pointer,0),ce&&t("sync failed w/ rc",ce),ce=h.ioSyncWrappers.xTruncate(m.pointer,1024),ce&&t("truncate failed w/ rc",ce),g.poke(Y,0,"i64"),ce=h.ioSyncWrappers.xFileSize(m.pointer,Y),ce&&t("xFileSize failed w/ rc",ce),w("xFileSize says:",g.peek(Y,"i64")),ce=h.ioSyncWrappers.xWrite(m.pointer,ae,10,1),ce&&t("xWrite() failed!");const ke=g.scopedAlloc(16);ce=h.ioSyncWrappers.xRead(m.pointer,ke,6,2),g.poke(ke+6,0);let Ne=g.cstrToJs(ke);w("xRead() got:",Ne),Ne!=="sanity"&&t("Unexpected xRead() value."),h.vfsSyncWrappers.xSleep&&(w("xSleep()ing before close()ing..."),h.vfsSyncWrappers.xSleep(h.pointer,2e3),w("waking up from xSleep()")),ce=h.ioSyncWrappers.xClose(C),w("xClose rc =",ce,"sabOPView =",c.sabOPView),w("Deleting file:",ne),h.vfsSyncWrappers.xDelete(h.pointer,ae,4660),h.vfsSyncWrappers.xAccess(h.pointer,ae,0,Y),ce=g.peek(Y,"i32"),ce&&t("Expecting 0 from xAccess(",ne,") after xDelete()."),x("End of OPFS sanity checks.")}finally{m.dispose(),g.scopedAllocPop(R)}};q.onmessage=function({data:R}){switch(R.type){case"opfs-unavailable":E(new Error(R.payload.join(" ")));break;case"opfs-async-loaded":delete c.vfs,q.postMessage({type:"opfs-async-init",args:r.nu(c)});break;case"opfs-async-inited":if(te===!0)break;clearTimeout(z),z=null;try{i.vfs.installVfs({io:{struct:h.ioMethods,methods:h.ioSyncWrappers},vfs:{struct:h,methods:h.vfsSyncWrappers}}),c.sabOPView=new Int32Array(c.sabOP),c.sabFileBufView=new Uint8Array(c.sabIO,0,c.fileBufferSize),c.sabS11nView=new Uint8Array(c.sabIO,c.sabS11nOffset,c.sabS11nSize),h.initS11n(),delete h.initS11n,u.sanityChecks&&(x("Running sanity checks because of opfs-sanity-check URL arg..."),V()),s.thisThreadHasOPFS()?s.getRootDir().then(m=>{q.onerror=q._originalOnError,delete q._originalOnError,w("End of OPFS sqlite3_vfs setup.",h),o()}).catch(E):o()}catch(m){L(m),E(m)}break;case"debug":x("debug message from worker:",R);break;default:{const m="Unexpected message from the OPFS async worker: "+JSON.stringify(R);L(m),E(new Error(m));break}}}})},c}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(!i.opfs||i.config.disable?.vfs?.opfs)return;const t=i.util,r=i.opfs||i.util.toss("Missing sqlite3.opfs"),s=async function(_){if(_=r.initOptions("opfs",_),!_)return i;const c=i.capi,b=r.createVfsState().vfs,M=b.metrics.counters,I=b.mTimeStart,S=b.mTimeEnd,w=b.opRun,x=b.__openFiles;return b.bindVfs(t.nu({xLock:function(L,H){I("xLock"),++M.xLock.count;const g=x[L];let h=0;return g.lockType?g.lockType=H:(h=w("xLock",L,H),h===0&&(g.lockType=H)),S(),h},xUnlock:function(L,H){I("xUnlock"),++M.xUnlock.count;const g=x[L];let h=0;return c.SQLITE_LOCK_NONE===H&&g.lockType&&(h=w("xUnlock",L,H)),h===0&&(g.lockType=H),S(),h}}),function(L,H){if(L.oo1){const g=function(...h){const D=L.oo1.DB.dbCtorHelper.normalizeArgs(...h);D.vfs=H.$zName,L.oo1.DB.dbCtorHelper.call(this,D)};g.prototype=Object.create(L.oo1.DB.prototype),L.oo1.OpfsDb=g,g.importDb=r.importDb,L.oo1.DB.dbCtorHelper.setVfsPostOpenCallback(b.pointer,function(h,D){D.capi.sqlite3_busy_timeout(h,1e4)})}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async _=>s().catch(c=>{_.config.warn("Ignoring inability to install 'opfs' sqlite3_vfs:",c)}))}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(i.config.disable?.vfs?.["opfs-sahpool"])return;const t=i.util.toss,r=i.util.toss3,s=Object.create(null),_=i.capi,c=i.util,b=i.wasm,M=4096,I=512,S=4,w=8,x=I+S,L=I,H=x,g=M,h=_.SQLITE_OPEN_MAIN_DB|_.SQLITE_OPEN_MAIN_JOURNAL|_.SQLITE_OPEN_SUPER_JOURNAL|_.SQLITE_OPEN_WAL,D=_.SQLITE_OPEN_MEMORY,Q=".opaque",A=()=>Math.random().toString(36).slice(2),N=new TextDecoder,J=new TextEncoder,d=Object.assign(Object.create(null),{name:"opfs-sahpool",directory:void 0,initialCapacity:6,clearOnInit:!1,verbosity:2,forceReinitIfPreviouslyFailed:!1}),y=[i.config.error,i.config.warn,i.config.log];i.config.log;const F=i.config.warn;i.config.error;const W=new Map,P=R=>W.get(R),X=(R,m)=>{m?W.set(R,m):W.delete(R)},ee=new Map,Z=R=>ee.get(R),te=(R,m)=>{m?ee.set(R,m):ee.delete(R)},E={xCheckReservedLock:function(R,m){const C=Z(R);return C.log("xCheckReservedLock"),C.storeErr(),b.poke32(m,1),0},xClose:function(R){const m=Z(R);m.storeErr();const C=m.getOFileForS3File(R);if(C)try{m.log(`xClose ${C.path}`),m.mapS3FileToOFile(R,!1),C.sah.flush(),C.flags&_.SQLITE_OPEN_DELETEONCLOSE&&m.deletePath(C.path)}catch(B){return m.storeErr(B,_.SQLITE_IOERR)}return 0},xDeviceCharacteristics:function(R){return _.SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN},xFileControl:function(R,m,C){return _.SQLITE_NOTFOUND},xFileSize:function(R,m){const C=Z(R);C.log("xFileSize");const B=C.getOFileForS3File(R).sah.getSize()-g;return b.poke64(m,BigInt(B)),0},xLock:function(R,m){const C=Z(R);C.log(`xLock ${m}`),C.storeErr();const B=C.getOFileForS3File(R);return B.lockType=m,0},xRead:function(R,m,C,B){const Y=Z(R);Y.storeErr();const ne=Y.getOFileForS3File(R);Y.log(`xRead ${ne.path} ${C} @ ${B}`);try{const ae=ne.sah.read(b.heap8u().subarray(Number(m),Number(m)+C),{at:g+Number(B)});return aem&&b.poke8(b.ptr.add(C,m,-1),0)}catch{return _.SQLITE_NOMEM}finally{b.scopedAllocPop(ne)}}return Y?Y.sqlite3Rc||_.SQLITE_IOERR:0},xOpen:function(m,C,B,Y,ne){const ae=P(m);try{Y&=~D,ae.log(`xOpen ${b.cstrToJs(C)} ${Y}`);const ce=C&&b.peek8(C)?ae.getPath(C):A();let ke=ae.getSAHForPath(ce);!ke&&Y&_.SQLITE_OPEN_CREATE&&(ae.getFileCount()X(m.pointer,0)),B&&(m.$xRandomness=B.$xRandomness,m.$xSleep=B.$xSleep,B.dispose()),!m.$xRandomness&&!u.xRandomness&&(u.xRandomness=function(Y,ne,ae){const ce=b.heap8u();let ke=0;const Ne=Number(ae);for(;ke0),i.vfs.installVfs({vfs:{struct:m,methods:u}}),m};class q{vfsDir;#e;#i;#s;#t=new Map;#n=new Map;#o=new Set;#a=new Map;#r=new Uint8Array(x);#c;#l;#_;constructor(m=Object.create(null)){this.#_=m.verbosity??d.verbosity,this.vfsName=m.name||d.name,this.#l=p(this.vfsName),X(this.#l.pointer,this),this.vfsDir=m.directory||"."+this.vfsName,this.#c=new DataView(this.#r.buffer,this.#r.byteOffset),this.isReady=this.reset(!!(m.clearOnInit??d.clearOnInit)).then(()=>{if(this.$error)throw this.$error;return this.getCapacity()?Promise.resolve(void 0):this.addCapacity(m.initialCapacity||d.initialCapacity)})}#u(m,...C){this.#_>m&&y[m](this.vfsName+":",...C)}log(...m){this.#u(2,...m)}warn(...m){this.#u(1,...m)}error(...m){this.#u(0,...m)}getVfs(){return this.#l}getCapacity(){return this.#t.size}getFileCount(){return this.#n.size}getFileNames(){const m=[];for(const C of this.#n.keys())m.push(C);return m}async addCapacity(m){for(let C=0;C{try{const ne=await Y.createSyncAccessHandle();if(this.#t.set(ne,B),m)ne.truncate(g),this.setAssociatedPath(ne,"",0);else{const ae=this.getAssociatedPath(ne);ae?this.#n.set(ae,ne):this.#o.add(ne)}}catch(ne){throw this.storeErr(ne),this.releaseAccessHandles(),ne}}))}getAssociatedPath(m){m.read(this.#r,{at:0});const C=this.#c.getUint32(L);if(this.#r[0]&&(C&_.SQLITE_OPEN_DELETEONCLOSE||(C&h)===0))return F(`Removing file with unexpected flags ${C.toString(16)}`,this.#r),this.setAssociatedPath(m,"",0),"";const B=new Uint32Array(w/4);m.read(B,{at:H});const Y=this.computeDigest(this.#r,C);if(B.every((ne,ae)=>ne===Y[ae])){const ne=this.#r.findIndex(ae=>ae===0);return ne===0&&m.truncate(g),ne?N.decode(this.#r.subarray(0,ne)):""}else return F("Disassociating file with bad digest."),this.setAssociatedPath(m,"",0),""}setAssociatedPath(m,C,B){const Y=J.encodeInto(C,this.#r);I<=Y.written+1&&t("Path too long:",C),C&&B&&(B|=D),this.#r.fill(0,Y.written,I),this.#c.setUint32(L,B);const ne=this.computeDigest(this.#r,B);m.write(this.#r,{at:0}),m.write(ne,{at:H}),m.flush(),C?(this.#n.set(C,m),this.#o.delete(m)):(m.truncate(g),this.#o.add(m))}computeDigest(m,C){if(C&D){let B=3735928559,Y=1103547991;for(const ne of m)B=Math.imul(B^ne,2654435761),Y=Math.imul(Y^ne,104729);return new Uint32Array([B>>>0,Y>>>0])}else return new Uint32Array([0,0])}async reset(m){await this.isReady;let C=await navigator.storage.getDirectory(),B;for(const Y of this.vfsDir.split("/"))Y&&(B=C,C=await C.getDirectoryHandle(Y,{create:!0}));return this.#e=C,this.#s=B,this.#i=await this.#e.getDirectoryHandle(Q,{create:!0}),this.releaseAccessHandles(),this.acquireAccessHandles(m)}getPath(m){return b.isPtr(m)&&(m=b.cstrToJs(m)),(m instanceof URL?m:new URL(m,"file://localhost/")).pathname}deletePath(m){const C=this.#n.get(m);return C&&(this.#n.delete(m),this.setAssociatedPath(C,"",0)),!!C}storeErr(m,C){return m&&(m.sqlite3Rc=C||_.SQLITE_IOERR,this.error(m)),this.$error=m,C}popErr(){const m=this.$error;return this.$error=void 0,m}nextAvailableSAH(){const[m]=this.#o.keys();return m}getOFileForS3File(m){return this.#a.get(m)}mapS3FileToOFile(m,C){C?(this.#a.set(m,C),te(m,this)):(this.#a.delete(m),te(m,!1))}hasFilename(m){return this.#n.has(m)}getSAHForPath(m){return this.#n.get(m)}async removeVfs(){if(!this.#l.pointer||!this.#i)return!1;_.sqlite3_vfs_unregister(this.#l.pointer),this.#l.dispose(),delete s[this.vfsName];try{this.releaseAccessHandles(),await this.#e.removeEntry(Q,{recursive:!0}),this.#i=void 0,await this.#s.removeEntry(this.#e.name,{recursive:!0}),this.#e=this.#s=void 0}catch(m){i.config.error(this.vfsName,"removeVfs() failed with no recovery strategy:",m)}return!0}pauseVfs(){return this.#a.size>0&&i.SQLite3Error.toss(_.SQLITE_MISUSE,"Cannot pause VFS",this.vfsName,"because it has opened files."),this.#t.size>0&&(_.sqlite3_vfs_unregister(this.vfsName),this.releaseAccessHandles()),this}isPaused(){return this.#t.size===0}async unpauseVfs(){return this.#t.size===0?this.acquireAccessHandles(!1).then(()=>_.sqlite3_vfs_register(this.#l,0),this):this}exportFile(m){const C=this.#n.get(m)||t("File not found:",m),B=C.getSize()-g,Y=new Uint8Array(B>0?B:0);if(B>0){const ne=C.read(Y,{at:g});ne!=B&&t("Expected to read "+B+" bytes but read "+ne+".")}return Y}async importDbChunked(m,C){const B=this.#n.get(m)||this.nextAvailableSAH()||t("No available handles to import to.");B.truncate(0);let Y=0,ne,ae=!1;try{for(;(ne=await C())!==void 0;)ne instanceof ArrayBuffer&&(ne=new Uint8Array(ne)),!ae&&Y===0&&ne.byteLength>=15&&(c.affirmDbHeader(ne),ae=!0),B.write(ne,{at:g+Y}),Y+=ne.byteLength;if((Y<512||Y%512!==0)&&t("Input size",Y,"is not correct for an SQLite database."),!ae){const ce=new Uint8Array(20);B.read(ce,{at:0}),c.affirmDbHeader(ce)}B.write(new Uint8Array([1,1]),{at:g+18})}catch(ce){throw this.setAssociatedPath(B,"",0),ce}return this.setAssociatedPath(B,m,_.SQLITE_OPEN_MAIN_DB),Y}importDb(m,C){if(C instanceof ArrayBuffer)C=new Uint8Array(C);else if(C instanceof Function)return this.importDbChunked(m,C);const B=this.#n.get(m)||this.nextAvailableSAH()||t("No available handles to import to."),Y=C.byteLength;(Y<512||Y%512!=0)&&t("Byte array size is invalid for an SQLite db.");const ne="SQLite format 3";for(let ce=0;ce<15;++ce)ne.charCodeAt(ce)!==C[ce]&&t("Input does not contain an SQLite database header.");const ae=B.write(C,{at:g});return ae!=Y?(this.setAssociatedPath(B,"",0),t("Expected to write "+Y+" bytes but wrote "+ae+".")):(B.write(new Uint8Array([1,1]),{at:g+18}),this.setAssociatedPath(B,m,_.SQLITE_OPEN_MAIN_DB)),ae}}class z{#e;constructor(m){this.#e=m,this.vfsName=m.vfsName}async addCapacity(m){return this.#e.addCapacity(m)}async reduceCapacity(m){return this.#e.reduceCapacity(m)}getCapacity(){return this.#e.getCapacity(this.#e)}getFileCount(){return this.#e.getFileCount()}getFileNames(){return this.#e.getFileNames()}async reserveMinimumCapacity(m){const C=this.#e.getCapacity();return Cthis)}isPaused(){return this.#e.isPaused()}}const V=async()=>{const R=await navigator.storage.getDirectory(),m=".opfs-sahpool-sync-check-"+A(),C=(await(await R.getFileHandle(m,{create:!0})).createSyncAccessHandle()).close();return await C,await R.removeEntry(m),C?.then&&t("The local OPFS API is too old for opfs-sahpool:","it has an async FileSystemSyncAccessHandle.close() method."),!0};i.installOpfsSAHPoolVfs=async function(R=Object.create(null)){R=Object.assign(Object.create(null),d,R||{});const m=R.name;if(R.$testThrowPhase1)throw R.$testThrowPhase1;if(s[m])try{return await s[m]}catch(C){if(R.forceReinitIfPreviouslyFailed)delete s[m];else throw C}return!globalThis.FileSystemHandle||!globalThis.FileSystemDirectoryHandle||!globalThis.FileSystemFileHandle||!globalThis.FileSystemFileHandle.prototype.createSyncAccessHandle||!navigator?.storage?.getDirectory?s[m]=Promise.reject(new Error("Missing required OPFS APIs.")):s[m]=V().then(async function(){if(R.$testThrowPhase2)throw R.$testThrowPhase2;const C=new q(R);return C.isReady.then(async()=>{const B=new z(C);if(i.oo1){const Y=i.oo1,ne=C.getVfs(),ae=function(...ce){const ke=Y.DB.dbCtorHelper.normalizeArgs(...ce);ke.vfs=ne.$zName,Y.DB.dbCtorHelper.call(this,ke)};ae.prototype=Object.create(Y.DB.prototype),B.OpfsSAHPoolDb=ae}return C.log("VFS initialized."),B}).catch(async B=>{throw await C.removeVfs().catch(()=>{}),B})}).catch(C=>s[m]=Promise.reject(C))}}),globalThis.sqlite3ApiBootstrap.initializers.push(function(i){if(!i.opfs||i.config.disable?.vfs?.["opfs-wl"])return;const t=i.util;i.util.toss;const r=i.opfs,s="opfs-wl",_=async function(c){if(c=r.initOptions(s,c),!c)return i;i.capi;const b=r.createVfsState().vfs;b.metrics.counters;const M=b.mTimeStart,I=b.mTimeEnd,S=b.opRun,w=b.__openFiles;return b.bindVfs(t.nu({xLock:function(x,L){M("xLock");const H=w[x],g=S("xLock",x,L);return g||(H.lockType=L),I(),g},xUnlock:function(x,L){M("xUnlock");const H=w[x],g=S("xUnlock",x,L);return g||(H.lockType=L),I(),g}}),function(x,L){if(x.oo1){const H=function(...g){const h=x.oo1.DB.dbCtorHelper.normalizeArgs(...g);h.vfs=L.$zName,x.oo1.DB.dbCtorHelper.call(this,h)};H.prototype=Object.create(x.oo1.DB.prototype),x.oo1.OpfsWlDb=H,H.importDb=r.importDb}})};globalThis.sqlite3ApiBootstrap.initializersAsync.push(async c=>_().catch(b=>{c.config.warn("Ignoring inability to install the",s,"sqlite3_vfs:",b)}))});try{const i=Object.assign(Object.create(null),{memory:typeof nt<"u"?nt:n.wasmMemory,exports:typeof dt<"u"?dt:Object.prototype.hasOwnProperty.call(n,"wasmExports")?n.wasmExports:n.asm},globalThis.sqlite3ApiBootstrap.defaultConfig,globalThis.sqlite3ApiConfig||{});e.debugModule("Bootstrapping lib config",i);const t=globalThis.sqlite3ApiBootstrap(i);return delete globalThis.sqlite3ApiBootstrap,t}catch(i){throw console.error("sqlite3ApiBootstrap() error:",i),i}},et?ie=f:ie=new Promise((e,n)=>{Ce=e,je=n}),ie}At=(function(){const qe=At;if(!qe)throw new Error("Expecting sqlite3InitModule to be defined by the Emscripten build.");const ie=globalThis.sqlite3InitModuleState=Object.assign(Object.create(null),{moduleScript:globalThis?.document?.currentScript,isWorker:typeof WorkerGlobalScope<"u",location:globalThis.location,urlParams:globalThis?.location?.href?new URL(globalThis.location.href).searchParams:new URLSearchParams,wasmFilename:"sqlite3.wasm"});if(ie.debugModule=ie.urlParams.has("sqlite3.debugModule")?(...he)=>console.warn("sqlite3.debugModule:",...he):()=>{},ie.urlParams.has("sqlite3.dir"))ie.sqlite3Dir=ie.urlParams.get("sqlite3.dir")+"/";else if(ie.moduleScript){const he=ie.moduleScript.src.split("/");he.pop(),ie.sqlite3Dir=he.join("/")+"/"}const f=globalThis.sqlite3InitModule=function he(...ye){return ie.emscriptenLocateFile=ye[0]?.locateFile,ie.emscriptenInstantiateWasm=ye[0]?.instantiateWasm,qe(...ye).then(ge=>{ie.debugModule("sqlite3InitModule() sIMS =",ie),ie.debugModule("sqlite3InitModule() EmscriptenModule =",ge);const Se=ge.runSQLite3PostLoadInit(ie,ge,!!he.__isUnderTest);return ie.debugModule("sqlite3InitModule() sqlite3 =",Se),Se}).catch(ge=>{throw console.error("Exception loading sqlite3 module:",ge),ge})};if(f.ready=qe.ready,ie.moduleScript){let he=ie.moduleScript.src.split("/");he.pop(),ie.scriptDir=he.join("/")+"/"}return ie.debugModule("extern-post-js.c-pp.js sqlite3InitModuleState =",ie),f})();var nn=At;const rn=/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/,sn=1024;function ut(qe){if(typeof qe!="string"||!rn.test(qe)||qe.length-Number(qe.startsWith("-"))-Number(qe.includes("."))>sn)throw new TypeError('Decimal requires a finite base-10 string (for example "3.50")');return qe}function It(qe){const ie=ut(qe),f=ie.startsWith("-"),[he,ye=""]=(f?ie.slice(1):ie).split("."),ge=he.replace(/^0+(?=[0-9])/,""),Se=ye.replace(/0+$/,"");return{negative:f&&(ge!=="0"||Se!==""),integer:ge,fraction:Se}}function Lt(qe,ie){const f=It(qe),he=It(ie);if(f.negative!==he.negative)return f.negative?-1:1;const ye=f.negative?-1:1;if(f.integer.length!==he.integer.length)return Math.sign(f.integer.length-he.integer.length)*ye;if(f.integer!==he.integer)return(f.integerye.replace(/[0-9]/g,ge=>String(9-Number(ge)));return`0${he(f)}${he(ie.integer)}:${he(ie.fraction)}~`}function ln(qe,ie){ut(qe),ut(ie);const f=qe.split(".")[1]?.length??0,he=ie.split(".")[1]?.length??0,ye=Math.max(f,he),ge=(De,We)=>BigInt(De.replace(".",""))*10n**BigInt(ye-We),Se=ge(qe,f)+ge(ie,he);if(ye===0)return ut(Se.toString());const Be=Se<0n?"-":"",Qe=(Se<0n?-Se:Se).toString().padStart(ye+1,"0");return ut(`${Be}${Qe.slice(0,-ye)}.${Qe.slice(-ye)}`)}function an(qe,ie){const f=ye=>{if(typeof ye!="string")throw new TypeError("Inexact SQLite Decimal value");return ut(ye)};qe.createFunction({name:"teaql_decimal_cmp",arity:2,deterministic:!0,xFunc:(ye,ge,Se)=>ge===null||Se===null?null:Lt(f(ge),f(Se))}),qe.createFunction({name:"teaql_decimal_order_key",arity:1,deterministic:!0,xFunc:(ye,ge)=>ge===null?null:on(f(ge))});const he=[];for(const ye of["sum","min","max"]){const ge=new Map;he.push(ge),qe.createFunction({name:`teaql_decimal_${ye}`,arity:1,deterministic:!0,xStep(Se,Be){if(Be===null)return;const Qe=f(Be),De=ie.sqlite3_js_aggregate_context(Se,1);if(!De)throw new Error("SQLite aggregate context allocation failed");const We=ge.get(De);ge.set(De,We===void 0?Qe:ye==="sum"?ln(We,Qe):Lt(Qe,We)===(ye==="min"?-1:1)?Qe:We)},xFinal(Se){const Be=ie.sqlite3_js_aggregate_context(Se,0),Qe=ge.get(Be)??null;return ge.delete(Be),Qe}})}return()=>{for(const ye of he)ye.clear()}}function cn(qe={}){const ie=qe.scope??globalThis;let f,he,ye,ge,Se=Promise.resolve();const Be=()=>(f||(f=nn(qe.wasmUrl?{locateFile:Ee=>Ee.endsWith(".wasm")?qe.wasmUrl:Ee}:void 0)),f),Qe=async(Ie={})=>{De();const Ee=Ie.storage??"memory",Ce=Ie.databaseName??"teaql-browser.sqlite3",je=await Be();if(Ee==="opfs"){if(!je.oo1.OpfsDb){const et=new Error("OPFS SQLite is unavailable. Serve COOP/COEP headers and use a compatible browser.");throw et.name="BrowserSQLiteStorageUnavailableError",et}he=new je.oo1.OpfsDb(`/${Ce}`,"c")}else he=new je.oo1.DB(":memory:","c");ge={storage:Ee,databaseName:Ce};try{ye=an(he,je.capi)}catch(et){throw De(),et}he.exec("PRAGMA foreign_keys = ON")},De=()=>{try{he?.close()}finally{he=void 0,ye?.(),ye=void 0}},We=()=>{if(!he)throw new Error("Browser SQLite database is not open");return he},de=(Ie,Ee=[])=>{if(typeof Ie!="string"||!Ie.trim())throw new TypeError("SQL is required");if(!Array.isArray(Ee))throw new TypeError("SQL bind values must be an array");const Ce=We();let je;try{je=Ce.exec({sql:Ie,bind:Ee,rowMode:"object",returnValue:"resultRows"})}finally{ye?.()}const et=/^\s*(?:insert|update|delete|replace)\b/i.test(Ie);return{rows:je,rowCount:je.length||(et?Number(Ce.changes()):0)}},Le=async()=>{const Ie=We();Ie.exec("PRAGMA foreign_keys = OFF");const Ee=Ie.exec({sql:"SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'",rowMode:"object",returnValue:"resultRows"});for(const Ce of Ee){const je=String(Ce.name).replace(/"/g,'""');Ie.exec(`DROP TABLE IF EXISTS "${je}"`)}if(Ie.exec("PRAGMA foreign_keys = ON"),!ge)throw new Error("Browser SQLite database is not open")};ie.addEventListener("message",Ie=>{const Ee=Ie.data;!Ee||Ee.type!=="teaql-browser-sqlite-request"||(Se=Se.then(async()=>{try{let Ce;if(Ee.operation==="open")Ce=await Qe(Ee.payload);else if(Ee.operation==="query")Ce=de(String(Ee.payload?.sql??""),Ee.payload?.values??[]);else if(Ee.operation==="reset")Ce=await Le();else if(Ee.operation==="close")De();else throw new Error(`Unsupported Browser SQLite operation: ${String(Ee.operation)}`);ie.postMessage({type:"teaql-browser-sqlite-response",requestId:Ee.requestId,result:Ce})}catch(Ce){const je=Ce instanceof Error?Ce:new Error(String(Ce));ie.postMessage({type:"teaql-browser-sqlite-response",requestId:Ee.requestId,error:{name:je.name,message:je.message,code:je.code}})}}))})}var un="/assets/sqlite3-BVKGSWc-.wasm";cn({wasmUrl:un})})(); diff --git a/dist/assets/style-F0ZYuCV2.css b/dist/assets/style-F0ZYuCV2.css new file mode 100644 index 0000000000000000000000000000000000000000..338634f51515693ae49cabf7aaf6a5a7b769bc01 --- /dev/null +++ b/dist/assets/style-F0ZYuCV2.css @@ -0,0 +1 @@ +:root{font:16px/1.5 Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,sans-serif;color:#17231b;background:#f5f4ed;font-synthesis:none;--ink: #17231b;--muted: #677067;--paper: #fffef8;--line: #d8ddd3;--green: #145b37;--green-deep: #0e4329;--lime: #dff45c;--orange: #ef8354;--blue: #2b66d9}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;min-width:320px;background:#f5f4ed}button,input{font:inherit}button,a{-webkit-tap-highlight-color:transparent}.page-shell{width:min(1440px,100%);margin:0 auto;padding:0 42px}.site-header{height:76px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line)}.brand,.docs-link{color:var(--ink);text-decoration:none;font-weight:750}.brand{display:inline-flex;align-items:center;gap:11px;letter-spacing:-.02em}.brand-mark{width:30px;height:30px;display:grid;place-items:center;border-radius:50%;color:var(--lime);background:var(--green-deep);font-family:Georgia,serif;font-style:italic}.docs-link{color:var(--green);font-size:14px}.header-actions{display:flex;align-items:center;gap:18px}.language-switch{display:flex;gap:3px;padding:3px;border:1px solid var(--line);border-radius:8px}.language-switch button{padding:3px 7px;border:0;border-radius:5px;color:var(--muted);background:transparent;font-size:11px;cursor:pointer}.language-switch button.active{color:#fff;background:var(--green)}.hero{min-height:460px;display:grid;grid-template-columns:minmax(0,1.1fr) minmax(440px,.9fr);align-items:center;gap:72px;padding:76px 0 66px}.eyebrow,.section-index,.query-card-label{margin:0 0 14px;color:var(--green);font-size:11px;font-weight:850;letter-spacing:.18em}h1{margin:0;max-width:820px;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(42px,5.6vw,78px);font-weight:500;line-height:1.08;letter-spacing:-.055em}.hero-intro{max-width:680px;margin:26px 0 0;color:var(--muted);font-size:18px}.model-map{position:relative;min-height:310px;padding:38px;display:flex;flex-direction:column;justify-content:center;align-items:center;gap:12px;border:1px solid #bfc8bb;border-radius:28px;background:linear-gradient(145deg,#fdfdf8,#e9eee5);box-shadow:0 18px 48px #213c280f;overflow:hidden}.model-map:before{content:"DOMAIN MODEL";position:absolute;top:18px;left:22px;color:#708073;font-size:10px;font-weight:800;letter-spacing:.16em}.model-flow{width:100%;display:grid;grid-template-columns:1fr auto 1fr auto 1fr;align-items:center;gap:10px}.model-flow>span:not(.model-arrow),.model-leaves span{min-width:0;padding:15px 17px;border:1px solid #b8c2b7;border-radius:12px;background:#fffffadb;font:750 14px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;box-shadow:0 8px 22px #1e3a260d}.model-map small{display:block;margin-top:7px;color:var(--muted);font:12px/1.2 Inter,sans-serif}.model-flow>span.model-root{color:#fff;border-color:var(--green);background:var(--green)}.model-map .model-root small{color:#cce4d4}.model-arrow{color:#809087;font-size:22px;text-align:center}.model-arrow-split{height:22px;line-height:18px}.model-leaves{width:100%;display:grid;grid-template-columns:repeat(4,1fr);gap:10px}.runtime-language-panel{margin-bottom:28px;padding:24px;display:grid;grid-template-columns:minmax(240px,.72fr) minmax(0,1.8fr);align-items:center;gap:30px;border:1px solid var(--line);border-radius:18px;background:var(--paper)}.runtime-language-copy .section-index{margin-bottom:8px}.runtime-language-copy h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(22px,2.4vw,31px);font-weight:500;line-height:1.15;letter-spacing:-.035em}.runtime-language-copy p:last-child{margin:11px 0 0;color:var(--muted);font-size:13px}.runtime-language-selector{display:grid;grid-template-columns:repeat(7,minmax(82px,1fr));gap:8px}.runtime-language{min-width:0;padding:13px 8px 11px;display:flex;align-items:center;flex-direction:column;gap:4px;border:1px solid #d7ddd5;border-radius:12px;color:var(--ink);background:#fafbf7;text-align:center;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.runtime-language:hover{border-color:#98aa9d;background:#fff;transform:translateY(-2px)}.runtime-language.active{color:#fff;border-color:var(--green);background:var(--green);box-shadow:0 8px 20px #145b3724}.runtime-language-icon{font-size:25px;line-height:1.1}.runtime-language strong{overflow:hidden;max-width:100%;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.runtime-language small{color:#78837a;font-size:8px;line-height:1.25}.runtime-language.active small{color:#d5e7da}.development-process{margin:54px 0 28px;padding:42px;border:1px solid var(--line);border-radius:24px;background:var(--paper);box-shadow:0 18px 48px #213c280d}.development-process-heading{display:grid;grid-template-columns:minmax(280px,.9fr) minmax(0,1.1fr);align-items:end;gap:48px}.development-process-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,3.5vw,48px);font-weight:500;line-height:1.08;letter-spacing:-.04em}.development-process-intro>p{margin:0;color:var(--muted);font-size:16px;line-height:1.7}.development-process-links{margin-top:22px;display:flex;flex-wrap:wrap;gap:10px}.source-link{min-width:210px;padding:12px 15px;display:grid;gap:3px;border:1px solid #cad3c9;border-radius:10px;color:var(--ink);background:#f8faf5;text-decoration:none;transition:border-color .16s ease,background .16s ease,transform .16s ease}.source-link:hover,.source-link:focus-visible{border-color:#819586;background:#fff;outline:none;transform:translateY(-1px)}.source-link-primary{color:#fff;border-color:var(--green);background:var(--green)}.source-link-primary:hover,.source-link-primary:focus-visible{border-color:var(--green-deep);background:var(--green-deep)}.source-link span{color:#77847a;font-size:10px;font-weight:850;letter-spacing:.13em}.source-link-primary span{color:#c8dccd}.source-link strong{font-size:14px;line-height:1.35}.development-process-flow{margin:38px 0 0;padding:0;display:grid;grid-template-columns:repeat(4,minmax(0,1fr));border:1px solid #d7ddd3;border-radius:16px;background:#f8faf5;list-style:none;overflow:hidden}.development-process-flow li{min-width:0;padding:22px;border-left:1px solid #d7ddd3}.development-process-flow li:first-child{border-left:0}.development-step{display:block;margin-bottom:20px;color:var(--orange);font:800 12px/1 ui-monospace,SFMono-Regular,Menlo,monospace}.development-process-flow strong{display:block;min-height:48px;font-size:16px;line-height:1.45}.development-process-flow p{min-height:92px;margin:10px 0 18px;color:var(--muted);font-size:14px;line-height:1.6}.development-process-flow code{color:var(--green);font:650 12px/1.45 ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.context-efficiency{margin-top:18px;padding:24px;display:grid;grid-template-columns:minmax(230px,.72fr) minmax(0,1.28fr);align-items:center;gap:34px;border-radius:14px;color:#edf7ef;background:var(--green-deep)}.context-efficiency .section-index{margin-bottom:8px;color:var(--lime)}.context-efficiency h3{margin:0;font:500 24px/1.2 Georgia,"Noto Serif SC",serif;letter-spacing:-.025em}.context-efficiency>p{margin:0;color:#c7d8cc;font-size:15px;line-height:1.7}.runtime-bar{min-height:72px;padding:14px 18px 14px 22px;display:flex;align-items:center;justify-content:space-between;gap:24px;border-radius:14px;color:#e7f1e9;background:var(--green-deep)}#status{margin:0;color:#c8d9ce;font:12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.controls{display:flex;align-items:center;gap:18px}.toggle{display:inline-flex;align-items:center;gap:9px;font-size:13px;cursor:pointer}.toggle input{position:absolute;opacity:0;pointer-events:none}.toggle span{position:relative;width:38px;height:22px;border-radius:999px;background:#55705f;transition:background .2s ease}.toggle span:after{content:"";position:absolute;top:3px;left:3px;width:16px;height:16px;border-radius:50%;background:#fff;transition:transform .2s ease}.toggle input:checked+span{background:var(--lime)}.toggle input:checked+span:after{transform:translate(16px);background:var(--green-deep)}.secondary-button,.tree-actions button{border:1px solid currentColor;border-radius:8px;background:transparent;cursor:pointer}.secondary-button{padding:8px 12px;color:#fff;font-size:12px}.secondary-button:disabled{opacity:.45;cursor:wait}.query-browser{padding:96px 0 82px}.section-heading,.result-heading{display:flex;align-items:end;justify-content:space-between;gap:36px;margin-bottom:40px}.section-heading h2,.result-heading h2{margin:0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(34px,4vw,52px);font-weight:500;letter-spacing:-.045em}.section-heading>p{max-width:420px;margin:0;color:var(--muted)}.query-group{display:grid;grid-template-columns:230px 1fr;gap:36px;padding:24px 0;border-top:1px solid var(--line)}.query-group:last-child{border-bottom:1px solid var(--line)}.query-group-heading h2{margin:0 0 4px;font-size:16px}.query-group-heading p{margin:0;color:var(--muted);font-size:12px}.query-links{display:flex;flex-wrap:wrap;align-items:center;gap:10px 24px}.query-links a{position:relative;padding:5px 0;color:#34443a;text-decoration-color:#a6b1a8;text-underline-offset:5px;font-weight:650;transition:color .16s ease}.query-links a:after{content:" ↗";color:#9aa49b;font-weight:400}.query-links a:hover{color:var(--green)}.query-links a.active{color:var(--green);text-decoration-color:var(--orange);text-decoration-thickness:2px}.result-panel{margin:0 -42px;padding:82px 42px 92px;color:#eef5f0;background:#111a15}.result-heading{align-items:center}.result-heading .section-index{color:var(--lime)}.result-heading h2{color:#fff}#result-description{max-width:620px;margin:10px 0 0;color:#9fb0a4}.result-actions{display:flex;align-items:center;gap:10px}.result-view-switch,.tree-actions{display:flex;gap:6px}.result-view-switch button,.tree-actions button{padding:8px 11px;border:1px solid #536159;border-radius:8px;color:#aebdb3;background:transparent;font-size:12px;cursor:pointer}.result-view-switch button.active{color:#17231b;border-color:var(--lime);background:var(--lime)}.result-view-switch button:disabled{opacity:.35;cursor:default}.tree-actions button:hover{color:var(--lime)}.result-grid{display:grid;grid-template-columns:minmax(0,1fr);gap:18px;align-items:start}.tree-card,.query-card,.sql-card{border:1px solid #2f3d34;border-radius:14px;background:#17231b}.tree-card{min-height:520px;overflow:hidden}.tree-card-bar{min-height:48px;padding:0 18px;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #2f3d34;color:#b8c9bd;font:11px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace;text-transform:uppercase;letter-spacing:.08em}#result-meta{margin:0;color:#829188;text-transform:none;letter-spacing:0}.json-tree{min-height:470px;max-height:680px;padding:18px 20px 28px;overflow:auto;font:13px/1.6 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}.json-tree.loading{opacity:.55}.tree-actions.hidden{display:none}.result-table-shell{width:100%;min-height:470px;overflow:auto}.result-table{width:100%;border-collapse:collapse;white-space:nowrap}.result-table th,.result-table td{padding:11px 14px;border-bottom:1px solid #2f3d34;text-align:left;vertical-align:top}.result-table th{position:sticky;top:0;z-index:1;color:#8ea095;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table td{color:#d9e5dc;font:12px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.result-table tbody tr:hover{background:#ffffff06}.result-table-empty{margin:0;padding:48px 20px;color:#7f9185;text-align:center}.tree-branch{margin:2px 0}.tree-branch>summary{min-height:29px;display:flex;align-items:center;gap:9px;list-style:none;cursor:pointer;border-radius:5px}.tree-branch>summary::-webkit-details-marker{display:none}.tree-branch>summary:before{content:"›";width:15px;color:#73887a;font-size:18px;line-height:1;transform-origin:center;transition:transform .12s ease}.tree-branch[open]>summary:before{transform:rotate(90deg)}.tree-branch>summary:hover{background:#ffffff09}.tree-children{margin-left:8px;padding-left:20px;border-left:1px solid #314238}.tree-leaf{min-height:28px;display:grid;grid-template-columns:minmax(110px,180px) 1fr;align-items:baseline;gap:12px;padding-left:23px}.tree-key{color:#bdd0c2;font-weight:700}.tree-preview{overflow:hidden;color:#718079;font-size:11px;text-overflow:ellipsis;white-space:nowrap}.tree-value{overflow-wrap:anywhere}.tree-string{color:#dff45c}.tree-number{color:#82b4ff}.tree-boolean{color:#f2a27f}.tree-null{color:#78847c;font-style:italic}.query-card,.sql-card{min-width:0;padding:22px}.query-card-label{color:var(--lime)}.query-card pre{max-height:430px;margin:0;padding:0;overflow:auto;color:#d5e2d8;background:transparent;font:12px/1.72 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;white-space:pre-wrap}.query-params{margin-top:24px;padding-top:18px;border-top:1px solid #2f3d34}.query-params.hidden{display:none}.query-params .query-card-label{margin-bottom:10px;color:#82b4ff}.query-params pre{max-height:220px;color:#b9caee}.query-note{margin:28px 0 0;padding-top:18px;border-top:1px solid #2f3d34;color:#829188;font-size:12px}.sql-card-heading{display:flex;align-items:center;justify-content:space-between;gap:16px}.sql-card-heading .query-card-label{margin-bottom:0}#sql-count{color:#7f9185;font:10px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence-wrap{margin-top:18px;overflow-x:auto;border:1px solid #34433a;border-radius:8px}.execution-evidence{min-width:1500px;width:100%;border-collapse:collapse;color:#c7d5cb}.execution-evidence th,.execution-evidence td{padding:10px 12px;border-right:1px solid #34433a;border-bottom:1px solid #34433a;text-align:left;vertical-align:top;white-space:nowrap}.execution-evidence th:last-child,.execution-evidence td:last-child{border-right:0}.execution-evidence tbody tr:last-child td{border-bottom:0}.execution-evidence th{color:#7f9185;background:#131d17;font:700 10px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence td{color:#cbd8ce;background:#101813;font:10px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace}.execution-evidence tbody tr:hover td{background:#141f18}.execution-evidence .evidence-trace{color:#b9caee}.execution-evidence .evidence-sql{color:#dff45c}.dashboard-result{max-height:none;padding:0;color:var(--ink);background:#f7f8f5;font:14px/1.45 Inter,system-ui,sans-serif}.order-center{min-width:880px;padding:24px}.order-center-toolbar{display:flex;align-items:end;justify-content:space-between;gap:24px;margin-bottom:20px}.order-center-toolbar h3{margin:0;color:#111d16;font:750 22px/1.2 Inter,system-ui,sans-serif;letter-spacing:-.025em}.order-center-toolbar p{margin:5px 0 0;color:#778078;font-size:12px}.order-search{width:min(390px,45%);display:flex;align-items:center;gap:6px}.order-search input{min-width:0;height:32px;flex:1;padding:6px 10px;border:1px solid #cfd5ce;border-radius:7px;outline:0;background:#fff;font-size:12px}.order-search input:focus{border-color:#8e9990}.order-search-submit{width:30px;height:30px;flex:0 0 30px;display:grid;place-items:center;padding:0;border:1px solid #cfd5ce;border-radius:7px;color:#536057;background:#fff;cursor:pointer}.order-search-submit:hover,.order-search-submit:focus-visible{color:var(--green);border-color:#93a097;outline:none}.search-icon{position:relative;width:13px;height:13px;display:block;border:1.5px solid currentColor;border-radius:50%}.search-icon:after{content:"";position:absolute;right:-3px;bottom:-2px;width:5px;height:1.5px;border-radius:1px;background:currentColor;transform:rotate(45deg);transform-origin:left center}.order-metrics{display:grid;grid-template-columns:repeat(auto-fit,minmax(120px,1fr));gap:10px;margin-bottom:18px}.metric-card{padding:14px;display:grid;gap:8px;text-align:left;border:1px solid #dbe0da;border-radius:9px;color:#58625b;background:#fff;cursor:pointer}.metric-card strong{color:#16231a;font-size:23px;line-height:1}.metric-card small{color:#727b74;font-size:10px;font-variant-numeric:tabular-nums}.metric-card.active{border-color:var(--metric-color, var(--blue));box-shadow:inset 3px 0 0 var(--metric-color, var(--blue))}.order-table{overflow:hidden;border:1px solid #e0e4df;border-radius:10px;background:#fff}.order-row{min-width:720px;display:grid;grid-template-columns:1.05fr .85fr .75fr 2fr;align-items:center;gap:14px;min-height:68px;padding:10px 14px;border-top:1px solid #edf0ec}.order-row:first-child{border-top:0}.order-row-head{min-height:40px;color:#69736b;background:#f2f4f1;font-size:11px;font-weight:750}.order-primary{color:#26322a;font:650 12px/1.4 ui-monospace,SFMono-Regular,Menlo,monospace}.status-badge{display:inline-block;padding:4px 8px;border-radius:999px;color:#2b5e39;background:#e3f4e8;font-size:10px;white-space:nowrap}.status-pending_payment{color:#92580a;background:#fff0d8}.status-paid{color:#215b9d;background:#e2efff}.status-shipped{color:#1d6e38;background:#ddf5e4}.status-cancelled{color:#7b4650;background:#f6e6e9}.product-preview{display:flex;align-items:center;gap:5px}.product-thumb{width:32px;height:28px;display:grid;place-items:center;border:1px solid #cad4ca;border-radius:6px;color:#315139;background:linear-gradient(135deg,#e5eddf,#bdceb8);font:800 11px/1 Inter,sans-serif}.product-tone-1{color:#725333;background:linear-gradient(135deg,#f1e5d4,#d3b58d)}.product-tone-2{color:#3d526b;background:linear-gradient(135deg,#e1e9ef,#adbecd)}.product-preview small{color:#68736a;font-size:10px}.order-empty{padding:48px 20px;color:#7a847c;text-align:center}.order-center-footer{display:flex;align-items:center;justify-content:space-between;gap:20px;padding-top:16px}.order-center-footer p{margin:0;color:#7a847c;font-size:11px}.pagination{display:flex;gap:5px}.pagination button{min-width:31px;height:31px;border:1px solid #d8ddd7;border-radius:6px;color:#465149;background:#fff;cursor:pointer}.pagination button.active{color:#fff;border-color:var(--blue);background:var(--blue)}.pagination button:disabled{opacity:.4;cursor:default}.observability-proof{padding:88px 0 52px}.observability-proof-heading{margin-bottom:26px;display:grid;grid-template-columns:minmax(260px,.72fr) minmax(0,1.28fr);align-items:end;gap:34px}.observability-proof-heading h2{margin:8px 0 0;font-family:Georgia,"Noto Serif SC",serif;font-size:clamp(30px,4vw,48px);font-weight:500;line-height:1.05;letter-spacing:-.04em}.observability-proof-heading>p{margin:0;color:var(--muted);font-size:15px;line-height:1.7}.observability-proof-figure{margin:0}.observability-proof-figure img{width:100%;height:auto;display:block;border:1px solid #d7ddd5;border-radius:18px;background:#f4f5fb;box-shadow:0 22px 54px #1c2d221a}.observability-proof-figure figcaption{margin-top:12px;color:var(--muted);font-size:11px}footer{min-height:86px;display:flex;align-items:center;justify-content:space-between;color:var(--muted);font-size:12px}@media(max-width:980px){.page-shell{padding:0 24px}.hero{grid-template-columns:1fr;gap:46px;padding-top:58px}.model-map{min-height:260px}.runtime-language-panel{grid-template-columns:1fr}.runtime-language-selector{grid-template-columns:repeat(4,minmax(100px,1fr))}.development-process-heading{grid-template-columns:1fr;align-items:start;gap:24px}.development-process-flow{grid-template-columns:repeat(2,minmax(0,1fr))}.development-process-flow li:nth-child(3){border-left:0;border-top:1px solid #d7ddd3}.development-process-flow li:nth-child(4){border-top:1px solid #d7ddd3}.result-panel{margin:0 -24px;padding-left:24px;padding-right:24px}.result-grid{grid-template-columns:1fr}.observability-proof-heading{grid-template-columns:1fr;align-items:start;gap:14px}}@media(max-width:680px){.page-shell{padding:0 16px}.site-header{height:64px}.header-actions{gap:9px}.docs-link{display:none}h1{font-size:43px}.hero{min-height:auto;padding:48px 0}.hero-intro{font-size:16px}.model-map{gap:9px;padding:52px 22px 22px}.model-flow{grid-template-columns:1fr}.model-flow>span:not(.model-arrow),.model-leaves span{width:100%}.model-flow .model-arrow{transform:rotate(90deg)}.model-leaves{grid-template-columns:1fr}.runtime-language-panel{padding:20px 16px;gap:20px}.runtime-language-selector{grid-template-columns:repeat(2,minmax(0,1fr))}.runtime-language:last-child{grid-column:1 / -1}.development-process{margin-top:38px;padding:26px 18px}.development-process-intro>p{font-size:15px}.development-process-links{align-items:stretch;flex-direction:column}.source-link{min-width:0;width:100%}.development-process-flow{grid-template-columns:1fr}.development-process-flow li{border-top:1px solid #d7ddd3;border-left:0}.development-process-flow li:first-child{border-top:0}.development-process-flow li:nth-child(3),.development-process-flow li:nth-child(4){border-left:0}.development-process-flow strong,.development-process-flow p{min-height:0}.context-efficiency{grid-template-columns:1fr;gap:16px;padding:20px}.runtime-bar,.section-heading,.result-heading{align-items:flex-start;flex-direction:column}.runtime-bar{padding:18px}.controls{width:100%;justify-content:space-between}.query-browser{padding:70px 0 64px}.query-group{grid-template-columns:1fr;gap:14px}.query-links{gap:8px 18px}.result-panel{margin:0 -16px;padding:64px 16px}.result-actions{width:100%;align-items:stretch;flex-direction:column}.result-view-switch,.tree-actions{width:100%}.result-view-switch button,.tree-actions button{flex:1}.tree-leaf{grid-template-columns:minmax(90px,120px) 1fr;padding-left:15px}.json-tree{padding-left:12px;padding-right:12px}.observability-proof{padding:64px 0 34px}.observability-proof-figure img{border-radius:12px}} diff --git a/dist/assets/workItems-DS6iz1SR.js b/dist/assets/workItems-DS6iz1SR.js new file mode 100644 index 0000000000000000000000000000000000000000..eba613bc491f9fbe01bb45356541a36a8a0c04ac --- /dev/null +++ b/dist/assets/workItems-DS6iz1SR.js @@ -0,0 +1 @@ +import{S as it,f as j,E as k,g as Q,L as l,M as I,n as U,C as w,d as f,a as b,j as z,e as O,Q as J,U as K,R as rt,B as st,D as nt,c as ot}from"./dynamic-search-BwvXmN4R.js";import{EntityCreationError as H,EntityCreation as v}from"./entity-creation-Bqaw1C4U.js";class N extends it{orderBy(t,e){return this.order({field:t,expr:null,direction:e==="desc"?"Desc":"Asc"})}relationQuery(t,e,i="id",r="id",n=!0,s){return super.relationQuery(t,e,i,r,n,s)}}const R=Symbol("managed entity construction");class m{static teaqlTemporaryId=0;static teaqlMutationFields=new j("WorkItem",["id","title","description","platform","version"],{id:"immutable_field",version:"immutable_field"});id;title;description;platform;version;constructor(t,e,i=!1){if(e!==R)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--m.teaqlTemporaryId,writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];Object.assign(this,n),t.platform&&typeof t.platform=="object"&&(this.platform=t.platform instanceof p?t.platform:p.fromRecord(t.platform),this.markLoaded("platform"))}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"WorkItem",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){return this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t),this}static fromRecord(t,e){const i=v.hydrated(new m(t,R));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){return Object.fromEntries(Object.entries(this))}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return m.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"WorkItem",e,i=>new m({id:i},R,!0))}static teaqlCreate(t){return v.create(t,"WorkItem",e=>new m({id:e},R,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());return v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),i}teaqlValidateLoadedIdentities(t=new Set){t.has(this)||(t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version))}teaqlDiscardRestoredGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)))}teaqlNormalizeGraph(t,e=new Set){e.has(this)||(e.add(this),t.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{platform:"Platform"},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()}})))}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),m.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}return i}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(m.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){const d=[{member:"id",canonical:"id"},{member:"title",canonical:"title"},{member:"description",canonical:"description"},{member:"platform",canonical:"platform"},{member:"version",canonical:"version"}].find(u=>!this.isLoaded(u.member));if(d)throw new w([{ruleId:"invalid_type",entityType:"WorkItem",location:f.property(d.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"WorkItem",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y),y.scopeFor(this.teaqlEntityKey())}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"WorkItem",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey()))return d.scopeFor(this.teaqlEntityKey()),this;const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();return d.scopeFor(c),e.afterGraphRollback(()=>{for(const P of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,P)||delete this[P];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c),d.scopeFor(c),e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,title:this.title,description:this.description,platform:this.platform,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateTitle(t){return this.title=t,this.markLoaded("title"),this._root.set(this.teaqlEntityKey(),"title",t),this}updateDescription(t){return this.description=t,this.markLoaded("description"),this._root.set(this.teaqlEntityKey(),"description",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}updatePlatform(t){return this.platform=t?.id??t,this.markLoaded("platform"),this._root.set(this.teaqlEntityKey(),"platform",this.platform),this}}const T=Symbol("managed entity construction");class p{static teaqlTemporaryId=0;static teaqlMutationFields=new j("Platform",["id","name","version"],{id:"immutable_field",version:"immutable_field"});id;name;version;constructor(t,e,i=!1){if(e!==T)throw new H;if(Object.defineProperty(this,"_action",{value:i?"Create":"Update",writable:!0,enumerable:!1}),Object.defineProperty(this,"_comment",{value:void 0,writable:!0,enumerable:!1}),Object.defineProperty(this,"_fullyLoaded",{value:i,writable:!0,enumerable:!1}),Object.defineProperty(this,"_loadedFields",{value:new Set(Object.keys(t||{})),writable:!0,enumerable:!1}),Object.defineProperty(this,"_root",{value:new k,writable:!0,enumerable:!1}),Object.defineProperty(this,"_ledgerId",{value:t?.id??--p.teaqlTemporaryId,writable:!0,enumerable:!1}),Object.defineProperty(this,"_workItemList",{value:i?new b:b.empty(),writable:!0,enumerable:!1}),t){const n={...t};for(const s of["_action","_comment","_fullyLoaded","_loadedFields","_root","_ledgerId"])delete n[s];if(delete n.workItemList,Object.assign(this,n),Array.isArray(t.workItemList)){const s=t.workItemList;this._workItemList=new b(s.map(o=>o instanceof m?o:m.fromRecord(o)),{totalCount:s.totalCount,aggregations:s.aggregations,summary:s.summary,facets:s.facets,isLoaded:s.isLoaded??!0}),this.markLoaded("workItemList")}}const r=this.teaqlEntityKey();this.version!==void 0&&(this.version=Q(this.version)),this._action==="Create"?this._root.markAsNew(r):this.version!==void 0&&this._root.setOriginalVersion(r,this.version),l.captureFor(this,this.teaqlMutationPayload(),r,this.version,i?"creationBaseline":"hydrated")}teaqlEntityKey(){return{entity:"Platform",id:this._ledgerId}}teaqlAttachRoot(t,e=!1){this._root!==t&&(t.mergeEntityFrom(this._root,this.teaqlEntityKey()),this._root=t);for(const i of this._workItemList)i.teaqlAttachRoot(t,e);return this}static fromRecord(t,e){const i=v.hydrated(new p(t,T));return e?i.teaqlAttachRoot(e,!0):i}toJSON(){const t=Object.fromEntries(Object.entries(this));return this.isLoaded("workItemList")&&(t.workItemList=this._workItemList),t}isLoaded(t){return this._fullyLoaded||this._loadedFields.has(t)}markLoaded(...t){for(const e of t)this._loadedFields.add(e);return this}markLoadedOnly(...t){return this._fullyLoaded=!1,this._loadedFields=new Set(t),this}static refer(t){return p.fromRecord({id:String(t)})}static teaqlBootstrapNew(t,e){return v.bootstrap(t,"Platform",e,i=>new p({id:i},T,!0))}static teaqlCreate(t){return v.create(t,"Platform",e=>new p({id:e},T,!0))}markForDeletion(){return this._action="Delete",this._root.markAsDeleted(this.teaqlEntityKey()),this}auditAs(t){return this._comment=new I(t).comment,this}async save(t){if(new I(this._comment),this.teaqlValidateLoadedIdentities(),!this.teaqlValidateMutationOrigins())return this;const e=t.requireResource("dataService");return e.executeGraphSave(new I(this._comment),async i=>this.teaqlSaveWithinGraph(t,e,i),i=>{this.teaqlPreflightGraph(t,e,i),this.teaqlValidateLoadedIdentities(),this.teaqlAdmitGraph(),i.sealPreparedGraph()},i=>(this.teaqlValidateLoadedIdentities(),this.teaqlDiscardRestoredGraph(i),this.teaqlAdmitGraph(),this.teaqlNormalizeGraph(i),this.teaqlAdmitGraph()))}teaqlValidateMutationOrigins(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action;let i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i);for(const r of this._workItemList)i=r.teaqlValidateMutationOrigins(t)||i;return i}teaqlValidateLoadedIdentities(t=new Set){if(!t.has(this)){t.add(this),l.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(),this.id,this.version);for(const[e,i]of this._workItemList.entries())try{i.teaqlValidateLoadedIdentities(t)}catch(r){if(!(r instanceof w))throw r;const n=f.property("work_item_list").index(e);throw new w(r.violations.map(s=>({...s,location:s.location.prefixedBy(n)})))}}}teaqlDiscardRestoredGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));for(const i of this._workItemList)i.teaqlDiscardRestoredGraph(t,e)}}teaqlNormalizeGraph(t,e=new Set){if(!e.has(this)){e.add(this),t.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this)),t.registerSource(this,this._root,this.teaqlEntityKey(),{},()=>({...this.teaqlMutationPayload(),__teaql_key:this.teaqlEntityKey(),__teaql_action:this._action,__teaql_comment:this._comment,__teaql_load:{fullyLoaded:this._fullyLoaded,fields:[...this._loadedFields].sort()},work_item_list:t.sourceMembers(this._workItemList)}));for(const i of this._workItemList){i.teaqlAttachRoot(this._root);const r=i.platform;(i._action!=="Update"||i._root.hasPending(i.teaqlEntityKey()))&&(this.id===void 0||!i.isLoaded("platform")||(typeof r=="object"&&r!==null?r.id:r)!==this.id)&&i.updatePlatform(this),i.teaqlNormalizeGraph(t,e)}}}teaqlAdmitGraph(t=new Set){if(t.has(this))return!1;t.add(this);const e=this._action,i=e!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(v.requireMutation(this,this.teaqlEntityKey(),this.id,e,this._root,i),l.forEntity(this)?.validateMutationVersion(this._root,this.teaqlEntityKey()),p.teaqlMutationFields.validate(this._root.change(this.teaqlEntityKey()),e==="Update"),i&&(U(e,l.forEntity(this)?.persistedVersion),e==="Update")){const n=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(s=>!this.isLoaded(s.member));if(n)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(n.canonical),message:"Mutation requires a fully loaded entity"}])}let r=i;for(const[n,s]of this._workItemList.entries())try{r=s.teaqlAdmitGraph(t)||r}catch(o){if(!(o instanceof w))throw o;const y=f.property("work_item_list").index(n);throw new w(o.violations.map(d=>({...d,location:d.location.prefixedBy(y)})))}return r}teaqlPreflightGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return;n.add(this);const s=this._action;i.discardRestoredFields(p.teaqlMutationFields,this._root,this.teaqlEntityKey(),l.forEntity(this));const o=s!=="Update"||this._root.hasPending(this.teaqlEntityKey());if(s==="Update"&&o){const u=[{member:"id",canonical:"id"},{member:"name",canonical:"name"},{member:"version",canonical:"version"}].find(a=>!this.isLoaded(a.member));if(u)throw new w([{ruleId:"invalid_type",entityType:"Platform",location:f.property(u.canonical),message:"Mutation requires a fully loaded entity"}])}const y=i.request({entity:"Platform",action:s,payload:s==="Update"?this._root.change(this.teaqlEntityKey()):this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);o&&e.preflightMutation(y);const d=y.scopeFor(this.teaqlEntityKey());for(const[u,a]of this._workItemList.entries()){a.teaqlAttachRoot(this._root);const q=a.platform;(a._action!=="Update"||a._root.hasPending(a.teaqlEntityKey()))&&(this.id===void 0||!a.isLoaded("platform")||(typeof q=="object"&&q!==null?q.id:q)!==this.id)&&a.updatePlatform(this);try{a.teaqlPreflightGraph(t,e,i,d,n)}catch(c){if(!(c instanceof w))throw c;const $=f.property("work_item_list").index(u);throw new w(t.translateCheckResults(c.violations.map(P=>({...P,location:P.location.prefixedBy($)}))))}}}async teaqlSaveWithinGraph(t,e,i,r,n=new Set){if(r||new I(this._comment),n.has(this))return this;n.add(this);const s=this._action,o=this._root.change(this.teaqlEntityKey()),y={entity:"Platform",action:this._action,payload:s==="Update"?o:this.teaqlMutationPayload(),id:this.id,version:l.forEntity(this)?.persistedVersion,comment:this._comment,ledgerKey:this.teaqlEntityKey(),ledgerRoot:this._root},d=i.request(y,r,this._comment).withLoadedSnapshot(l.forEntity(this)??new l);if(s==="Update"&&!this._root.hasPending(this.teaqlEntityKey())){const L=d.scopeFor(this.teaqlEntityKey());for(const[_,g]of this._workItemList.entries()){g.teaqlAttachRoot(this._root);const E=g.platform;(g._action!=="Update"||g._root.hasPending(g.teaqlEntityKey()))&&(this.id===void 0||!g.isLoaded("platform")||(typeof E=="object"&&E!==null?E.id:E)!==this.id)&&g.updatePlatform(this);try{await g.teaqlSaveWithinGraph(t,e,i,L,n)}catch(C){if(!(C instanceof w))throw C;const F=f.property("work_item_list").index(_);throw new w(t.translateCheckResults(C.violations.map(V=>({...V,location:V.location.prefixedBy(F)}))))}}return this}const u=await e.executeMutation(d);if(i.validatePreparedSources(),!u.persistedRecord)throw new Error("Mutation did not return the authoritative persisted record");const a={ownProperties:Object.getOwnPropertyDescriptors(this),ledgerId:this._ledgerId,action:this._action,loadedFields:new Set(this._loadedFields),fullyLoaded:this._fullyLoaded,loadedSnapshot:l.forEntity(this)},q=this.teaqlEntityKey();Object.assign(this,u.persistedRecord),this._ledgerId=this.id??this._ledgerId;const c=this.teaqlEntityKey();this._root.rekey(q,c);const $=this.teaqlScalarSnapshot();d.scopeFor(c),e.afterGraphRollback(()=>{for(const L of Object.getOwnPropertyNames(this))Object.prototype.hasOwnProperty.call(a.ownProperties,L)||delete this[L];Object.defineProperties(this,a.ownProperties),this._ledgerId=a.ledgerId,this._action=a.action,this._loadedFields=a.loadedFields,this._fullyLoaded=a.fullyLoaded,l.restoreFor(this,a.loadedSnapshot),this._root.rekey(c,q)}),this._loadedFields=new Set(Object.keys(u.persistedRecord)),this._fullyLoaded=!1,y.action!=="Delete"&&(this._action="Update"),i.acceptPreparedResult(this._root,q,c);const P=d.scopeFor(c);for(const[L,_]of this._workItemList.entries()){_.teaqlAttachRoot(this._root);const g=_.platform;(_._action!=="Update"||_._root.hasPending(_.teaqlEntityKey()))&&(this.id===void 0||!_.isLoaded("platform")||(typeof g=="object"&&g!==null?g.id:g)!==this.id)&&_.updatePlatform(this);try{await _.teaqlSaveWithinGraph(t,e,i,P,n)}catch(E){if(!(E instanceof w))throw E;const C=f.property("work_item_list").index(L);throw new w(t.translateCheckResults(E.violations.map(F=>({...F,location:F.location.prefixedBy(C)}))))}}return e.afterGraphCommit(()=>{i.validatePreparedSources(),l.restoreFor(this,$),this._root.clearEntity(c),this.version!==void 0&&this._root.acceptCommittedVersion(c,this.version),i.finishPreparedCommit(this._root,c)}),this}teaqlMutationPayload(){return{id:this.id,name:this.name,version:this.version}}teaqlScalarSnapshot(){return new l(this.teaqlMutationPayload(),this.teaqlEntityKey(),this.version)}updateId(t){return this.id=t,this.markLoaded("id"),this._root.set(this.teaqlEntityKey(),"id",t),this}updateName(t){return this.name=t,this.markLoaded("name"),this._root.set(this.teaqlEntityKey(),"name",t),this}updateVersion(t){return this.version=t,this.markLoaded("version"),this._root.set(this.teaqlEntityKey(),"version",t),this}workItemList(){return this._workItemList}}const Y=Object.freeze({Platform:Object.freeze({fields:Object.freeze({id:"integer",name:"string",version:"integer"}),queryFields:Object.freeze({id:"id",name:"name",version:"version"}),relations:Object.freeze({workItemList:"WorkItem"})}),WorkItem:Object.freeze({fields:Object.freeze({id:"integer",title:"string",description:"string",platform:"integer",version:"integer"}),queryFields:Object.freeze({id:"id",title:"title",description:"description",platform:"platform",version:"version"}),relations:Object.freeze({platform:"Platform"})})});class D{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("Platform"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"Platform"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=z(i,t,Y,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new at(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","name","version"]),this}selectId(){return this.query.select(["id"]),this}selectName(){return this.query.select(["name"]),this}selectVersion(){return this.query.select(["version"]),this}selectWorkItemListWith(t){return this.query.relationQuery("workItemList",t.toQuery(),"id","platform",!0,{kind:"relation-select",method:"selectWorkItemListWith",relation:"workItemList"}),this}haveWorkItems(){return this.withWorkItemListMatching({entityName:"WorkItem",toQuery:()=>new N("WorkItem")})}haveNoWorkItems(){return this.withoutWorkItemListMatching({entityName:"WorkItem",toQuery:()=>new N("WorkItem")})}withWorkItemListMatching(t){return this.filters.push({id:{$inSubquery:{query:t.toQuery(),field:"platform"}}}),this}withoutWorkItemListMatching(t){return this.filters.push({id:{$notInSubquery:{query:t.toQuery(),field:"platform"}}}),this}countWorkItems(){return this.countWorkItemsAs("countWorkItems")}countWorkItemsAs(t){const e=new N("WorkItem").filter({version:{$gte:1}});return this.countWorkItemsWith(t,{entityName:"WorkItem",toQuery:()=>e}),this.query.relationAggregates[this.query.relationAggregates.length-1].operation={kind:"relation-count",method:"countWorkItemsAs",relation:"workItemList",alias:t},this}countWorkItemsWith(t,e){const i=e.toQuery().clone();return i.aggregateItems=[],i.aggregate("Count","id",t),this.query.relationAggregate("workItemList",t,i,!0,{kind:"relation-count",method:"countWorkItemsWith",relation:"workItemList",alias:t}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withNameContaining(t){return this.filters.push({name:{$contains:t}}),this}withNameIs(t){return this.filters.push({name:{$eq:t}}),this}withNameIsNot(t){return this.filters.push({name:{$ne:t}}),this}withNameIn(...t){return this.filters.push({name:{$in:t}}),this}withNameNotIn(...t){return this.filters.push({name:{$notIn:t}}),this}withNameGreaterThan(t){return this.filters.push({name:{$gt:t}}),this}withNameGreaterThanOrEqualTo(t){return this.filters.push({name:{$gte:t}}),this}withNameLessThan(t){return this.filters.push({name:{$lt:t}}),this}withNameLessThanOrEqualTo(t){return this.filters.push({name:{$lte:t}}),this}withNameBetween(t,e){return this.filters.push({name:{$between:[t,e]}}),this}withNameIsKnown(){return this.filters.push({name:{$isNull:!1}}),this}withNameIsUnknown(){return this.filters.push({name:{$isNull:!0}}),this}withNameNotContaining(t){return this.filters.push({name:{$notContains:t}}),this}withNameStartingWith(t){return this.filters.push({name:{$startsWith:t}}),this}withNameNotStartingWith(t){return this.filters.push({name:{$notStartsWith:t}}),this}withNameEndingWith(t){return this.filters.push({name:{$endsWith:t}}),this}withNameNotEndingWith(t){return this.filters.push({name:{$notEndsWith:t}}),this}withNameSoundingLike(t){return this.filters.push({name:{$soundLike:t}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByNameAscending(){return this.query.orderBy("name","asc"),this}orderByNameDescending(){return this.query.orderBy("name","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByName(){return this.query.groupBy("name"),this}groupByNameAs(t){return this.query.groupBy("name",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,n=r?[]:i.map(o=>o instanceof p?o:p.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof p?a:p.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof p?o:p.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class at{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return p.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class G{query;filters=[];_purpose;_comment;_pageCountAlias;_pageCountMethod;_dynamicSearchWarnings=[];constructor(t=!1){this.query=new N("WorkItem"),this.filters.push({version:{$gte:1}}),t?(this.selectId(),this.selectVersion()):this.selectSelfFields()}get entityName(){return"WorkItem"}comment(t){return this.query.comment(t),this._comment=t,this}filterByJson(t,e){const i=this.query.clone();this.filters.length>0&&i.filter({$and:this.filters});const r=z(i,t,Y,e);return this.query=r.query,this.filters=this.query.filterCondition?[this.query.filterCondition]:[],this._dynamicSearchWarnings.push(...r.warnings),this}get dynamicSearchWarnings(){return this._dynamicSearchWarnings.map(t=>({...t}))}purpose(t){return this.query.purpose(t),this._purpose=t,new ht(e=>e.withQueryRequest(this.query,()=>this.executeForListInternal(e)),e=>e.withQueryRequest(this.query,()=>this.executeForRowsInternal(e)),(e,i)=>this.executeForStreamInternal(e,i),()=>this.limit(1),e=>this.comment(e),()=>this.ensureIntent())}optimizeForContinuousPageFetch(){return this.query.optimizeForContinuousPageFetch(),this}optimizeForContinuousPageFetchWith(t,e){return this.query.optimizeForContinuousPageFetchWith(t,e),this}optimizePaginationWithIdSet(){return this.query.optimizePaginationWithIdSet(),this}optimizePaginationWithIdSetConfig(t,e,i){return this.query.optimizePaginationWithIdSetConfig(t,e,i),this}topNProbeParentThreshold(t){return this.query.topNProbeParentThreshold(t),this}limit(t){return this.query.limit(t),this}offset(t){return this.query.offset(t),this}toQuery(){return this.filters.length>0&&this.query.filter({$and:this.filters}),this.query}withDeletedRows(){return this.query.withDeletedRows(),this.filters=this.filters.filter(t=>!("version"in t)),this}deletedRowsOnly(){return this.withDeletedRows(),this.query.deletedRowsOnly(),this.filters.push({version:{$lte:-1}}),this}selectSelfFields(){return this.query.select(["id","title","description","platform","version"]),this}selectId(){return this.query.select(["id"]),this}selectTitle(){return this.query.select(["title"]),this}selectDescription(){return this.query.select(["description"]),this}selectVersion(){return this.query.select(["version"]),this}selectPlatformWith(t){return this.query.select(["platform"]),this.query.relationQuery("platform",t.toQuery(),"platform","id",!1,{kind:"relation-select",method:"selectPlatformWith",relation:"platform"}),this}withPlatformMatching(t){return this.filters.push({platform:{$inSubquery:{query:t.toQuery(),field:"id"}}}),this}withoutPlatformMatching(t){return this.filters.push({platform:{$notInSubquery:{query:t.toQuery(),field:"id"}}}),this}withIdIs(t){return this.filters.push({id:{$eq:t}}),this}withIdIsNot(t){return this.filters.push({id:{$ne:t}}),this}withIdIn(...t){return this.filters.push({id:{$in:t}}),this}withIdNotIn(...t){return this.filters.push({id:{$notIn:t}}),this}withIdGreaterThan(t){return this.filters.push({id:{$gt:t}}),this}withIdGreaterThanOrEqualTo(t){return this.filters.push({id:{$gte:t}}),this}withIdLessThan(t){return this.filters.push({id:{$lt:t}}),this}withIdLessThanOrEqualTo(t){return this.filters.push({id:{$lte:t}}),this}withIdBetween(t,e){return this.filters.push({id:{$between:[t,e]}}),this}withIdIsKnown(){return this.filters.push({id:{$isNull:!1}}),this}withIdIsUnknown(){return this.filters.push({id:{$isNull:!0}}),this}withTitleContaining(t){return this.filters.push({title:{$contains:t}}),this}withTitleIs(t){return this.filters.push({title:{$eq:t}}),this}withTitleIsNot(t){return this.filters.push({title:{$ne:t}}),this}withTitleIn(...t){return this.filters.push({title:{$in:t}}),this}withTitleNotIn(...t){return this.filters.push({title:{$notIn:t}}),this}withTitleGreaterThan(t){return this.filters.push({title:{$gt:t}}),this}withTitleGreaterThanOrEqualTo(t){return this.filters.push({title:{$gte:t}}),this}withTitleLessThan(t){return this.filters.push({title:{$lt:t}}),this}withTitleLessThanOrEqualTo(t){return this.filters.push({title:{$lte:t}}),this}withTitleBetween(t,e){return this.filters.push({title:{$between:[t,e]}}),this}withTitleIsKnown(){return this.filters.push({title:{$isNull:!1}}),this}withTitleIsUnknown(){return this.filters.push({title:{$isNull:!0}}),this}withTitleNotContaining(t){return this.filters.push({title:{$notContains:t}}),this}withTitleStartingWith(t){return this.filters.push({title:{$startsWith:t}}),this}withTitleNotStartingWith(t){return this.filters.push({title:{$notStartsWith:t}}),this}withTitleEndingWith(t){return this.filters.push({title:{$endsWith:t}}),this}withTitleNotEndingWith(t){return this.filters.push({title:{$notEndsWith:t}}),this}withTitleSoundingLike(t){return this.filters.push({title:{$soundLike:t}}),this}withDescriptionContaining(t){return this.filters.push({description:{$contains:t}}),this}withDescriptionIs(t){return this.filters.push({description:{$eq:t}}),this}withDescriptionIsNot(t){return this.filters.push({description:{$ne:t}}),this}withDescriptionIn(...t){return this.filters.push({description:{$in:t}}),this}withDescriptionNotIn(...t){return this.filters.push({description:{$notIn:t}}),this}withDescriptionGreaterThan(t){return this.filters.push({description:{$gt:t}}),this}withDescriptionGreaterThanOrEqualTo(t){return this.filters.push({description:{$gte:t}}),this}withDescriptionLessThan(t){return this.filters.push({description:{$lt:t}}),this}withDescriptionLessThanOrEqualTo(t){return this.filters.push({description:{$lte:t}}),this}withDescriptionBetween(t,e){return this.filters.push({description:{$between:[t,e]}}),this}withDescriptionIsKnown(){return this.filters.push({description:{$isNull:!1}}),this}withDescriptionIsUnknown(){return this.filters.push({description:{$isNull:!0}}),this}withDescriptionNotContaining(t){return this.filters.push({description:{$notContains:t}}),this}withDescriptionStartingWith(t){return this.filters.push({description:{$startsWith:t}}),this}withDescriptionNotStartingWith(t){return this.filters.push({description:{$notStartsWith:t}}),this}withDescriptionEndingWith(t){return this.filters.push({description:{$endsWith:t}}),this}withDescriptionNotEndingWith(t){return this.filters.push({description:{$notEndsWith:t}}),this}withDescriptionSoundingLike(t){return this.filters.push({description:{$soundLike:t}}),this}filterByPlatform(t){return this.filters.push({platform:{$eq:t}}),this}filterByPlatformIn(...t){return this.filters.push({platform:{$in:t}}),this}withPlatformIsKnown(){return this.filters.push({platform:{$isNull:!1}}),this}withPlatformIsUnknown(){return this.filters.push({platform:{$isNull:!0}}),this}withVersionIs(t){return this.filters.push({version:{$eq:t}}),this}withVersionIsNot(t){return this.filters.push({version:{$ne:t}}),this}withVersionIn(...t){return this.filters.push({version:{$in:t}}),this}withVersionNotIn(...t){return this.filters.push({version:{$notIn:t}}),this}withVersionGreaterThan(t){return this.filters.push({version:{$gt:t}}),this}withVersionGreaterThanOrEqualTo(t){return this.filters.push({version:{$gte:t}}),this}withVersionLessThan(t){return this.filters.push({version:{$lt:t}}),this}withVersionLessThanOrEqualTo(t){return this.filters.push({version:{$lte:t}}),this}withVersionBetween(t,e){return this.filters.push({version:{$between:[t,e]}}),this}withVersionIsKnown(){return this.filters.push({version:{$isNull:!1}}),this}withVersionIsUnknown(){return this.filters.push({version:{$isNull:!0}}),this}orderByIdAscending(){return this.query.orderBy("id","asc"),this}orderByIdDescending(){return this.query.orderBy("id","desc"),this}orderByTitleAscending(){return this.query.orderBy("title","asc"),this}orderByTitleDescending(){return this.query.orderBy("title","desc"),this}orderByDescriptionAscending(){return this.query.orderBy("description","asc"),this}orderByDescriptionDescending(){return this.query.orderBy("description","desc"),this}orderByVersionAscending(){return this.query.orderBy("version","asc"),this}orderByVersionDescending(){return this.query.orderBy("version","desc"),this}count(){return this.query.aggregate("Count","id","count"),this._pageCountAlias="count",this._pageCountMethod="count",this}countAs(t){return this.query.aggregate("Count","id",t),this._pageCountAlias=t,this._pageCountMethod="countAs",this}groupById(){return this.query.groupBy("id"),this}groupByIdAs(t){return this.query.groupBy("id",t),this}groupByTitle(){return this.query.groupBy("title"),this}groupByTitleAs(t){return this.query.groupBy("title",t),this}groupByDescription(){return this.query.groupBy("description"),this}groupByDescriptionAs(t){return this.query.groupBy("description",t),this}groupByPlatform(){return this.query.groupBy("platform"),this}groupByPlatformAs(t){return this.query.groupBy("platform",t),this}groupByVersion(){return this.query.groupBy("version"),this}groupByVersionAs(t){return this.query.groupBy("version",t),this}facetByPlatformAs(t,e,i=!0){return this.query.facetBy(t,"platform",e,i,{kind:"facet",method:"facetByPlatformAs",relation:"platform",alias:t}),this}async executeForListInternal(t){if(this.ensureIntent(),this._pageCountAlias!==void 0)return this.executeCountedListInternal(t);this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=await e.executeQuery(t.prepareQuery(this.query)),r=this.query.aggregateItems.length>0&&this.query.groupByItems.length===0,n=r?[]:i.map(o=>o instanceof m?o:m.fromRecord(o,new k)),s=new b(n);return r&&i[0]&&Object.assign(s.aggregations,i[0]),this.query.facets.length>0&&(s.facets=await O(e,o=>t.prepareQuery(o),this.query,this.query.facets)),s}async executeForRowsInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService");return new b(await e.executeQuery(t.prepareQuery(this.query)))}async executeCountedListInternal(t){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const e=t.requireResource("dataService"),i=t.prepareQuery(this.query),r=i.localIdSetPaginationOptions()!==void 0,n={kind:"named-count",method:this._pageCountMethod??"count",...this._pageCountMethod==="countAs"?{alias:this._pageCountAlias}:{}},s=r?void 0:await e.executeCount(i,this._pageCountAlias,n),o=i.clone();o.aggregateItems=o.aggregateItems.filter(a=>!(String(a.function).toLowerCase()==="count"&&a.alias===this._pageCountAlias));const y=await e.executeQuery(o),d=r&&t.idSetPaginationCountAccuracy==="EXACT"?t.idSetPaginationCount:s??await e.executeCount(i,this._pageCountAlias,n),u=new b(y.map(a=>a instanceof m?a:m.fromRecord(a,new k)));return u.totalCount=d,this._pageCountAlias!==void 0&&(u.aggregations[this._pageCountAlias]=d),this.query.facets.length>0&&(u.facets=await O(e,a=>t.prepareQuery(a),i,i.facets)),u}executeForStreamInternal(t,e){this.ensureIntent(),this.filters.length>0&&this.query.filter({$and:this.filters});const i=t.requireResource("dataService"),r=t.prepareQuery(this.query),n=i.executeForStream(r,e);return(async function*(){for await(const s of n)for(const o of s)yield o instanceof m?o:m.fromRecord(o,new k)})()}ensureIntent(){new J(this._comment,this._purpose)}}class ht{constructor(t,e,i,r,n,s){this.execute=t,this.executeRows=e,this.stream=i,this.limitOne=r,this.addComment=n,this.ensureIntent=s}execute;executeRows;stream;limitOne;addComment;ensureIntent;comment(t){return this.addComment(t),this}async newEntity(t){if(this.ensureIntent(),!(t instanceof K))throw new TypeError("UserContext is required for creation");return m.teaqlCreate(t)}executeForList(t){return this.ensureIntent(),this.execute(t)}executeForRows(t){return this.ensureIntent(),this.executeRows(t)}executeForStream(t,e=1e3){return this.ensureIntent(),this.stream(t,e)}async executeForOne(t){return this.limitOne(),(await this.executeForList(t))[0]}}class A{static platforms(){return new D(!1)}static platformsWithMinimalFields(){return new D(!0)}static workItems(){return new G(!1)}static workItemsWithMinimalFields(){return new G(!0)}}const lt={Platform:{table:"platform_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",auditMaskFields:[],columns:{id:{columnName:"id",modelName:"id",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logPolicy:"plain",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logPolicy:"plain",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logPolicy:"plain",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}};async function ut(h){let t=(await A.platforms().withIdIs("1").comment("what: locate generated Domain Root").purpose("why: idempotent runtime bootstrap").executeForList(h))[0];t||(t=p.teaqlBootstrapNew(h,"1"),t.updateName("Runtime Example"),await t.auditAs("create generated Domain Root Platform").save(h)),h.withActiveRoot({entity:"Platform",id:t.id})}const dt=new rt(lt,{Platform:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.name===void 0||t.payload.name===null)&&e.push({ruleId:"required",location:f.property("name")}),t.payload.name!=null&&[...String(t.payload.name)].length>100&&e.push({ruleId:"max_length",location:f.property("name"),inputValue:t.payload.name,systemValue:100})}},WorkItem:{checkAndFix(h,t,e){h.getResource("fixTime"),(t.action==="Create"&&t.payload.title===void 0||t.payload.title===null)&&e.push({ruleId:"required",location:f.property("title")}),t.payload.title!=null&&!([...String(t.payload.title)].length>=1)&&e.push({ruleId:"min_length",location:f.property("title"),inputValue:t.payload.title,systemValue:1}),t.payload.title!=null&&[...String(t.payload.title)].length>80&&e.push({ruleId:"max_length",location:f.property("title"),inputValue:t.payload.title,systemValue:80}),t.payload.description!=null&&[...String(t.payload.description)].length>100&&e.push({ruleId:"max_length",location:f.property("description"),inputValue:t.payload.description,systemValue:100}),(t.action==="Create"&&t.payload.platform===void 0||t.payload.platform===null)&&e.push({ruleId:"required",location:f.property("platform")})}}},{defaultDomainRoot:{entity:"Platform",id:"1",values:{name:"Runtime Example"}},constants:[],ensure:ut}),ct={Platform:{table:"platform_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},name:{columnName:"name",modelName:"name",logicalType:"text",decode:"native",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{workItemList:{targetEntity:"WorkItem",localKey:"id",foreignKey:"platform",many:!0}}},WorkItem:{table:"work_item_data",columns:{id:{columnName:"id",modelName:"id",logicalType:"integer",decode:"string",nullable:!1},title:{columnName:"title",modelName:"title",logicalType:"text",decode:"native",nullable:!1},description:{columnName:"description",modelName:"description",logicalType:"text",decode:"native",nullable:!0},platform:{columnName:"platform",modelName:"platform",logicalType:"integer",decode:"string",nullable:!1},version:{columnName:"version",modelName:"version",logicalType:"integer",decode:"number",nullable:!1}},relations:{platform:{targetEntity:"Platform",localKey:"platform",foreignKey:"id",many:!1}}}},x=document.querySelector("#status"),pt=document.querySelector("#result"),B=document.querySelector("#persist"),W=document.querySelector("#reset");let S;const X=localStorage.getItem("teaql-browser-storage")==="opfs"?"opfs":"memory";B.checked=X==="opfs";async function mt(h){const t=new Worker(new URL("/assets/sqlite.worker-BcUEWFpc.js",import.meta.url),{type:"module"}),e=await st.open(t,{...ct},{storage:h,databaseName:"teaql-browser-example.sqlite3"});e.install(dt);const i=Object.freeze({policyId:"browser-demo-seed",version:"1",fingerprint:"sha256:browser-demo-seed-v1"}),r=new K().insertResource("dataService",e).withMutationPolicyRegistry(new nt(()=>({identity:i,review:(n,s)=>s.operations.length>0?{verdict:"allow"}:{verdict:"deny",code:"EMPTY_GRAPH",message:"empty mutation graph"}}))).withMutationPolicyApprovalProvider(new ot(n=>({policy:n,approvedBy:"browser-demo-owner",approvedAt:new Date})));return e.setUserContext(r),await r.ensureSchema(),{client:e,context:r}}async function Z({context:h}){if(!(await A.workItemsWithMinimalFields().comment("what: detect existing browser demo records").purpose("why: keep generated mutation bootstrap idempotent").executeForList(h)).length)for(const e of["Evaluate semantic model","Generate typed library","Verify browser runtime"])await(await A.workItems().comment("reserve one browser demo work item").purpose("seed deterministic data through managed creation").newEntity(h)).updateTitle(e).updatePlatform("1").auditAs("seed deterministic browser demo data").save(h)}async function tt(h){const t=await A.workItems().selectTitle().orderByIdAscending().limit(20).comment("what: load browser-local work items").purpose("why: prove the generated Q API runs without a backend").executeForList(h.context);pt.textContent=JSON.stringify(t,null,2),x.textContent=`${h.client.storage.toUpperCase()} · ${t.length} rows · policy installed · ready`}async function et(h){x.textContent=`Opening ${h.toUpperCase()} SQLite/WASM…`;const t=S;S=void 0,await t?.client.close();const e=await mt(h);S=e,await Z(e),await tt(e)}B.addEventListener("change",()=>{const h=B.checked?"opfs":"memory";localStorage.setItem("teaql-browser-storage",h),et(h).catch(M)});W.addEventListener("click",async()=>{if(S){W.disabled=!0;try{await S.client.reset(S.context),await Z(S),await tt(S)}catch(h){M(h)}finally{W.disabled=!1}}});function M(h){const t=h instanceof Error?h:new Error(String(h));x.textContent=`${t.name}: ${t.message}`}et(X).catch(M); diff --git a/dist/index.html b/dist/index.html index e52fb43b9d10d471dacd39ae4382f1df68c87ee0..e8ca40c51697d840847240888be5594b8c007f06 100644 --- a/dist/index.html +++ b/dist/index.html @@ -6,9 +6,9 @@ TeaQL Order Query Playground - - - + + +
@@ -96,6 +96,63 @@ +
+
+
+

00 / DEVELOPMENT PROCESS

+

From one domain model to executable evidence.

+
+
+

TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.

+ +
+
+ +
    +
  1. + 01 + Model the domain +

    Define entities, fields, relationships, constant objects, and constraints in one model file.

    + order-model.xml +
  2. +
  3. + 02 + Generate the working surface +

    Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.

    + Q · E · Schema · Assist +
  4. +
  5. + 03 + Build one bounded Q request +

    Application code selects only what the page needs and attaches a readable comment and purpose.

    + comment · purpose · execute +
  6. +
  7. + 04 + Run and retain evidence +

    The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.

    + Result · TraceChain · SQL +
  8. +
+ +
+
+

CONTEXT EFFICIENCY

+

Spend context on the business change.

+
+

Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.

+
+
+

Starting SQLite/WASM…

diff --git a/dist/orders.html b/dist/orders.html index 149b950dcddc087b45bcf0a33767ad765801f47f..6fecb9fdb12d4fbfe7522450bac07f7c1b684198 100644 --- a/dist/orders.html +++ b/dist/orders.html @@ -5,10 +5,10 @@ TeaQL browser order TraceChain - - - - + + + +
diff --git a/dist/work-items.html b/dist/work-items.html index b23ddbf029e4c4748ef1196d6322f43bc53c3919..6d8758844bcedee460faa677c83658a66ed75a1c 100644 --- a/dist/work-items.html +++ b/dist/work-items.html @@ -5,9 +5,9 @@ TeaQL Browser SQLite WorkItems - - - + + + diff --git a/index.html b/index.html index e52fb43b9d10d471dacd39ae4382f1df68c87ee0..e8ca40c51697d840847240888be5594b8c007f06 100644 --- a/index.html +++ b/index.html @@ -6,9 +6,9 @@ TeaQL Order Query Playground - - - + + +
@@ -96,6 +96,63 @@
+
+
+
+

00 / DEVELOPMENT PROCESS

+

From one domain model to executable evidence.

+
+
+

TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.

+ +
+
+ +
    +
  1. + 01 + Model the domain +

    Define entities, fields, relationships, constant objects, and constraints in one model file.

    + order-model.xml +
  2. +
  3. + 02 + Generate the working surface +

    Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.

    + Q · E · Schema · Assist +
  4. +
  5. + 03 + Build one bounded Q request +

    Application code selects only what the page needs and attaches a readable comment and purpose.

    + comment · purpose · execute +
  6. +
  7. + 04 + Run and retain evidence +

    The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.

    + Result · TraceChain · SQL +
  8. +
+ +
+
+

CONTEXT EFFICIENCY

+

Spend context on the business change.

+
+

Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.

+
+
+

Starting SQLite/WASM…

diff --git a/orders.html b/orders.html index 149b950dcddc087b45bcf0a33767ad765801f47f..6fecb9fdb12d4fbfe7522450bac07f7c1b684198 100644 --- a/orders.html +++ b/orders.html @@ -5,10 +5,10 @@ TeaQL browser order TraceChain - - - - + + + +
diff --git a/source/provenance.json b/source/provenance.json index d5c04dce30a9811537675ca8350d1f76c38c5810..bb7ce5b12539135e420d1af73854be724f796280 100644 --- a/source/provenance.json +++ b/source/provenance.json @@ -1,17 +1,17 @@ { "repository": "https://github.com/teaql/teaql-ts", - "commit": "1e1f50e7a54f2f47753a24cdd988e53fbde78180", + "commit": "b7c0f71f717d368c222da7cc8484db32bf281f11", "branch": "main", - "runtimeVersion": "0.3.1", + "runtimeVersion": "0.6.0", "sourceDirectory": "source/teaql-ts", "applicationDirectory": "source/teaql-ts/examples/browser-sqlite", "buildDirectory": "dist", "validation": { - "runtimeSuitesPassed": 57, - "runtimeTestsPassed": 608, - "runtimeTestsSkipped": 6, + "runtimeBuild": "passed", + "browserBuild": "passed", "browserSmoke": "passed", - "generatedOrderSmoke": "passed" + "generatedOrderSmoke": "passed", + "visualQA": "desktop and 390px English/Chinese" }, "limitations": [ "No application backend", diff --git a/source/teaql-ts/.github/release-signing-key.asc b/source/teaql-ts/.github/release-signing-key.asc new file mode 100644 index 0000000000000000000000000000000000000000..a0213ccc759bfdc5a9cf01a1338e51acfcfe1c45 --- /dev/null +++ b/source/teaql-ts/.github/release-signing-key.asc @@ -0,0 +1,52 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mQINBGpsF40BEAC+Olumai3qpCWXV6QYFufotbsG2TK+mIvFfHxOjX0qq24PsGW7 +D3iXxAYxG1Ohu3dNIM7Rj2lvLpxL1si6pJCvuD8vSnuhuubcpOJJIhGeG4S+r3sy +CFbgYw5Wde0t9MG4Gr5+p6OB0o3yeOeLB8Xeyk+jTZ/O9ukGgpGANNu8wMpEKE5t +06mjYPcajUdpPCs0FIC9WhyyPBQw4CLywMuJ1amnrs+yWDyaJogkw39m1/VZtnHE +FEg9PLg3SKq60DydI2kiOL2ozum/nj9y0Oe+wxNH+k+ACokZsoGV5PMG+PcDsOO/ +dPQ1v1Jm7aKAl6pyyV/jCq9tU43toKXD5MHm8Rffsb1nfgRHERzbqcl9bxsxmk1/ +62ePdc3RWiqlMS0YdqXYkd7yFtrZmJUL5xrRB0bI5tEbH0i4yema73WeSMV4PSlq +xU71TdA41Tq9OgmKKpVfWAThunKg50Dt1JXApTnCVMuEG+ejdvzXDwqlH+T9fXnp +knVgMpusZhhk4S9rP4QTmBmwNJZMIOMYNoKja0K/VAjKTfYmSHSrhpdWCkD71tqF +vD3RfTG/QohuhUz34EzN9pIpZpBAAQ6LHfISVLp9R8wdDRlOm0ICK6eVWooxtdLP +x6dQA/C4MApbuRj1pKgfwCk1X0k6HkZJA8KOqDWdmthHuFS6l1//LCVzeQARAQAB +tChQaGlsaXAgWiAoZ3BnIGZvciB0ZWFxbCkgPGluZm9AdGVhcWwuaW8+iQJUBBMB +CgA+FiEE0ZXN0QKIVz1lAZPaa58fi+AL1ZUFAmpsF40CGwMFCQHhM4AFCwkIBwIG +FQoJCAsCBBYCAwECHgECF4AACgkQa58fi+AL1ZUBdw//Qd9RBSgaxtJcSV4SnYDh +0Q2g8rWjA9WqREQAaMJJkwSHw3WsuvDi1At/zUDOy1DOjN0BrS/1tj5UneOqC4AF +jg/tuHFxTcfUPUFpPp/0Nj/jA7QPbGC2Ih2wVO8guO4JqUGbNsU0d59scwHRxSlI +l4PndTKVANi6l/cgdWXuejfLr/uPvMUji0lsODFBI4YOSvAG0RH1Ut2HHNMiNejZ +acstCPSKut01YSTDYce74RMZlBu3N+I1jW5ivOFabjkpnP2gMrYSzDzF+TsZLZAr +QYWi4pYdepf0/4LoBCUO7PqU2secg5rZ7r74E6xnBIntpTc2EG4zO4LfV4xDkavH +0Ar/I+L1VySx2QN9DiMywFJBau7Ajbc62gQacEzUzpBzPu2IW76XICLP0b5ZOltm +oBZg7xW1kvY/fFbfYT7K0K9L03K/fhIYzRRyhryZUAzv474zr9E7Tb96lsgubul6 +8s43GmQOadgHG3ZElX8XE8vGJ/ARm2FsIL99Iyw1AsSH7e2ri4diLktuVGKv7xSc +Jzywf+iTlTABPMlHJ/VDJ4KbzS5qlI/uwpdNlmCYfizXZncWIXAGpTJwoJgb0KC5 +wasDtFBNgX0cI/70Q0uDkligIQCLnqpu+LBmOynzJfwos2fzDGcsssf4ZMyL44gV +wQ0oEO5pocdEBLtGLlc4wuO5Ag0EamwXjQEQAJeD4iIKzNhQ1eJZSYmHMOcXh4pR +1rxISk0Pnu3u0raUeCKCj5iIUQTTD7b49O9j1HIxwCbjnjSeiIjE+4n/K88v/bIk +oa4yT8e+pwxs260KivtikltePAR3aNr3yr/XJEO1qCOIBaz2tW3AZlTDEOUli3Rt +unIwBwf9BC7CC9IbSDapSnWEp54XrV/uP/I1xtBB6hKla5IJNyaJzgUljb9aRXdD +nPXh7eTBsErY3io+x/EQXhmgS2qtnfC7nqDXreLohC2WrllqvyWVto1apYzS/g42 +onm3yvdMadt6FhX1oBZcktLQjY/fat7OCsAHvmluCwRpOQDw+zfMpLuWw6fbWSHl +6i1hE/1iKfW0a4NHtNleH+ClFJPyW3U5a5cWOv8mTC8xXVT+bAxdcEOxpDVzFkgl ++zgRFPB++kJAjyHqAqcFZOlQSfY0wHRT+DJKoWDGziNc5ae0U7e5oF+1kYUqOe00 +EAZajSDQj5BpF+dCrA8F08i48fVbb7WqYHRivARhkh/+z6qcbqjzJP799BCOYetB +0wehG5q9EZCgi0FqSjq+Ze0C+aGB0wuehOqgXqGG3C3xOpgduUNPucdIR8et27Pa +ij0zmKciYbs3VsvlcDxkx/7No3xh5oIk9If2ThE+A2/nbIC3rLjjo7dVOqvvrRxR +x030Qy7h2/NmycPZABEBAAGJAjwEGAEKACYWIQTRlc3RAohXPWUBk9prnx+L4AvV +lQUCamwXjQIbDAUJAeEzgAAKCRBrnx+L4AvVldZfD/9EMaDjuUXDFzVrCa4/03Wz +1HStHRLL8U9q+tc7GQDFeQELE7HH45MqA1j2ayRBOdhCcNlq0hRA371T3khqwxZ7 +PsU0TFYxosfDfuZ0nneJtFjI9yeABPhaXc+vcJZRTSn0qtvsSQeA+xJxfeNYLjK9 +0RCxd6qipVQjNnZgmpAvZNbqGO1RSLH8kdQcU21iXSL6EEawZmvYqHWX4pXVYI07 +YRbLUMUlXFSoTQTi20LORgOfk/gHNQxgRed82RGhtv7Fx8wm2jXOFOrlGDYjJ6f3 +RwxDC3GPX+DR3HWYk8tGxYiCxvVa/aP+ezamBDs+wzVJ+GtzTkeP/jYTRSBUFfCS +R9e1XyRqt+SsvutxkeMA89QlV9TkBGG1P+66Ibjf3pb6BG+3EBH77OXlMMmn1Q/q +rT0woJQXF4q3ZndunaIPYoIVlqajdIL7qJ9HMvpXN6cuD8F9J27DJGuZwTUYA7ps +0f6n4ylfO8UK0aEYQ4aoWGcgHONxYU7mXLwkUCcMhAd44HWUQwKr44XPalZtwGka +5MCfgdv2DQAWisuLZO6kYXeaallxRhfwO6Qr+7v4qBGogb4iBNtRrM8R+UYv9RTa +dsuUUWeDko0TFNxYFsCmFRtX3nN/eSn6E2DW3GS2+05PISd9f5Aun6AOCjwQNneZ +QCad98Aov4EvyhTT7opivw== +=gHhI +-----END PGP PUBLIC KEY BLOCK----- diff --git a/source/teaql-ts/.github/workflows/example-gate.yml b/source/teaql-ts/.github/workflows/example-gate.yml index 7a73d0f86dfa36599e4e77d4c2d5ceacf0703653..69f5a4daa1da207124c40dfcdd9172f583ea74ed 100644 --- a/source/teaql-ts/.github/workflows/example-gate.yml +++ b/source/teaql-ts/.github/workflows/example-gate.yml @@ -20,8 +20,9 @@ jobs: with: node-version: '22' cache: npm - - run: npm install - - run: npm run build + # The canonical gate hashes the complete checked-in source before its + # isolated builds replace tracked dist chunks. Do not prebuild here. + - run: npm ci --no-audit --fund=false - name: Start dedicated S3 example fixture run: | docker run -d --name teaql-ts-example-s3 \ diff --git a/source/teaql-ts/.github/workflows/release.yml b/source/teaql-ts/.github/workflows/release.yml index 392144899ba916714a66532205d7da2e8dbfc672..45394952160afbd90dbae6e315cfa3ee91fa22bc 100644 --- a/source/teaql-ts/.github/workflows/release.yml +++ b/source/teaql-ts/.github/workflows/release.yml @@ -1,32 +1,67 @@ -name: Publish TypeScript package +name: Promote qualified typescript packages on: workflow_dispatch: - push: - tags: - - "typescript-v*" + inputs: + release_tag: + description: Existing signed tag whose exact packages passed internal qualification + required: true + type: string + qualification_sha256: + description: SHA-256 of logging-qualification.json retained with the release evidence + required: true + type: string + +concurrency: + group: typescript-public-promotion + cancel-in-progress: false jobs: + verify: + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ inputs.release_tag }} + fetch-depth: 0 + - name: Verify signed source and qualified package bytes + env: + GH_TOKEN: ${{ github.token }} + RELEASE_TAG: ${{ inputs.release_tag }} + QUALIFICATION_SHA256: ${{ inputs.qualification_sha256 }} + shell: bash + run: | + export GNUPGHOME="$RUNNER_TEMP/teaql-release-signatures" + mkdir -m 700 "$GNUPGHOME" + gpg --batch --import .github/release-signing-key.asc + python3 scripts/verify-qualified-release.py \ + --tag "$RELEASE_TAG" --manifest-sha256 "$QUALIFICATION_SHA256" \ + --language typescript --repository "$GITHUB_REPOSITORY" + - uses: actions/upload-artifact@v4 + with: + name: qualified-typescript-packages + path: qualified-packages/ + if-no-files-found: error + publish: + needs: verify runs-on: ubuntu-latest environment: npm permissions: contents: read id-token: write steps: - - uses: actions/checkout@v4 + - uses: actions/download-artifact@v4 + with: + name: qualified-typescript-packages + path: qualified-packages/ - uses: actions/setup-node@v4 with: node-version: "24" registry-url: https://registry.npmjs.org - cache: npm - - run: npm ci - - name: Verify tag matches package version - run: test "${GITHUB_REF_NAME#typescript-v}" = "$(node -p 'require("./package.json").version')" - # Keep native SQLite lifecycle coverage deterministic and verify the - # current Node LTS used by generated TeaQL projects. - - run: npm test -- --runInBand - - run: npm run build - name: Upgrade npm for trusted publishing run: npm install --global npm@latest - - run: npm publish --access public + - name: Publish the verified tarball + run: npm publish ./qualified-packages/*.tgz --access public --provenance diff --git a/source/teaql-ts/README.md b/source/teaql-ts/README.md index 91eb927cc29bb23fc8be71cbaf6440977a7273f3..c44d22cc999e88589fe0e35cebabc8ffdff57240 100644 --- a/source/teaql-ts/README.md +++ b/source/teaql-ts/README.md @@ -282,6 +282,14 @@ final execution report. It is a workflow, not a guarantee of unattended correctn Node.js/npm for the repository examples. Browser SQLite runs in a Web Worker with SQLite/WASM. From a checkout of this repository: +The Node SQLite adapter and its examples require **Node 22+** and +**better-sqlite3 13.0.3+ (13.x)**. Version 13 uses N-API; the older 12.x binding can +abort during allocation-driven garbage collection on Node 24.19.0 even when a +manual `global.gc()` check passes. The repository regression executes 300,000 +prepared queries in a separate real Node process twice. This native-provider +requirement does not apply to browser SQLite/WASM or Expo SQLite, and does not +raise the runtime core's Node requirement for unrelated providers. + ```bash cd examples/school-management npm install diff --git a/source/teaql-ts/examples/browser-sqlite/README.md b/source/teaql-ts/examples/browser-sqlite/README.md index 9bf74dab060f7a91feb45b6d48f9339eed85c4cf..fcc5795e75ae6b045ed6cccc700f42cf1f2e690c 100644 --- a/source/teaql-ts/examples/browser-sqlite/README.md +++ b/source/teaql-ts/examples/browser-sqlite/README.md @@ -12,6 +12,15 @@ Java, Rust, Go, Python, .NET and Swift runtimes. The seven-language strip links to each runtime source and marks TypeScript as the current browser runtime; it does not imply that selecting another link swaps the page's execution engine. +The page includes a development-process section linking directly to +`order-model.xml` and the model-aware Assist directory. It explains the real +model-to-runtime path: define the domain once, generate typed Q/E APIs and +scoped Assist, write one bounded Q request with comment and purpose, then let +the runtime retain TraceChain, timing and actual SQL evidence. Progressive +entity/action/field Assist keeps agents from loading the runtime internals and +the entire generated library into every context window; no unmeasured context +savings are claimed. + `OrderStatus` is a seventh, constant model object rather than a string field. Its five fixed values are reconciled through `RuntimeModule` bootstrap, orders store the status object ID, and generated Q expressions select, filter, and diff --git a/source/teaql-ts/examples/browser-sqlite/generated-order-hashes.json b/source/teaql-ts/examples/browser-sqlite/generated-order-hashes.json index bc6cc715fa94722884cac06592cba651dd46d2ad..b3280595d7f92918f11f25bbda362a9cb9a7044f 100644 --- a/source/teaql-ts/examples/browser-sqlite/generated-order-hashes.json +++ b/source/teaql-ts/examples/browser-sqlite/generated-order-hashes.json @@ -1,19 +1,19 @@ { - "src/generated-bootstrap.ts": "5f3065c1e4794c0d21ada7c2eef48f4694cec1cbc4771fa48bc7d6ff9221540b", + "src/generated-bootstrap.ts": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c", "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", - "src/generated/E.ts": "940a5dfa19912a7973ac44879488b37132d981cd3325f7f28aefdef0480c7542", + "src/generated/E.ts": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", - "src/generated/models/Customer.ts": "5ff4b46a58b2dad54858b7ed444f3b78c49941b8e01b150008d6f48ae11cc067", - "src/generated/models/CustomerOrder.ts": "94168486fb9dffd2f99296bf93eb0bfcfa83744d4516e706f8b144cec8317f1a", - "src/generated/models/OrderItem.ts": "e2884b4013b7478d8e3083b1a18ed9b3321c19b49004249b5486a31385c6797e", - "src/generated/models/OrderStatus.ts": "2bb7bfe245ab3dd75ca4359037769a3f760c90fed5ac214032f008c90fb39c14", - "src/generated/models/Platform.ts": "55d9146a4b42929e4f206beb9288921dfaee5c08ac9616100898d4c6e7817c5a", - "src/generated/requests/CustomerOrderRequest.ts": "167326d997fa314411fdad1349ea34aef3c1232c2c469253714318905f041744", - "src/generated/requests/CustomerRequest.ts": "7c1dfc760a67d523579ef0758731d7c6772930d8360e5594a37926aa5df3e5f3", - "src/generated/requests/OrderItemRequest.ts": "ee3fe2e2d3dc6eae0c1ff1697cb7f73626595682dd2b5a87218b855287468c0a", - "src/generated/requests/OrderStatusRequest.ts": "fbb8ed0507ec80f4b9a5d0d260f7e08ecc524d56cc4b78166326750629cfec24", - "src/generated/requests/PlatformRequest.ts": "dcf958694498114f744ea59570dc92e4fd2e93b84ddb2c831af99be04b08c2b7", - "src/runtime-module.ts": "f92fe9a9474678d26a233eb734b14493b4ddc216ed3b648bfad723b4b6a46eeb", - "src/teaql-schemas.ts": "68cb7cacc725ff041d2289f17d7817ae56f37d035c92f2feb6c1318face6f806", - "src/teaql-ts.ts": "cc705f9f7873450eae541311317db3402dc40b7cf068c440169bd7ba06dcb1ed" + "src/generated/models/Customer.ts": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a", + "src/generated/models/CustomerOrder.ts": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c", + "src/generated/models/OrderItem.ts": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64", + "src/generated/models/OrderStatus.ts": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e", + "src/generated/models/Platform.ts": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415", + "src/generated/requests/CustomerOrderRequest.ts": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244", + "src/generated/requests/CustomerRequest.ts": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf", + "src/generated/requests/OrderItemRequest.ts": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b", + "src/generated/requests/OrderStatusRequest.ts": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77", + "src/generated/requests/PlatformRequest.ts": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22", + "src/runtime-module.ts": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "src/teaql-schemas.ts": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814" } diff --git a/source/teaql-ts/examples/browser-sqlite/index.html b/source/teaql-ts/examples/browser-sqlite/index.html index 60b09f38daaac44a85e0cb214098e793737856b8..488ed6927baf28f9f71fc3bfe203e166f5ad2e03 100644 --- a/source/teaql-ts/examples/browser-sqlite/index.html +++ b/source/teaql-ts/examples/browser-sqlite/index.html @@ -93,6 +93,63 @@
+
+
+
+

00 / DEVELOPMENT PROCESS

+

From one domain model to executable evidence.

+
+
+

TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.

+ +
+
+ +
    +
  1. + 01 + Model the domain +

    Define entities, fields, relationships, constant objects, and constraints in one model file.

    + order-model.xml +
  2. +
  3. + 02 + Generate the working surface +

    Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.

    + Q · E · Schema · Assist +
  4. +
  5. + 03 + Build one bounded Q request +

    Application code selects only what the page needs and attaches a readable comment and purpose.

    + comment · purpose · execute +
  6. +
  7. + 04 + Run and retain evidence +

    The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.

    + Result · TraceChain · SQL +
  8. +
+ +
+
+

CONTEXT EFFICIENCY

+

Spend context on the business change.

+
+

Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.

+
+
+

Starting SQLite/WASM…

diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/current-generator-fixture.json b/source/teaql-ts/examples/browser-sqlite/orders-lib/current-generator-fixture.json new file mode 100644 index 0000000000000000000000000000000000000000..773f61fc081921a01f6e75d08848ee659c6dcbdb --- /dev/null +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/current-generator-fixture.json @@ -0,0 +1,36 @@ +{ + "schema": "teaql.typescript-current-example-fixture/v1", + "modelSha256": "44d20c0d236de9c79f767054deba773e11aa6ae4eaed1ede98cf7c6ed8d18495", + "scope": "typescript-lib-core", + "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "files": { + "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "src/generated/requests/PlatformRequest.ts": "77760c1213a1012c98601dfced364ecf5fa5636e8f04a0186150fe7744cbcc22", + "src/generated/requests/OrderStatusRequest.ts": "fa9c36b305a410b16cd87f84a3932efb425f53fe6537f447d15824f39d186b77", + "src/generated/requests/CustomerRequest.ts": "5b8bd3ec2b080a3134e2f53a8ac8392b1307dec49f6acea42b4377931697f4bf", + "src/generated/requests/CustomerOrderRequest.ts": "5090c29d8a539b08f3abbf2bcff98f5aa354240c990df4f89c28d06e96285244", + "src/generated/requests/OrderItemRequest.ts": "4a40a7eb45166b69110af8413c0ad5353acff1cc7b927444fba117a72598db9b", + "src/generated/E.ts": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "src/teaql-schemas.ts": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "src/runtime-module.ts": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "src/generated-bootstrap.ts": "2c1ebd40196256d590417568ff08bc883e2d65c9663ef649f3665a502c77b76c", + "src/generated/models/Platform.ts": "f8107a5bac9a98bb867f89c1c80969b9c3e978b5b28291722c0be8c558a11415", + "src/generated/models/OrderStatus.ts": "a9e0b751597f2e8ba881184d397679a9fc3968ef34efbab5158796e7e335a04e", + "src/generated/models/Customer.ts": "0169ad722f34c8a9e5a30eab390ed4bd83a84c46fe4410d7178cf136edb0e28a", + "src/generated/models/CustomerOrder.ts": "0510b3ce7c628bae67699d37e35e758882b6c4fa718c4f4a527dba80b055758c", + "src/generated/models/OrderItem.ts": "4363421c144d79ca76fd11fbe11115186f3193e19b8bffd1671b92817e4e8f64" + }, + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousFixtureManifestSha256": "8faee6961c8802d2952be9d228012ac260843234301260b798917428ad09dfb7", + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } +} diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts index b0458cb91bdca98d6fbab0a1eb1c0c53fb73d305..f9583ebef1a926327a1dac4721fdf0a8df250542 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts @@ -1,4 +1,4 @@ -import { UserContext } from './teaql-ts'; +import { UserContext, decimal, long, localTime } from './teaql-ts'; import { Q } from './generated/Q'; import { Platform } from './generated/models/Platform'; import { OrderStatus } from './generated/models/OrderStatus'; @@ -7,14 +7,14 @@ import { OrderStatus } from './generated/models/OrderStatus'; export async function ensureGeneratedBootstrap(context: UserContext): Promise { let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; if (!domainRoot) { - domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot = Platform.teaqlBootstrapNew(context, '1'); domainRoot.updateName("Commerce Test Platform"); await domainRoot.auditAs('create generated Domain Root Platform').save(context); } context.withActiveRoot({ entity: 'Platform', id: domainRoot.id! }); let constantOrderStatus1001 = (await Q.orderStatuses().withIdIs("1001").comment('what: locate generated constant OrderStatus(1001)').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; if (!constantOrderStatus1001) { - constantOrderStatus1001 = OrderStatus.teaqlBootstrapNew("1001"); + constantOrderStatus1001 = OrderStatus.teaqlBootstrapNew(context, "1001"); constantOrderStatus1001.updatePlatform(domainRoot); constantOrderStatus1001.updateName("New"); constantOrderStatus1001.updateCode("NEW"); @@ -32,7 +32,7 @@ export async function ensureGeneratedBootstrap(context: UserContext): Promise; - - constructor( - readonly root: string, - readonly accessPath: string, - readonly breakPoint: string, - ) { - const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; - const details = { - error: 'TeaQLNotLoadedError', - root, - accessPath: accessPath.split('.'), - breakPoint, - missingPreload: [breakPoint], - suggestedFix, - severity: 'error', - humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, - }; - super(JSON.stringify(details)); - this.name = 'TeaQLNotLoadedError'; - this.details = details; - } -} - -function expressionPath(prefix: string, field: string): string { - return prefix ? `${prefix}.${field}` : field; -} +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; export class ValueExpression { constructor( private readonly value: T | null | undefined, private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, ) {} static missing(): ValueExpression { @@ -48,18 +23,26 @@ export class ValueExpression { return new ValueExpression(undefined, false, error); } + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + eval(): T | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; return this.present ? this.value : undefined; } isPresent(): boolean { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; return this.present; } orElse(fallback: T): T { - const value = this.eval(); + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; return this.present && value != null ? value : fallback; } } @@ -68,62 +51,62 @@ export class PlatformExpression { constructor( private readonly value: Platform | null | undefined, private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Platform | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } orderStatusList(): OrderStatusListExpression { - const path = expressionPath(this.path, 'orderStatusList'); + const path = this.path.member('order_status_list', 'orderStatusList'); if (this.notLoaded) { - return new OrderStatusListExpression([], this.root, path, false, this.notLoaded); + return new OrderStatusListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return OrderStatusListExpression.missing(this.root, path); if (!this.value.isLoaded('orderStatusList')) { return new OrderStatusListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'orderStatusList')); + new TeaQLNotLoadedError(path.markMissing(), 'order_status_list')); } return new OrderStatusListExpression( this.value.orderStatusList(), this.root, path, @@ -131,14 +114,14 @@ export class PlatformExpression { } customerList(): CustomerListExpression { - const path = expressionPath(this.path, 'customerList'); + const path = this.path.member('customer_list', 'customerList'); if (this.notLoaded) { - return new CustomerListExpression([], this.root, path, false, this.notLoaded); + return new CustomerListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return CustomerListExpression.missing(this.root, path); if (!this.value.isLoaded('customerList')) { return new CustomerListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'customerList')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_list')); } return new CustomerListExpression( this.value.customerList(), this.root, path, @@ -150,94 +133,96 @@ export class OrderStatusExpression { constructor( private readonly value: OrderStatus | null | undefined, private readonly root = 'OrderStatus(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.orderStatus()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): OrderStatus | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } code(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('code', 'code'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'code'); if (!this.value.isLoaded('code')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'code'), + new TeaQLNotLoadedError(path.markMissing(), 'code'), ); } return new ValueExpression(this.value.code); } color(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('color', 'color'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'color'); if (!this.value.isLoaded('color')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'color'), + new TeaQLNotLoadedError(path.markMissing(), 'color'), ); } return new ValueExpression(this.value.color); } displayOrder(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('display_order', 'displayOrder'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'displayOrder'); if (!this.value.isLoaded('displayOrder')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + new TeaQLNotLoadedError(path.markMissing(), 'display_order'), ); } + const error = integer32Error(this.value.displayOrder, 'OrderStatus', 'display_order'); + if (error) return ValueExpression.invalid(error); return new ValueExpression(this.value.displayOrder); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -248,33 +233,35 @@ export class OrderStatusExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } customerOrderList(): CustomerOrderListExpression { - const path = expressionPath(this.path, 'customerOrderList'); + const path = this.path.member('customer_order_list', 'customerOrderList'); if (this.notLoaded) { - return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded); + return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return CustomerOrderListExpression.missing(this.root, path); if (!this.value.isLoaded('customerOrderList')) { return new CustomerOrderListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'customerOrderList')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list')); } return new CustomerOrderListExpression( this.value.customerOrderList(), this.root, path, @@ -286,58 +273,58 @@ export class CustomerExpression { constructor( private readonly value: Customer | null | undefined, private readonly root = 'Customer(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.customer()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Customer | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -348,33 +335,35 @@ export class CustomerExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } customerOrderList(): CustomerOrderListExpression { - const path = expressionPath(this.path, 'customerOrderList'); + const path = this.path.member('customer_order_list', 'customerOrderList'); if (this.notLoaded) { - return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded); + return new CustomerOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return CustomerOrderListExpression.missing(this.root, path); if (!this.value.isLoaded('customerOrderList')) { return new CustomerOrderListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'customerOrderList')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order_list')); } return new CustomerOrderListExpression( this.value.customerOrderList(), this.root, path, @@ -386,82 +375,82 @@ export class CustomerOrderExpression { constructor( private readonly value: CustomerOrder | null | undefined, private readonly root = 'CustomerOrder(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.customerOrder()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): CustomerOrder | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } orderNumber(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('order_number', 'orderNumber'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'orderNumber'); if (!this.value.isLoaded('orderNumber')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'orderNumber'), + new TeaQLNotLoadedError(path.markMissing(), 'order_number'), ); } return new ValueExpression(this.value.orderNumber); } orderDate(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('order_date', 'orderDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'orderDate'); if (!this.value.isLoaded('orderDate')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'orderDate'), + new TeaQLNotLoadedError(path.markMissing(), 'order_date'), ); } return new ValueExpression(this.value.orderDate); } - totalAmount(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'totalAmount'); + totalAmount(): ValueExpression { + const path = this.path.member('total_amount', 'totalAmount'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('totalAmount')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'totalAmount'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'total_amount'), ); } - return new ValueExpression(this.value.totalAmount); + return new ValueExpression(this.value.totalAmount); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } customerId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('customer', 'customerId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'customer'); if (!this.value.isLoaded('customer')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'customer'), + new TeaQLNotLoadedError(path.markMissing(), 'customer'), ); } const reference = this.value.customer; @@ -472,12 +461,12 @@ export class CustomerOrderExpression { } statusId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('status', 'statusId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'status'); if (!this.value.isLoaded('status')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'status'), + new TeaQLNotLoadedError(path.markMissing(), 'status'), ); } const reference = this.value.status; @@ -488,52 +477,56 @@ export class CustomerOrderExpression { } customer(): CustomerExpression { - const path = expressionPath(this.path, 'customer'); + const path = this.path.member('customer', 'customer'); if (this.notLoaded) { - return new CustomerExpression(undefined, this.root, path, this.notLoaded); + return new CustomerExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new CustomerExpression(undefined, this.root, path); if (!this.value.isLoaded('customer')) { return new CustomerExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'customer')); + new TeaQLNotLoadedError(path.markMissing(), 'customer')); } const relation = this.value.customer; - const target = relation == null - ? undefined - : relation instanceof Customer - ? relation - : Customer.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Customer)) { + return new CustomerExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer')); + } + const target = relation instanceof Customer ? relation : undefined; return new CustomerExpression(target, this.root, path); } status(): OrderStatusExpression { - const path = expressionPath(this.path, 'status'); + const path = this.path.member('status', 'status'); if (this.notLoaded) { - return new OrderStatusExpression(undefined, this.root, path, this.notLoaded); + return new OrderStatusExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new OrderStatusExpression(undefined, this.root, path); if (!this.value.isLoaded('status')) { return new OrderStatusExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'status')); + new TeaQLNotLoadedError(path.markMissing(), 'status')); } const relation = this.value.status; - const target = relation == null - ? undefined - : relation instanceof OrderStatus - ? relation - : OrderStatus.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof OrderStatus)) { + return new OrderStatusExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'status')); + } + const target = relation instanceof OrderStatus ? relation : undefined; return new OrderStatusExpression(target, this.root, path); } orderItemList(): OrderItemListExpression { - const path = expressionPath(this.path, 'orderItemList'); + const path = this.path.member('order_item_list', 'orderItemList'); if (this.notLoaded) { - return new OrderItemListExpression([], this.root, path, false, this.notLoaded); + return new OrderItemListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return OrderItemListExpression.missing(this.root, path); if (!this.value.isLoaded('orderItemList')) { return new OrderItemListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'orderItemList')); + new TeaQLNotLoadedError(path.markMissing(), 'order_item_list')); } return new OrderItemListExpression( this.value.orderItemList(), this.root, path, @@ -545,82 +538,84 @@ export class OrderItemExpression { constructor( private readonly value: OrderItem | null | undefined, private readonly root = 'OrderItem(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.orderItem()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): OrderItem | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } productName(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('product_name', 'productName'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'productName'); if (!this.value.isLoaded('productName')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'productName'), + new TeaQLNotLoadedError(path.markMissing(), 'product_name'), ); } return new ValueExpression(this.value.productName); } quantity(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('quantity', 'quantity'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'quantity'); if (!this.value.isLoaded('quantity')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'quantity'), + new TeaQLNotLoadedError(path.markMissing(), 'quantity'), ); } + const error = integer32Error(this.value.quantity, 'OrderItem', 'quantity'); + if (error) return ValueExpression.invalid(error); return new ValueExpression(this.value.quantity); } - unitPrice(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'unitPrice'); + unitPrice(): ValueExpression { + const path = this.path.member('unit_price', 'unitPrice'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('unitPrice')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'unitPrice'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'unit_price'), ); } - return new ValueExpression(this.value.unitPrice); + return new ValueExpression(this.value.unitPrice); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } customerOrderId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('customer_order', 'customerOrderId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'customerOrder'); if (!this.value.isLoaded('customerOrder')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'customerOrder'), + new TeaQLNotLoadedError(path.markMissing(), 'customer_order'), ); } const reference = this.value.customerOrder; @@ -631,21 +626,23 @@ export class OrderItemExpression { } customerOrder(): CustomerOrderExpression { - const path = expressionPath(this.path, 'customerOrder'); + const path = this.path.member('customer_order', 'customerOrder'); if (this.notLoaded) { - return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded); + return new CustomerOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new CustomerOrderExpression(undefined, this.root, path); if (!this.value.isLoaded('customerOrder')) { return new CustomerOrderExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'customerOrder')); + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); } const relation = this.value.customerOrder; - const target = relation == null - ? undefined - : relation instanceof CustomerOrder - ? relation - : CustomerOrder.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof CustomerOrder)) { + return new CustomerOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'customer_order')); + } + const target = relation instanceof CustomerOrder ? relation : undefined; return new CustomerOrderExpression(target, this.root, path); } @@ -655,30 +652,34 @@ export class PlatformListExpression { constructor( private readonly items: readonly Platform[], private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PlatformListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { return new PlatformListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PlatformExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PlatformExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PlatformExpression(undefined, this.root, itemPath) @@ -690,30 +691,34 @@ export class OrderStatusListExpression { constructor( private readonly items: readonly OrderStatus[], private readonly root = 'OrderStatus(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): OrderStatusListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderStatusListExpression { return new OrderStatusListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): OrderStatusExpression { - return this.get(0); + return this.item(0, true); } get(index: number): OrderStatusExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderStatusExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new OrderStatusExpression(undefined, this.root, itemPath, this.notLoaded); + return new OrderStatusExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new OrderStatusExpression(undefined, this.root, itemPath) @@ -725,30 +730,34 @@ export class CustomerListExpression { constructor( private readonly items: readonly Customer[], private readonly root = 'Customer(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): CustomerListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CustomerListExpression { return new CustomerListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): CustomerExpression { - return this.get(0); + return this.item(0, true); } get(index: number): CustomerExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): CustomerExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new CustomerExpression(undefined, this.root, itemPath, this.notLoaded); + return new CustomerExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new CustomerExpression(undefined, this.root, itemPath) @@ -760,30 +769,34 @@ export class CustomerOrderListExpression { constructor( private readonly items: readonly CustomerOrder[], private readonly root = 'CustomerOrder(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): CustomerOrderListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CustomerOrderListExpression { return new CustomerOrderListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): CustomerOrderExpression { - return this.get(0); + return this.item(0, true); } get(index: number): CustomerOrderExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): CustomerOrderExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded); + return new CustomerOrderExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new CustomerOrderExpression(undefined, this.root, itemPath) @@ -795,30 +808,34 @@ export class OrderItemListExpression { constructor( private readonly items: readonly OrderItem[], private readonly root = 'OrderItem(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): OrderItemListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderItemListExpression { return new OrderItemListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): OrderItemExpression { - return this.get(0); + return this.item(0, true); } get(index: number): OrderItemExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderItemExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded); + return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new OrderItemExpression(undefined, this.root, itemPath) @@ -831,7 +848,7 @@ export class E { value: Platform | null | undefined, ): PlatformExpression { return new PlatformExpression( - value, `Platform(id=${value?.id ?? 'null'})`, + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), ); } @@ -839,7 +856,7 @@ export class E { value: OrderStatus | null | undefined, ): OrderStatusExpression { return new OrderStatusExpression( - value, `OrderStatus(id=${value?.id ?? 'null'})`, + value, 'OrderStatus', ExpressionPath.root('E.orderStatus()', 'camelCase'), ); } @@ -847,7 +864,7 @@ export class E { value: Customer | null | undefined, ): CustomerExpression { return new CustomerExpression( - value, `Customer(id=${value?.id ?? 'null'})`, + value, 'Customer', ExpressionPath.root('E.customer()', 'camelCase'), ); } @@ -855,7 +872,7 @@ export class E { value: CustomerOrder | null | undefined, ): CustomerOrderExpression { return new CustomerOrderExpression( - value, `CustomerOrder(id=${value?.id ?? 'null'})`, + value, 'CustomerOrder', ExpressionPath.root('E.customerOrder()', 'camelCase'), ); } @@ -863,7 +880,7 @@ export class E { value: OrderItem | null | undefined, ): OrderItemExpression { return new OrderItemExpression( - value, `OrderItem(id=${value?.id ?? 'null'})`, + value, 'OrderItem', ExpressionPath.root('E.orderItem()', 'camelCase'), ); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts index 41f197c51bf0120adcbd6f3377f3a984c5327c10..302aeb1a76d5beb4b35034961ee728389373f47c 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts @@ -1,24 +1,30 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { CustomerOrder } from './CustomerOrder'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Customer { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Customer", + ["id", "platform", "name", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; platform?: Platform | string; name?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Customer.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_customerOrderList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["customerOrderList"]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { @@ -39,24 +45,32 @@ export class Customer { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Customer", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root); + for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Customer { - const entity = new Customer(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Customer(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList; + return result; } isLoaded(field: string): boolean { @@ -75,12 +89,19 @@ export class Customer { } static refer(id: string | number): Customer { - return new Customer({ id: String(id) } as Partial); + return Customer.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Customer { - return new Customer().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Customer { + return EntityCreation.bootstrap(context, "Customer", id, + reserved => new Customer({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Customer", + reserved => new Customer({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -90,23 +111,127 @@ export class Customer { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Customer.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Customer.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "customer_order_list": graph.sourceMembers((this as any)._customerOrderList) + })); + for (const child of (this as any)._customerOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customer; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Customer.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Customer", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Customer.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] @@ -114,6 +239,7 @@ export class Customer { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Customer", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -124,7 +250,8 @@ export class Customer { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -133,22 +260,25 @@ export class Customer { for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customer; - if (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomer(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -156,7 +286,7 @@ export class Customer { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -168,28 +298,27 @@ export class Customer { for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customer; - if (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomer(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -198,12 +327,16 @@ export class Customer { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -214,24 +347,29 @@ export class Customer { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customer; - if (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomer(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customer") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomer(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -245,6 +383,10 @@ export class Customer { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -259,7 +401,7 @@ export class Customer { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts index 65bd4518b1c3caf3961f44efac213d470c1c9c5f..9d4d58fc071d66703aca309c96809e39f77da8cf 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts @@ -1,28 +1,34 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Customer } from './Customer'; import { OrderStatus } from './OrderStatus'; import { OrderItem } from './OrderItem'; +const teaqlConstruction = Symbol("managed entity construction"); + export class CustomerOrder { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("CustomerOrder", + ["id", "customer", "status", "order_number", "order_date", "total_amount", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; customer?: Customer | string; status?: OrderStatus | string; orderNumber?: string; orderDate?: string; - totalAmount?: number; - version?: number; + totalAmount?: Decimal; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --CustomerOrder.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_orderItemList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderItemList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["orderItemList"]; Object.assign(this, fields); if ((init as any).customer && typeof (init as any).customer === "object") { @@ -49,24 +55,32 @@ export class CustomerOrder { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "CustomerOrder", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root); + for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): CustomerOrder { - const entity = new CustomerOrder(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new CustomerOrder(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("orderItemList")) result["orderItemList"] = (this as any)._orderItemList; + return result; } isLoaded(field: string): boolean { @@ -85,12 +99,19 @@ export class CustomerOrder { } static refer(id: string | number): CustomerOrder { - return new CustomerOrder({ id: String(id) } as Partial); + return CustomerOrder.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): CustomerOrder { - return new CustomerOrder().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): CustomerOrder { + return EntityCreation.bootstrap(context, "CustomerOrder", id, + reserved => new CustomerOrder({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "CustomerOrder", + reserved => new CustomerOrder({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -100,23 +121,128 @@ export class CustomerOrder { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._orderItemList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._orderItemList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "customer": "Customer", + "status": "OrderStatus" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "order_item_list": graph.sourceMembers((this as any)._orderItemList) + })); + for (const child of (this as any)._orderItemList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.customerOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + CustomerOrder.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customer", canonical: "customer" }, { member: "status", canonical: "status" }, { member: "orderNumber", canonical: "order_number" }, { member: "orderDate", canonical: "order_date" }, { member: "totalAmount", canonical: "total_amount" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "CustomerOrder", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(CustomerOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "customer", canonical: "customer" }, { member: "status", canonical: "status" }, { member: "orderNumber", canonical: "order_number" }, { member: "orderDate", canonical: "order_date" }, { member: "totalAmount", canonical: "total_amount" }, { member: "version", canonical: "version" }] @@ -124,6 +250,7 @@ export class CustomerOrder { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "CustomerOrder", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -134,7 +261,8 @@ export class CustomerOrder { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -143,22 +271,25 @@ export class CustomerOrder { for (const [index, child] of (this as any)._orderItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -166,7 +297,7 @@ export class CustomerOrder { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -178,28 +309,27 @@ export class CustomerOrder { for (const [index, child] of (this as any)._orderItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -208,12 +338,16 @@ export class CustomerOrder { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -224,24 +358,29 @@ export class CustomerOrder { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._orderItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.customerOrder; - if (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateCustomerOrder(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("customerOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCustomerOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -258,6 +397,10 @@ export class CustomerOrder { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -279,14 +422,15 @@ export class CustomerOrder { return this; } - updateTotalAmount(value: number): this { + updateTotalAmount(value: Decimal): this { + if (value != null) value = decimal(value); this.totalAmount = value; this.markLoaded("totalAmount"); (this as any)._root.set(this.teaqlEntityKey(), "total_amount", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts index 901988e62f05d076f079539423513df14036e512..d96f7239360a0f22d7307b8bf990e6c9323ed669 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts @@ -1,24 +1,34 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { CustomerOrder } from './CustomerOrder'; +const teaqlConstruction = Symbol("managed entity construction"); + export class OrderItem { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderItem", + ["id", "customer_order", "product_name", "quantity", "unit_price", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; customerOrder?: CustomerOrder | string; productName?: string; quantity?: number; - unitPrice?: number; - version?: number; + unitPrice?: Decimal; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.quantity, "OrderItem", "quantity"); if (error) throw error; } + - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderItem.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).customerOrder && typeof (init as any).customerOrder === "object") { this.customerOrder = (init as any).customerOrder instanceof CustomerOrder @@ -28,13 +38,15 @@ export class OrderItem { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "OrderItem", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -43,8 +55,17 @@ export class OrderItem { } static fromRecord(record: Record, root?: EntityRoot): OrderItem { - const entity = new OrderItem(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new OrderItem(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.quantity, "OrderItem", "quantity"); if (error) throw error; } + + + + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -63,12 +84,19 @@ export class OrderItem { } static refer(id: string | number): OrderItem { - return new OrderItem({ id: String(id) } as Partial); + return OrderItem.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): OrderItem { - return new OrderItem().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderItem { + return EntityCreation.bootstrap(context, "OrderItem", id, + reserved => new OrderItem({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderItem", + reserved => new OrderItem({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -78,23 +106,100 @@ export class OrderItem { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "customer_order": "CustomerOrder" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderItem.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "productName", canonical: "product_name" }, { member: "quantity", canonical: "quantity" }, { member: "unitPrice", canonical: "unit_price" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderItem", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "customerOrder", canonical: "customer_order" }, { member: "productName", canonical: "product_name" }, { member: "quantity", canonical: "quantity" }, { member: "unitPrice", canonical: "unit_price" }, { member: "version", canonical: "version" }] @@ -102,6 +207,7 @@ export class OrderItem { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "OrderItem", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -112,7 +218,8 @@ export class OrderItem { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -121,8 +228,10 @@ export class OrderItem { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -130,7 +239,7 @@ export class OrderItem { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -142,14 +251,12 @@ export class OrderItem { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -158,12 +265,16 @@ export class OrderItem { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -174,10 +285,14 @@ export class OrderItem { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -193,6 +308,10 @@ export class OrderItem { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -214,14 +333,15 @@ export class OrderItem { return this; } - updateUnitPrice(value: number): this { + updateUnitPrice(value: Decimal): this { + if (value != null) value = decimal(value); this.unitPrice = value; this.markLoaded("unitPrice"); (this as any)._root.set(this.teaqlEntityKey(), "unit_price", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts index e590f39c38b8ff37ff59724b3f99592813b7dd48..960425cc3b41c2b4f73e324e2cd23b79f2297f05 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts @@ -1,27 +1,36 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { CustomerOrder } from './CustomerOrder'; +const teaqlConstruction = Symbol("managed entity construction"); + export class OrderStatus { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderStatus", + ["platform", "id", "name", "code", "color", "display_order", "version"], { id: "immutable_field", version: "immutable_field" }); platform?: Platform | string; id?: string; name?: string; code?: string; color?: string; displayOrder?: number; - version?: number; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.displayOrder, "OrderStatus", "display_order"); if (error) throw error; } + - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderStatus.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_customerOrderList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_customerOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["customerOrderList"]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { @@ -42,24 +51,35 @@ export class OrderStatus { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "OrderStatus", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root); + for (const child of (this as any)._customerOrderList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): OrderStatus { - const entity = new OrderStatus(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new OrderStatus(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.displayOrder, "OrderStatus", "display_order"); if (error) throw error; } + + + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("customerOrderList")) result["customerOrderList"] = (this as any)._customerOrderList; + return result; } isLoaded(field: string): boolean { @@ -78,12 +98,19 @@ export class OrderStatus { } static refer(id: string | number): OrderStatus { - return new OrderStatus({ id: String(id) } as Partial); + return OrderStatus.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): OrderStatus { - return new OrderStatus().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderStatus { + return EntityCreation.bootstrap(context, "OrderStatus", id, + reserved => new OrderStatus({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderStatus", + reserved => new OrderStatus({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -93,23 +120,127 @@ export class OrderStatus { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._customerOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._customerOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "customer_order_list": graph.sourceMembers((this as any)._customerOrderList) + })); + for (const child of (this as any)._customerOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.status; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderStatus.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderStatus", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._customerOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(OrderStatus.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "color", canonical: "color" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] @@ -117,6 +248,7 @@ export class OrderStatus { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "OrderStatus", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -127,7 +259,8 @@ export class OrderStatus { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -136,22 +269,25 @@ export class OrderStatus { for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.status; - if (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateStatus(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -159,7 +295,7 @@ export class OrderStatus { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -171,28 +307,27 @@ export class OrderStatus { for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.status; - if (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateStatus(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -201,12 +336,16 @@ export class OrderStatus { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -217,24 +356,29 @@ export class OrderStatus { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._customerOrderList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.status; - if (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateStatus(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("status") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateStatus(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_order_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -251,6 +395,10 @@ export class OrderStatus { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -286,7 +434,7 @@ export class OrderStatus { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts index ca2f0c835dfe23f9073d70150d528933d134a01f..37d638ed58c93ee0e6ad4c6fc69d273f476f89a3 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts @@ -1,24 +1,30 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { OrderStatus } from './OrderStatus'; import { Customer } from './Customer'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_orderStatusList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); - Object.defineProperty(this, "_customerList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderStatusList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_customerList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["orderStatusList"]; delete fields["customerList"]; Object.assign(this, fields); @@ -44,25 +50,34 @@ export class Platform { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._orderStatusList) child.teaqlAttachRoot(root); - for (const child of (this as any)._customerList) child.teaqlAttachRoot(root); + for (const child of (this as any)._orderStatusList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._customerList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Platform { - const entity = new Platform(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("orderStatusList")) result["orderStatusList"] = (this as any)._orderStatusList; + if (this.isLoaded("customerList")) result["customerList"] = (this as any)._customerList; + return result; } isLoaded(field: string): boolean { @@ -81,12 +96,19 @@ export class Platform { } static refer(id: string | number): Platform { - return new Platform({ id: String(id) } as Partial); + return Platform.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Platform { - return new Platform().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -96,23 +118,153 @@ export class Platform { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._orderStatusList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._customerList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._orderStatusList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._customerList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._orderStatusList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._customerList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "order_status_list": graph.sourceMembers((this as any)._orderStatusList), + "customer_list": graph.sourceMembers((this as any)._customerList) + })); + for (const child of (this as any)._orderStatusList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._customerList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._orderStatusList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_status_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._customerList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("customer_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] @@ -120,6 +272,7 @@ export class Platform { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -130,7 +283,8 @@ export class Platform { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -139,36 +293,40 @@ export class Platform { for (const [index, child] of (this as any)._orderStatusList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_status_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._customerList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -176,7 +334,7 @@ export class Platform { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -188,42 +346,42 @@ export class Platform { for (const [index, child] of (this as any)._orderStatusList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_status_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._customerList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -232,12 +390,16 @@ export class Platform { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -248,38 +410,44 @@ export class Platform { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._orderStatusList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("order_status_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._customerList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("customer_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -292,6 +460,10 @@ export class Platform { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -306,7 +478,7 @@ export class Platform { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts index dc34d5b0fb8cd552f7899440dc9dd8e4557d1b2f..414df98d39f955b7e72307a3f941555308b50497 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { CustomerOrder } from '../models/CustomerOrder'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class CustomerOrderRequest { else this.selectSelfFields(); } + get entityName(): "CustomerOrder" { + return "CustomerOrder"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class CustomerOrderRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -142,14 +149,14 @@ export class CustomerOrderRequest { } - selectCustomerWith(request: { toQuery(): SelectQuery }): this { + selectCustomerWith(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { this.query.select(["customer"]); this.query.relationQuery( "customer", request.toQuery(), "customer", "id", false, { kind: "relation-select", method: "selectCustomerWith", relation: "customer" }); return this; } - selectStatusWith(request: { toQuery(): SelectQuery }): this { + selectStatusWith(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { this.query.select(["status"]); this.query.relationQuery( "status", request.toQuery(), "status", "id", false, @@ -157,7 +164,7 @@ export class CustomerOrderRequest { return this; } - withCustomerMatching(request: { toQuery(): SelectQuery }): this { + withCustomerMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { this.filters.push({ "customer": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -166,7 +173,7 @@ export class CustomerOrderRequest { return this; } - withoutCustomerMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { this.filters.push({ "customer": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -174,7 +181,7 @@ export class CustomerOrderRequest { }); return this; } - withStatusMatching(request: { toQuery(): SelectQuery }): this { + withStatusMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { this.filters.push({ "status": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -183,7 +190,7 @@ export class CustomerOrderRequest { return this; } - withoutStatusMatching(request: { toQuery(): SelectQuery }): this { + withoutStatusMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { this.filters.push({ "status": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -192,7 +199,7 @@ export class CustomerOrderRequest { return this; } - selectOrderItemListWith(request: { toQuery(): SelectQuery }): this { + selectOrderItemListWith(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { this.query.relationQuery( "orderItemList", request.toQuery(), "id", "customerOrder", true, { kind: "relation-select", method: "selectOrderItemListWith", relation: "orderItemList" }); @@ -201,17 +208,19 @@ export class CustomerOrderRequest { haveOrderItems(): this { return this.withOrderItemListMatching({ + entityName: "OrderItem", toQuery: () => new SelectQuery("OrderItem"), }); } haveNoOrderItems(): this { return this.withoutOrderItemListMatching({ + entityName: "OrderItem", toQuery: () => new SelectQuery("OrderItem"), }); } - withOrderItemListMatching(request: { toQuery(): SelectQuery }): this { + withOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -222,7 +231,7 @@ export class CustomerOrderRequest { return this; } - withoutOrderItemListMatching(request: { toQuery(): SelectQuery }): this { + withoutOrderItemListMatching(request: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -239,13 +248,13 @@ export class CustomerOrderRequest { countOrderItemsAs(alias: string): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); - this.countOrderItemsWith(alias, { toQuery: () => query }); + this.countOrderItemsWith(alias, { entityName: "OrderItem", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countOrderItemsAs", relation: "orderItemList", alias }; return this; } - countOrderItemsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countOrderItemsWith(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -257,10 +266,10 @@ export class CustomerOrderRequest { minQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.minQuantityOfOrderItemsAs( - "minOfQuantityOfOrderItems", { toQuery: () => query }); + "minOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - minQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "quantity", alias); @@ -271,10 +280,10 @@ export class CustomerOrderRequest { maxQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.maxQuantityOfOrderItemsAs( - "maxOfQuantityOfOrderItems", { toQuery: () => query }); + "maxOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - maxQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "quantity", alias); @@ -285,10 +294,10 @@ export class CustomerOrderRequest { sumQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.sumQuantityOfOrderItemsAs( - "sumOfQuantityOfOrderItems", { toQuery: () => query }); + "sumOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - sumQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "quantity", alias); @@ -299,10 +308,10 @@ export class CustomerOrderRequest { avgQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.avgQuantityOfOrderItemsAs( - "avgOfQuantityOfOrderItems", { toQuery: () => query }); + "avgOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - avgQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "quantity", alias); @@ -313,10 +322,10 @@ export class CustomerOrderRequest { standardDeviationQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.standardDeviationQuantityOfOrderItemsAs( - "standardDeviationOfQuantityOfOrderItems", { toQuery: () => query }); + "standardDeviationOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - standardDeviationQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "quantity", alias); @@ -327,10 +336,10 @@ export class CustomerOrderRequest { squareRootOfPopulationStandardDeviationQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs( - "squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "quantity", alias); @@ -341,10 +350,10 @@ export class CustomerOrderRequest { sampleVarianceQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.sampleVarianceQuantityOfOrderItemsAs( - "sampleVarianceOfQuantityOfOrderItems", { toQuery: () => query }); + "sampleVarianceOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - sampleVarianceQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "quantity", alias); @@ -355,10 +364,10 @@ export class CustomerOrderRequest { samplePopulationVarianceQuantityOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceQuantityOfOrderItemsAs( - "samplePopulationVarianceOfQuantityOfOrderItems", { toQuery: () => query }); + "samplePopulationVarianceOfQuantityOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - samplePopulationVarianceQuantityOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceQuantityOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "quantity", alias); @@ -369,10 +378,10 @@ export class CustomerOrderRequest { minUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.minUnitPriceOfOrderItemsAs( - "minOfUnitPriceOfOrderItems", { toQuery: () => query }); + "minOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - minUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "unitPrice", alias); @@ -383,10 +392,10 @@ export class CustomerOrderRequest { maxUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.maxUnitPriceOfOrderItemsAs( - "maxOfUnitPriceOfOrderItems", { toQuery: () => query }); + "maxOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - maxUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "unitPrice", alias); @@ -397,10 +406,10 @@ export class CustomerOrderRequest { sumUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.sumUnitPriceOfOrderItemsAs( - "sumOfUnitPriceOfOrderItems", { toQuery: () => query }); + "sumOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - sumUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "unitPrice", alias); @@ -411,10 +420,10 @@ export class CustomerOrderRequest { avgUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.avgUnitPriceOfOrderItemsAs( - "avgOfUnitPriceOfOrderItems", { toQuery: () => query }); + "avgOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - avgUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "unitPrice", alias); @@ -425,10 +434,10 @@ export class CustomerOrderRequest { standardDeviationUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.standardDeviationUnitPriceOfOrderItemsAs( - "standardDeviationOfUnitPriceOfOrderItems", { toQuery: () => query }); + "standardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "unitPrice", alias); @@ -439,10 +448,10 @@ export class CustomerOrderRequest { squareRootOfPopulationStandardDeviationUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs( - "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "unitPrice", alias); @@ -453,10 +462,10 @@ export class CustomerOrderRequest { sampleVarianceUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.sampleVarianceUnitPriceOfOrderItemsAs( - "sampleVarianceOfUnitPriceOfOrderItems", { toQuery: () => query }); + "sampleVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "unitPrice", alias); @@ -467,10 +476,10 @@ export class CustomerOrderRequest { samplePopulationVarianceUnitPriceOfOrderItems(): this { const query = new SelectQuery("OrderItem").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceUnitPriceOfOrderItemsAs( - "samplePopulationVarianceOfUnitPriceOfOrderItems", { toQuery: () => query }); + "samplePopulationVarianceOfUnitPriceOfOrderItems", { entityName: "OrderItem", toQuery: () => query }); } - samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceUnitPriceOfOrderItemsAs(alias: string, child: { readonly entityName: "OrderItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "unitPrice", alias); @@ -479,47 +488,47 @@ export class CustomerOrderRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -596,42 +605,42 @@ export class CustomerOrderRequest { return this; } - withOrderNumberIsNot(val: any): this { + withOrderNumberIsNot(val: string): this { this.filters.push({ "orderNumber": { "$ne": val } }); return this; } - withOrderNumberIn(...vals: any[]): this { + withOrderNumberIn(...vals: string[]): this { this.filters.push({ "orderNumber": { "$in": vals } }); return this; } - withOrderNumberNotIn(...vals: any[]): this { + withOrderNumberNotIn(...vals: string[]): this { this.filters.push({ "orderNumber": { "$notIn": vals } }); return this; } - withOrderNumberGreaterThan(val: any): this { + withOrderNumberGreaterThan(val: string): this { this.filters.push({ "orderNumber": { "$gt": val } }); return this; } - withOrderNumberGreaterThanOrEqualTo(val: any): this { + withOrderNumberGreaterThanOrEqualTo(val: string): this { this.filters.push({ "orderNumber": { "$gte": val } }); return this; } - withOrderNumberLessThan(val: any): this { + withOrderNumberLessThan(val: string): this { this.filters.push({ "orderNumber": { "$lt": val } }); return this; } - withOrderNumberLessThanOrEqualTo(val: any): this { + withOrderNumberLessThanOrEqualTo(val: string): this { this.filters.push({ "orderNumber": { "$lte": val } }); return this; } - withOrderNumberBetween(lower: any, upper: any): this { + withOrderNumberBetween(lower: string, upper: string): this { this.filters.push({ "orderNumber": { "$between": [lower, upper] } }); return this; } @@ -675,47 +684,47 @@ export class CustomerOrderRequest { return this; } - withOrderDateIs(val: any): this { + withOrderDateIs(val: string): this { this.filters.push({ "orderDate": { "$eq": val } }); return this; } - withOrderDateIsNot(val: any): this { + withOrderDateIsNot(val: string): this { this.filters.push({ "orderDate": { "$ne": val } }); return this; } - withOrderDateIn(...vals: any[]): this { + withOrderDateIn(...vals: string[]): this { this.filters.push({ "orderDate": { "$in": vals } }); return this; } - withOrderDateNotIn(...vals: any[]): this { + withOrderDateNotIn(...vals: string[]): this { this.filters.push({ "orderDate": { "$notIn": vals } }); return this; } - withOrderDateGreaterThan(val: any): this { + withOrderDateGreaterThan(val: string): this { this.filters.push({ "orderDate": { "$gt": val } }); return this; } - withOrderDateGreaterThanOrEqualTo(val: any): this { + withOrderDateGreaterThanOrEqualTo(val: string): this { this.filters.push({ "orderDate": { "$gte": val } }); return this; } - withOrderDateLessThan(val: any): this { + withOrderDateLessThan(val: string): this { this.filters.push({ "orderDate": { "$lt": val } }); return this; } - withOrderDateLessThanOrEqualTo(val: any): this { + withOrderDateLessThanOrEqualTo(val: string): this { this.filters.push({ "orderDate": { "$lte": val } }); return this; } - withOrderDateBetween(lower: any, upper: any): this { + withOrderDateBetween(lower: string, upper: string): this { this.filters.push({ "orderDate": { "$between": [lower, upper] } }); return this; } @@ -730,47 +739,47 @@ export class CustomerOrderRequest { return this; } - withTotalAmountIs(val: any): this { + withTotalAmountIs(val: Decimal): this { this.filters.push({ "totalAmount": { "$eq": val } }); return this; } - withTotalAmountIsNot(val: any): this { + withTotalAmountIsNot(val: Decimal): this { this.filters.push({ "totalAmount": { "$ne": val } }); return this; } - withTotalAmountIn(...vals: any[]): this { + withTotalAmountIn(...vals: Decimal[]): this { this.filters.push({ "totalAmount": { "$in": vals } }); return this; } - withTotalAmountNotIn(...vals: any[]): this { + withTotalAmountNotIn(...vals: Decimal[]): this { this.filters.push({ "totalAmount": { "$notIn": vals } }); return this; } - withTotalAmountGreaterThan(val: any): this { + withTotalAmountGreaterThan(val: Decimal): this { this.filters.push({ "totalAmount": { "$gt": val } }); return this; } - withTotalAmountGreaterThanOrEqualTo(val: any): this { + withTotalAmountGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "totalAmount": { "$gte": val } }); return this; } - withTotalAmountLessThan(val: any): this { + withTotalAmountLessThan(val: Decimal): this { this.filters.push({ "totalAmount": { "$lt": val } }); return this; } - withTotalAmountLessThanOrEqualTo(val: any): this { + withTotalAmountLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "totalAmount": { "$lte": val } }); return this; } - withTotalAmountBetween(lower: any, upper: any): this { + withTotalAmountBetween(lower: Decimal, upper: Decimal): this { this.filters.push({ "totalAmount": { "$between": [lower, upper] } }); return this; } @@ -785,47 +794,47 @@ export class CustomerOrderRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -980,7 +989,7 @@ export class CustomerOrderRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByCustomer(): this { @@ -989,7 +998,7 @@ export class CustomerOrderRequest { } groupByCustomerAs(retName: string): this { - this.query.groupBy("customer"); // In TS we don't alias group by yet natively + this.query.groupBy("customer", retName); return this; } groupByStatus(): this { @@ -998,7 +1007,7 @@ export class CustomerOrderRequest { } groupByStatusAs(retName: string): this { - this.query.groupBy("status"); // In TS we don't alias group by yet natively + this.query.groupBy("status", retName); return this; } groupByOrderNumber(): this { @@ -1007,7 +1016,7 @@ export class CustomerOrderRequest { } groupByOrderNumberAs(retName: string): this { - this.query.groupBy("orderNumber"); // In TS we don't alias group by yet natively + this.query.groupBy("orderNumber", retName); return this; } groupByOrderDate(): this { @@ -1016,7 +1025,7 @@ export class CustomerOrderRequest { } groupByOrderDateAs(retName: string): this { - this.query.groupBy("orderDate"); // In TS we don't alias group by yet natively + this.query.groupBy("orderDate", retName); return this; } groupByTotalAmount(): this { @@ -1025,7 +1034,7 @@ export class CustomerOrderRequest { } groupByTotalAmountAs(retName: string): this { - this.query.groupBy("totalAmount"); // In TS we don't alias group by yet natively + this.query.groupBy("totalAmount", retName); return this; } groupByVersion(): this { @@ -1034,14 +1043,14 @@ export class CustomerOrderRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByCustomerAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Customer"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "customer", request, includeAllFacets, @@ -1051,7 +1060,7 @@ export class CustomerOrderRequest { facetByStatusAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "status", request, includeAllFacets, @@ -1167,9 +1176,10 @@ export class ExecutableCustomerOrderRequest { return this; } - newEntity(context: UserContext): CustomerOrder { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new CustomerOrder(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return CustomerOrder.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts index 2a51eebba8d63abb2cf26fe0c5e4810032a6faa1..f686f04646c0d7892acc563d885ecf9310774414 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Customer } from '../models/Customer'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class CustomerRequest { else this.selectSelfFields(); } + get entityName(): "Customer" { + return "Customer"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class CustomerRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -131,7 +138,7 @@ export class CustomerRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -139,7 +146,7 @@ export class CustomerRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -148,7 +155,7 @@ export class CustomerRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -157,7 +164,7 @@ export class CustomerRequest { return this; } - selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.relationQuery( "customerOrderList", request.toQuery(), "id", "customer", true, { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" }); @@ -166,17 +173,19 @@ export class CustomerRequest { haveCustomerOrders(): this { return this.withCustomerOrderListMatching({ + entityName: "CustomerOrder", toQuery: () => new SelectQuery("CustomerOrder"), }); } haveNoCustomerOrders(): this { return this.withoutCustomerOrderListMatching({ + entityName: "CustomerOrder", toQuery: () => new SelectQuery("CustomerOrder"), }); } - withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -187,7 +196,7 @@ export class CustomerRequest { return this; } - withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -204,13 +213,13 @@ export class CustomerRequest { countCustomerOrdersAs(alias: string): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); - this.countCustomerOrdersWith(alias, { toQuery: () => query }); + this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias }; return this; } - countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this { + countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -222,10 +231,10 @@ export class CustomerRequest { minTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.minTotalAmountOfCustomerOrdersAs( - "minOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - minTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "totalAmount", alias); @@ -236,10 +245,10 @@ export class CustomerRequest { maxTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.maxTotalAmountOfCustomerOrdersAs( - "maxOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - maxTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "totalAmount", alias); @@ -250,10 +259,10 @@ export class CustomerRequest { sumTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.sumTotalAmountOfCustomerOrdersAs( - "sumOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - sumTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "totalAmount", alias); @@ -264,10 +273,10 @@ export class CustomerRequest { avgTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.avgTotalAmountOfCustomerOrdersAs( - "avgOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - avgTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "totalAmount", alias); @@ -278,10 +287,10 @@ export class CustomerRequest { standardDeviationTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.standardDeviationTotalAmountOfCustomerOrdersAs( - "standardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "totalAmount", alias); @@ -292,10 +301,10 @@ export class CustomerRequest { squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs( - "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "totalAmount", alias); @@ -306,10 +315,10 @@ export class CustomerRequest { sampleVarianceTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.sampleVarianceTotalAmountOfCustomerOrdersAs( - "sampleVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "totalAmount", alias); @@ -320,10 +329,10 @@ export class CustomerRequest { samplePopulationVarianceTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs( - "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "totalAmount", alias); @@ -332,47 +341,47 @@ export class CustomerRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -417,42 +426,42 @@ export class CustomerRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -496,47 +505,47 @@ export class CustomerRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -606,7 +615,7 @@ export class CustomerRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByPlatform(): this { @@ -615,7 +624,7 @@ export class CustomerRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupByName(): this { @@ -624,7 +633,7 @@ export class CustomerRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByVersion(): this { @@ -633,14 +642,14 @@ export class CustomerRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -756,9 +765,10 @@ export class ExecutableCustomerRequest { return this; } - newEntity(context: UserContext): Customer { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Customer(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Customer.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts index 25e555f713a8ef73ad488af4170b407e821824a3..6d3fb5cdbf97d3b629e25a77d4eb53137d299a8a 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { OrderItem } from '../models/OrderItem'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class OrderItemRequest { else this.selectSelfFields(); } + get entityName(): "OrderItem" { + return "OrderItem"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class OrderItemRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -141,7 +148,7 @@ export class OrderItemRequest { } - selectCustomerOrderWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.select(["customerOrder"]); this.query.relationQuery( "customerOrder", request.toQuery(), "customerOrder", "id", false, @@ -149,7 +156,7 @@ export class OrderItemRequest { return this; } - withCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -158,7 +165,7 @@ export class OrderItemRequest { return this; } - withoutCustomerOrderMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "customerOrder": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -170,47 +177,47 @@ export class OrderItemRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -255,42 +262,42 @@ export class OrderItemRequest { return this; } - withProductNameIsNot(val: any): this { + withProductNameIsNot(val: string): this { this.filters.push({ "productName": { "$ne": val } }); return this; } - withProductNameIn(...vals: any[]): this { + withProductNameIn(...vals: string[]): this { this.filters.push({ "productName": { "$in": vals } }); return this; } - withProductNameNotIn(...vals: any[]): this { + withProductNameNotIn(...vals: string[]): this { this.filters.push({ "productName": { "$notIn": vals } }); return this; } - withProductNameGreaterThan(val: any): this { + withProductNameGreaterThan(val: string): this { this.filters.push({ "productName": { "$gt": val } }); return this; } - withProductNameGreaterThanOrEqualTo(val: any): this { + withProductNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "productName": { "$gte": val } }); return this; } - withProductNameLessThan(val: any): this { + withProductNameLessThan(val: string): this { this.filters.push({ "productName": { "$lt": val } }); return this; } - withProductNameLessThanOrEqualTo(val: any): this { + withProductNameLessThanOrEqualTo(val: string): this { this.filters.push({ "productName": { "$lte": val } }); return this; } - withProductNameBetween(lower: any, upper: any): this { + withProductNameBetween(lower: string, upper: string): this { this.filters.push({ "productName": { "$between": [lower, upper] } }); return this; } @@ -334,47 +341,47 @@ export class OrderItemRequest { return this; } - withQuantityIs(val: any): this { + withQuantityIs(val: number): this { this.filters.push({ "quantity": { "$eq": val } }); return this; } - withQuantityIsNot(val: any): this { + withQuantityIsNot(val: number): this { this.filters.push({ "quantity": { "$ne": val } }); return this; } - withQuantityIn(...vals: any[]): this { + withQuantityIn(...vals: number[]): this { this.filters.push({ "quantity": { "$in": vals } }); return this; } - withQuantityNotIn(...vals: any[]): this { + withQuantityNotIn(...vals: number[]): this { this.filters.push({ "quantity": { "$notIn": vals } }); return this; } - withQuantityGreaterThan(val: any): this { + withQuantityGreaterThan(val: number): this { this.filters.push({ "quantity": { "$gt": val } }); return this; } - withQuantityGreaterThanOrEqualTo(val: any): this { + withQuantityGreaterThanOrEqualTo(val: number): this { this.filters.push({ "quantity": { "$gte": val } }); return this; } - withQuantityLessThan(val: any): this { + withQuantityLessThan(val: number): this { this.filters.push({ "quantity": { "$lt": val } }); return this; } - withQuantityLessThanOrEqualTo(val: any): this { + withQuantityLessThanOrEqualTo(val: number): this { this.filters.push({ "quantity": { "$lte": val } }); return this; } - withQuantityBetween(lower: any, upper: any): this { + withQuantityBetween(lower: number, upper: number): this { this.filters.push({ "quantity": { "$between": [lower, upper] } }); return this; } @@ -389,47 +396,47 @@ export class OrderItemRequest { return this; } - withUnitPriceIs(val: any): this { + withUnitPriceIs(val: Decimal): this { this.filters.push({ "unitPrice": { "$eq": val } }); return this; } - withUnitPriceIsNot(val: any): this { + withUnitPriceIsNot(val: Decimal): this { this.filters.push({ "unitPrice": { "$ne": val } }); return this; } - withUnitPriceIn(...vals: any[]): this { + withUnitPriceIn(...vals: Decimal[]): this { this.filters.push({ "unitPrice": { "$in": vals } }); return this; } - withUnitPriceNotIn(...vals: any[]): this { + withUnitPriceNotIn(...vals: Decimal[]): this { this.filters.push({ "unitPrice": { "$notIn": vals } }); return this; } - withUnitPriceGreaterThan(val: any): this { + withUnitPriceGreaterThan(val: Decimal): this { this.filters.push({ "unitPrice": { "$gt": val } }); return this; } - withUnitPriceGreaterThanOrEqualTo(val: any): this { + withUnitPriceGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "unitPrice": { "$gte": val } }); return this; } - withUnitPriceLessThan(val: any): this { + withUnitPriceLessThan(val: Decimal): this { this.filters.push({ "unitPrice": { "$lt": val } }); return this; } - withUnitPriceLessThanOrEqualTo(val: any): this { + withUnitPriceLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "unitPrice": { "$lte": val } }); return this; } - withUnitPriceBetween(lower: any, upper: any): this { + withUnitPriceBetween(lower: Decimal, upper: Decimal): this { this.filters.push({ "unitPrice": { "$between": [lower, upper] } }); return this; } @@ -444,47 +451,47 @@ export class OrderItemRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -702,7 +709,7 @@ export class OrderItemRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByCustomerOrder(): this { @@ -711,7 +718,7 @@ export class OrderItemRequest { } groupByCustomerOrderAs(retName: string): this { - this.query.groupBy("customerOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("customerOrder", retName); return this; } groupByProductName(): this { @@ -720,7 +727,7 @@ export class OrderItemRequest { } groupByProductNameAs(retName: string): this { - this.query.groupBy("productName"); // In TS we don't alias group by yet natively + this.query.groupBy("productName", retName); return this; } groupByQuantity(): this { @@ -729,7 +736,7 @@ export class OrderItemRequest { } groupByQuantityAs(retName: string): this { - this.query.groupBy("quantity"); // In TS we don't alias group by yet natively + this.query.groupBy("quantity", retName); return this; } groupByUnitPrice(): this { @@ -738,7 +745,7 @@ export class OrderItemRequest { } groupByUnitPriceAs(retName: string): this { - this.query.groupBy("unitPrice"); // In TS we don't alias group by yet natively + this.query.groupBy("unitPrice", retName); return this; } groupByVersion(): this { @@ -747,14 +754,14 @@ export class OrderItemRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByCustomerOrderAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "customerOrder", request, includeAllFacets, @@ -870,9 +877,10 @@ export class ExecutableOrderItemRequest { return this; } - newEntity(context: UserContext): OrderItem { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new OrderItem(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderItem.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts index 26fa6973bc60c899419a62f0c971f92bffe7027a..a82759c128bcd604d667547bd60d5d1b335505c1 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { OrderStatus } from '../models/OrderStatus'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class OrderStatusRequest { else this.selectSelfFields(); } + get entityName(): "OrderStatus" { + return "OrderStatus"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class OrderStatusRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -145,7 +152,7 @@ export class OrderStatusRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -153,7 +160,7 @@ export class OrderStatusRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -162,7 +169,7 @@ export class OrderStatusRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -171,7 +178,7 @@ export class OrderStatusRequest { return this; } - selectCustomerOrderListWith(request: { toQuery(): SelectQuery }): this { + selectCustomerOrderListWith(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.query.relationQuery( "customerOrderList", request.toQuery(), "id", "status", true, { kind: "relation-select", method: "selectCustomerOrderListWith", relation: "customerOrderList" }); @@ -180,17 +187,19 @@ export class OrderStatusRequest { haveCustomerOrders(): this { return this.withCustomerOrderListMatching({ + entityName: "CustomerOrder", toQuery: () => new SelectQuery("CustomerOrder"), }); } haveNoCustomerOrders(): this { return this.withoutCustomerOrderListMatching({ + entityName: "CustomerOrder", toQuery: () => new SelectQuery("CustomerOrder"), }); } - withCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this { + withCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -201,7 +210,7 @@ export class OrderStatusRequest { return this; } - withoutCustomerOrderListMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerOrderListMatching(request: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -218,13 +227,13 @@ export class OrderStatusRequest { countCustomerOrdersAs(alias: string): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); - this.countCustomerOrdersWith(alias, { toQuery: () => query }); + this.countCustomerOrdersWith(alias, { entityName: "CustomerOrder", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countCustomerOrdersAs", relation: "customerOrderList", alias }; return this; } - countCustomerOrdersWith(alias: string, child: { toQuery(): SelectQuery }): this { + countCustomerOrdersWith(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -236,10 +245,10 @@ export class OrderStatusRequest { minTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.minTotalAmountOfCustomerOrdersAs( - "minOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "minOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - minTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + minTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "totalAmount", alias); @@ -250,10 +259,10 @@ export class OrderStatusRequest { maxTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.maxTotalAmountOfCustomerOrdersAs( - "maxOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "maxOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - maxTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "totalAmount", alias); @@ -264,10 +273,10 @@ export class OrderStatusRequest { sumTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.sumTotalAmountOfCustomerOrdersAs( - "sumOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "sumOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - sumTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "totalAmount", alias); @@ -278,10 +287,10 @@ export class OrderStatusRequest { avgTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.avgTotalAmountOfCustomerOrdersAs( - "avgOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "avgOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - avgTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "totalAmount", alias); @@ -292,10 +301,10 @@ export class OrderStatusRequest { standardDeviationTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.standardDeviationTotalAmountOfCustomerOrdersAs( - "standardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "standardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "totalAmount", alias); @@ -306,10 +315,10 @@ export class OrderStatusRequest { squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs( - "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "totalAmount", alias); @@ -320,10 +329,10 @@ export class OrderStatusRequest { sampleVarianceTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.sampleVarianceTotalAmountOfCustomerOrdersAs( - "sampleVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "sampleVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "totalAmount", alias); @@ -334,10 +343,10 @@ export class OrderStatusRequest { samplePopulationVarianceTotalAmountOfCustomerOrders(): this { const query = new SelectQuery("CustomerOrder").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceTotalAmountOfCustomerOrdersAs( - "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { toQuery: () => query }); + "samplePopulationVarianceOfTotalAmountOfCustomerOrders", { entityName: "CustomerOrder", toQuery: () => query }); } - samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceTotalAmountOfCustomerOrdersAs(alias: string, child: { readonly entityName: "CustomerOrder"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "totalAmount", alias); @@ -366,47 +375,47 @@ export class OrderStatusRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -431,42 +440,42 @@ export class OrderStatusRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -520,42 +529,42 @@ export class OrderStatusRequest { return this; } - withCodeIsNot(val: any): this { + withCodeIsNot(val: string): this { this.filters.push({ "code": { "$ne": val } }); return this; } - withCodeIn(...vals: any[]): this { + withCodeIn(...vals: string[]): this { this.filters.push({ "code": { "$in": vals } }); return this; } - withCodeNotIn(...vals: any[]): this { + withCodeNotIn(...vals: string[]): this { this.filters.push({ "code": { "$notIn": vals } }); return this; } - withCodeGreaterThan(val: any): this { + withCodeGreaterThan(val: string): this { this.filters.push({ "code": { "$gt": val } }); return this; } - withCodeGreaterThanOrEqualTo(val: any): this { + withCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$gte": val } }); return this; } - withCodeLessThan(val: any): this { + withCodeLessThan(val: string): this { this.filters.push({ "code": { "$lt": val } }); return this; } - withCodeLessThanOrEqualTo(val: any): this { + withCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$lte": val } }); return this; } - withCodeBetween(lower: any, upper: any): this { + withCodeBetween(lower: string, upper: string): this { this.filters.push({ "code": { "$between": [lower, upper] } }); return this; } @@ -609,42 +618,42 @@ export class OrderStatusRequest { return this; } - withColorIsNot(val: any): this { + withColorIsNot(val: string): this { this.filters.push({ "color": { "$ne": val } }); return this; } - withColorIn(...vals: any[]): this { + withColorIn(...vals: string[]): this { this.filters.push({ "color": { "$in": vals } }); return this; } - withColorNotIn(...vals: any[]): this { + withColorNotIn(...vals: string[]): this { this.filters.push({ "color": { "$notIn": vals } }); return this; } - withColorGreaterThan(val: any): this { + withColorGreaterThan(val: string): this { this.filters.push({ "color": { "$gt": val } }); return this; } - withColorGreaterThanOrEqualTo(val: any): this { + withColorGreaterThanOrEqualTo(val: string): this { this.filters.push({ "color": { "$gte": val } }); return this; } - withColorLessThan(val: any): this { + withColorLessThan(val: string): this { this.filters.push({ "color": { "$lt": val } }); return this; } - withColorLessThanOrEqualTo(val: any): this { + withColorLessThanOrEqualTo(val: string): this { this.filters.push({ "color": { "$lte": val } }); return this; } - withColorBetween(lower: any, upper: any): this { + withColorBetween(lower: string, upper: string): this { this.filters.push({ "color": { "$between": [lower, upper] } }); return this; } @@ -688,47 +697,47 @@ export class OrderStatusRequest { return this; } - withDisplayOrderIs(val: any): this { + withDisplayOrderIs(val: number): this { this.filters.push({ "displayOrder": { "$eq": val } }); return this; } - withDisplayOrderIsNot(val: any): this { + withDisplayOrderIsNot(val: number): this { this.filters.push({ "displayOrder": { "$ne": val } }); return this; } - withDisplayOrderIn(...vals: any[]): this { + withDisplayOrderIn(...vals: number[]): this { this.filters.push({ "displayOrder": { "$in": vals } }); return this; } - withDisplayOrderNotIn(...vals: any[]): this { + withDisplayOrderNotIn(...vals: number[]): this { this.filters.push({ "displayOrder": { "$notIn": vals } }); return this; } - withDisplayOrderGreaterThan(val: any): this { + withDisplayOrderGreaterThan(val: number): this { this.filters.push({ "displayOrder": { "$gt": val } }); return this; } - withDisplayOrderGreaterThanOrEqualTo(val: any): this { + withDisplayOrderGreaterThanOrEqualTo(val: number): this { this.filters.push({ "displayOrder": { "$gte": val } }); return this; } - withDisplayOrderLessThan(val: any): this { + withDisplayOrderLessThan(val: number): this { this.filters.push({ "displayOrder": { "$lt": val } }); return this; } - withDisplayOrderLessThanOrEqualTo(val: any): this { + withDisplayOrderLessThanOrEqualTo(val: number): this { this.filters.push({ "displayOrder": { "$lte": val } }); return this; } - withDisplayOrderBetween(lower: any, upper: any): this { + withDisplayOrderBetween(lower: number, upper: number): this { this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); return this; } @@ -743,47 +752,47 @@ export class OrderStatusRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -946,7 +955,7 @@ export class OrderStatusRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupById(): this { @@ -955,7 +964,7 @@ export class OrderStatusRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -964,7 +973,7 @@ export class OrderStatusRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByCode(): this { @@ -973,7 +982,7 @@ export class OrderStatusRequest { } groupByCodeAs(retName: string): this { - this.query.groupBy("code"); // In TS we don't alias group by yet natively + this.query.groupBy("code", retName); return this; } groupByColor(): this { @@ -982,7 +991,7 @@ export class OrderStatusRequest { } groupByColorAs(retName: string): this { - this.query.groupBy("color"); // In TS we don't alias group by yet natively + this.query.groupBy("color", retName); return this; } groupByDisplayOrder(): this { @@ -991,7 +1000,7 @@ export class OrderStatusRequest { } groupByDisplayOrderAs(retName: string): this { - this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("displayOrder", retName); return this; } groupByVersion(): this { @@ -1000,14 +1009,14 @@ export class OrderStatusRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1123,9 +1132,10 @@ export class ExecutableOrderStatusRequest { return this; } - newEntity(context: UserContext): OrderStatus { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new OrderStatus(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return OrderStatus.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts index 6f44548cc3788a1325f0307b6a8e2bc0d8d1a58a..75f64520bdd0e6292db0bfd8df4d65c2e0a7f2fa 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PlatformRequest { else this.selectSelfFields(); } + get entityName(): "Platform" { + return "Platform"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PlatformRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -132,13 +139,13 @@ export class PlatformRequest { - selectOrderStatusListWith(request: { toQuery(): SelectQuery }): this { + selectOrderStatusListWith(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { this.query.relationQuery( "orderStatusList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectOrderStatusListWith", relation: "orderStatusList" }); return this; } - selectCustomerListWith(request: { toQuery(): SelectQuery }): this { + selectCustomerListWith(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { this.query.relationQuery( "customerList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectCustomerListWith", relation: "customerList" }); @@ -147,17 +154,19 @@ export class PlatformRequest { haveOrderStatuses(): this { return this.withOrderStatusListMatching({ + entityName: "OrderStatus", toQuery: () => new SelectQuery("OrderStatus"), }); } haveNoOrderStatuses(): this { return this.withoutOrderStatusListMatching({ + entityName: "OrderStatus", toQuery: () => new SelectQuery("OrderStatus"), }); } - withOrderStatusListMatching(request: { toQuery(): SelectQuery }): this { + withOrderStatusListMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -168,7 +177,7 @@ export class PlatformRequest { return this; } - withoutOrderStatusListMatching(request: { toQuery(): SelectQuery }): this { + withoutOrderStatusListMatching(request: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -180,17 +189,19 @@ export class PlatformRequest { } haveCustomers(): this { return this.withCustomerListMatching({ + entityName: "Customer", toQuery: () => new SelectQuery("Customer"), }); } haveNoCustomers(): this { return this.withoutCustomerListMatching({ + entityName: "Customer", toQuery: () => new SelectQuery("Customer"), }); } - withCustomerListMatching(request: { toQuery(): SelectQuery }): this { + withCustomerListMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -201,7 +212,7 @@ export class PlatformRequest { return this; } - withoutCustomerListMatching(request: { toQuery(): SelectQuery }): this { + withoutCustomerListMatching(request: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -218,13 +229,13 @@ export class PlatformRequest { countOrderStatusesAs(alias: string): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); - this.countOrderStatusesWith(alias, { toQuery: () => query }); + this.countOrderStatusesWith(alias, { entityName: "OrderStatus", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countOrderStatusesAs", relation: "orderStatusList", alias }; return this; } - countOrderStatusesWith(alias: string, child: { toQuery(): SelectQuery }): this { + countOrderStatusesWith(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -236,10 +247,10 @@ export class PlatformRequest { minDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.minDisplayOrderOfOrderStatusesAs( - "minOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "minOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - minDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + minDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "displayOrder", alias); @@ -250,10 +261,10 @@ export class PlatformRequest { maxDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.maxDisplayOrderOfOrderStatusesAs( - "maxOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "maxOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - maxDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "displayOrder", alias); @@ -264,10 +275,10 @@ export class PlatformRequest { sumDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.sumDisplayOrderOfOrderStatusesAs( - "sumOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "sumOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - sumDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "displayOrder", alias); @@ -278,10 +289,10 @@ export class PlatformRequest { avgDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.avgDisplayOrderOfOrderStatusesAs( - "avgOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "avgOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - avgDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "displayOrder", alias); @@ -292,10 +303,10 @@ export class PlatformRequest { standardDeviationDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.standardDeviationDisplayOrderOfOrderStatusesAs( - "standardDeviationOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "standardDeviationOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - standardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "displayOrder", alias); @@ -306,10 +317,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs( - "squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "displayOrder", alias); @@ -320,10 +331,10 @@ export class PlatformRequest { sampleVarianceDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.sampleVarianceDisplayOrderOfOrderStatusesAs( - "sampleVarianceOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "sampleVarianceOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - sampleVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "displayOrder", alias); @@ -334,10 +345,10 @@ export class PlatformRequest { samplePopulationVarianceDisplayOrderOfOrderStatuses(): this { const query = new SelectQuery("OrderStatus").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceDisplayOrderOfOrderStatusesAs( - "samplePopulationVarianceOfDisplayOrderOfOrderStatuses", { toQuery: () => query }); + "samplePopulationVarianceOfDisplayOrderOfOrderStatuses", { entityName: "OrderStatus", toQuery: () => query }); } - samplePopulationVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceDisplayOrderOfOrderStatusesAs(alias: string, child: { readonly entityName: "OrderStatus"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "displayOrder", alias); @@ -351,13 +362,13 @@ export class PlatformRequest { countCustomersAs(alias: string): this { const query = new SelectQuery("Customer").filter({ version: { "$gte": 1 } }); - this.countCustomersWith(alias, { toQuery: () => query }); + this.countCustomersWith(alias, { entityName: "Customer", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countCustomersAs", relation: "customerList", alias }; return this; } - countCustomersWith(alias: string, child: { toQuery(): SelectQuery }): this { + countCustomersWith(alias: string, child: { readonly entityName: "Customer"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -368,47 +379,47 @@ export class PlatformRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -433,42 +444,42 @@ export class PlatformRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -512,47 +523,47 @@ export class PlatformRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -621,7 +632,7 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -630,7 +641,7 @@ export class PlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByVersion(): this { @@ -639,7 +650,7 @@ export class PlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } @@ -752,9 +763,10 @@ export class ExecutablePlatformRequest { return this; } - newEntity(context: UserContext): Platform { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Platform(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/runtime-module.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/runtime-module.ts index 6acd8901738de1cf9c62144bac04a2da46fec691..7182beaca7a2f7aada20292bc13e58ddd551237e 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/runtime-module.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/runtime-module.ts @@ -1,3 +1,4 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; import { ObjectLocation, RuntimeModule } from "teaql-ts"; import { ENTITY_SCHEMAS } from "./teaql-schemas"; import { ensureGeneratedBootstrap } from "./generated-bootstrap"; diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-schemas.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-schemas.ts index 879ae338448bc5e7d73d2e91a1cdc034d3a97213..99c33d7e81639a3db9c718c8c7a18957b2293e02 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-schemas.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-schemas.ts @@ -10,7 +10,7 @@ export const ENTITY_SCHEMAS: Record = { "OrderStatus": { table: "order_status_data", auditMaskFields: [], - columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "color": { columnName: "color", modelName: "color", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "customerOrderList": { targetEntity: "CustomerOrder", localKey: "id", foreignKey: "status", many: true }} }, "Customer": { @@ -22,13 +22,13 @@ export const ENTITY_SCHEMAS: Record = { "CustomerOrder": { table: "customer_order_data", auditMaskFields: [], - columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customer": { columnName: "customer", modelName: "customer", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "orderNumber": { columnName: "order_number", modelName: "order_number", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "orderDate": { columnName: "order_date", modelName: "order_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "totalAmount": { columnName: "total_amount", modelName: "total_amount", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customer": { columnName: "customer", modelName: "customer", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "status": { columnName: "status", modelName: "status", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "orderNumber": { columnName: "order_number", modelName: "order_number", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "orderDate": { columnName: "order_date", modelName: "order_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "totalAmount": { columnName: "total_amount", modelName: "total_amount", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"customer": { targetEntity: "Customer", localKey: "customer", foreignKey: "id", many: false }, "status": { targetEntity: "OrderStatus", localKey: "status", foreignKey: "id", many: false }, "orderItemList": { targetEntity: "OrderItem", localKey: "id", foreignKey: "customerOrder", many: true }} }, "OrderItem": { table: "order_item_data", auditMaskFields: [], - columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customerOrder": { columnName: "customer_order", modelName: "customer_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "quantity": { columnName: "quantity", modelName: "quantity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "unitPrice": { columnName: "unit_price", modelName: "unit_price", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "customerOrder": { columnName: "customer_order", modelName: "customer_order", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "productName": { columnName: "product_name", modelName: "product_name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "quantity": { columnName: "quantity", modelName: "quantity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "unitPrice": { columnName: "unit_price", modelName: "unit_price", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"customerOrder": { targetEntity: "CustomerOrder", localKey: "customerOrder", foreignKey: "id", many: false }} } }; \ No newline at end of file diff --git a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-ts.ts b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-ts.ts index b54a29ac3c12fb072cf4c292e22bb2e644b56319..9983b00b27c90dc429fca76441f2bf077f825921 100644 --- a/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-ts.ts +++ b/source/teaql-ts/examples/browser-sqlite/orders-lib/src/teaql-ts.ts @@ -1,14 +1,26 @@ import { - CheckException, EntityChecker, RuntimeModule, + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, SelectQuery as RuntimeSelectQuery, UserContext, - executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, } from "teaql-ts"; export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; -export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; export type { EntityKey } from "teaql-ts"; export type { TeaQLPage } from "teaql-ts"; import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; function soundex(input: unknown): string { const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); @@ -41,7 +53,8 @@ export class SelectQuery extends RuntimeSelectQuery { } export interface TeaQLDataService { - executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; preflightMutation(mutation: any): any; afterGraphCommit(work: () => void): void; afterGraphRollback(work: () => void): void; @@ -52,18 +65,24 @@ export interface TeaQLDataService { close?(): Promise; } -export class TeaQLClient implements TeaQLDataService { +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { private data: Record> = {}; private nextIds: Record = {}; private readonly checkers: Record = {}; + private readonly schemas: Record = {}; private userContext = new UserContext(); private graphSaveActive = false; + private activeGraph?: GraphMutationSession; private graphCommitActions: Array<() => void> = []; private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; private graphSaveTail: Promise = Promise.resolve(); private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; constructor(private storagePath?: string) { + super(); if (storagePath) { const fs = require("fs"); if (fs.existsSync(storagePath)) { @@ -76,10 +95,74 @@ export class TeaQLClient implements TeaQLDataService { /** Installs passive generated metadata. It never mutates storage. */ install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); return this; } + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + setUserContext(context: UserContext): this { this.userContext = context; return this; @@ -89,6 +172,33 @@ export class TeaQLClient implements TeaQLDataService { return [...this.mutationGovernanceEvents]; } + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + private persist() { if (!this.storagePath) return; const fs = require("fs"); @@ -99,8 +209,15 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } - async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } const predecessor = this.graphSaveTail; let release!: () => void; this.graphSaveTail = new Promise(resolve => { release = resolve; }); @@ -109,32 +226,57 @@ export class TeaQLClient implements TeaQLDataService { const nextIdsSnapshot = { ...this.nextIds }; let fixEvidenceStarted = false; let mutationPolicyGraphStarted = false; + let committed = false; try { + graph.validatePreparedSources(); this.graphSaveActive = true; + this.activeGraph = graph; this.graphCommitActions = []; this.graphRollbackActions = []; - this.userContext.insertResource("fixTime", new Date()); - this.userContext.beginFixEvidence(); - fixEvidenceStarted = true; - this.userContext.beginMutationPolicyGraph(); + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); const result = await work(graph); - this.userContext.ensureMutationPolicyGraphComplete(); - this.persist(); - for (const action of this.graphCommitActions) action(); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); return result; } catch (error) { - this.data = dataSnapshot; - this.nextIds = nextIdsSnapshot; - for (const action of [...this.graphRollbackActions].reverse()) action(); + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } throw error; } finally { this.graphSaveActive = false; + this.activeGraph = undefined; this.graphCommitActions = []; this.graphRollbackActions = []; - if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); - this.userContext.removeResource("fixTime"); - if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); release(); } } @@ -150,84 +292,145 @@ export class TeaQLClient implements TeaQLDataService { } preflightMutation(mutation: any): any { - mutation = this.checkAndFixMutation(mutation); - this.userContext.recordMutationPolicyPreflight(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); return mutation; } private checkAndFixMutation(mutation: any): any { - if (mutation instanceof MutationRequest) mutation = mutation.mutation; - if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; - const checker = this.checkers[String(mutation.entity)]; - if (!checker) return mutation; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } const results: any[] = []; const ownsFixTime = this.userContext.getResource("fixTime") === undefined; - if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); try { checker.checkAndFix(this.userContext, mutation, results); - if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); - this.userContext.translateCheckResults(results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); if (results.length) throw new CheckException(results); - return mutation; + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } } async executeMutation(mutation: any): Promise { - mutation = this.checkAndFixMutation(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); const mutationGovernance = this.userContext.enterMutationPolicy(mutation); - this.mutationGovernanceEvents.push(mutationGovernance); const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); if (mutation.action === "Create") { const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); - this.nextIds[mutation.entity] = Number(id) + 1; - const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; table[String(id)] = record; if (!this.graphSaveActive) this.persist(); - return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; - } - if (mutation.action === "Update") { - const id = String(mutation.id); - if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { - throw new Error( - `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); - } - table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; - if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); } - if (mutation.action === "Delete") { + if (["Update", "Delete", "Recover"].includes(mutation.action)) { const id = String(mutation.id); if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { throw new Error( `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); } - table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); } throw new Error(`Unsupported mutation action: ${mutation.action}`); } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } async query(context: any, req: any): Promise { return { rows: [] }; } async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; if (!(query instanceof RuntimeSelectQuery)) { throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); } query.prepareForList(); - let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); const matches = (row: any, expression: any): boolean => { if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { - if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); - if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); @@ -235,15 +438,17 @@ export class TeaQLClient implements TeaQLDataService { if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); - if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; - if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; - if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; - if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; - if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; return true; }); }; @@ -257,17 +462,19 @@ export class TeaQLClient implements TeaQLDataService { }))]; } for (const order of [...query.orderItems].reverse()) { - rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); } const start = query.offsetValue || 0; rows = rows.slice(start, start + query.limitValue); for (const relation of (query.relations || []) as any[]) { - const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); - const relatedRows = (await this.executeQuery(relation.query)).filter( - (row: any) => localValues.has(row[relation.foreignKey || "id"])); for (const row of rows) { - const matches = relatedRows.filter( - (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); row[relation.name] = relation.many === false ? matches[0] : matches; } } @@ -277,6 +484,8 @@ export class TeaQLClient implements TeaQLDataService { rows = rows.map((row: any) => Object.fromEntries( Object.entries(row).filter(([field]) => selections.has(field)))); } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); return rows; } async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { @@ -294,6 +503,7 @@ export class TeaQLClient implements TeaQLDataService { return value; } async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); const rows = await this.executeQuery(query); for (let offset = 0; offset < rows.length; offset += chunkSize) { diff --git a/source/teaql-ts/examples/browser-sqlite/package-lock.json b/source/teaql-ts/examples/browser-sqlite/package-lock.json index ef72c29e372820bf833e30eaa268e48c7e557440..fea0a44fbf7597c1dbc5fb596841015ea9dbf979 100644 --- a/source/teaql-ts/examples/browser-sqlite/package-lock.json +++ b/source/teaql-ts/examples/browser-sqlite/package-lock.json @@ -19,7 +19,7 @@ }, "../..": { "name": "@teaql/teaql", - "version": "0.3.1", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" @@ -43,7 +43,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -70,7 +70,7 @@ "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", diff --git a/source/teaql-ts/examples/browser-sqlite/scripts/orders-smoke.mjs b/source/teaql-ts/examples/browser-sqlite/scripts/orders-smoke.mjs index 3997d91a2915a2cd56c97b2dc2ed7666d65d9ef2..1b4f189f34461182dd450c29979fdb53dd102b4f 100644 --- a/source/teaql-ts/examples/browser-sqlite/scripts/orders-smoke.mjs +++ b/source/teaql-ts/examples/browser-sqlite/scripts/orders-smoke.mjs @@ -29,9 +29,14 @@ try { ? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' : '/usr/bin/google-chrome'), args: ['--no-sandbox', '--disable-dev-shm-usage'], headless: true}); - const page = await browser.newPage(), errors = []; + const page = await browser.newPage(), errors = [], rawMutationConsole = []; page.on('pageerror', error => errors.push(error.message)); - page.on('console', event => { if (event.type() === 'error') errors.push(event.text()); }); + page.on('console', event => { + if (event.type() === 'error') errors.push(event.text()); + // Mutation diagnostics are disabled above. A second SDK write tracer must + // not bypass TeaQL's policy-aware diagnostic channel. + if (/\b(?:INSERT INTO|UPDATE\s+.+\s+SET|DELETE FROM)\b/i.test(event.text())) rawMutationConsole.push(event.text()); + }); page.on('response', response => { if (response.status() >= 400) errors.push(`${response.status()} ${response.url()}`); }); page.on('requestfailed', request => errors.push(`${request.failure()?.errorText} ${request.url()}`)); async function waitReady(storage) { @@ -55,7 +60,7 @@ try { assert.deepEqual(order.items.map(item => [item.productName, item.quantity]), [['Box 1', 1], ['Box 2', 2], ['Box 3', 3]]); assert.equal(order.itemCount, 5); assert.deepEqual(response.facets.statusCounts.map(row => [String(row.id), row.orderCount, row.orderTotalAmount]), - [['1001', 1, 100], ['1002', 2, 500], ['1003', 0, null]]); + [['1001', 1, '100'], ['1002', 2, '500'], ['1003', 0, null]]); const evidence = JSON.parse(await page.$eval('#sql', element => element.textContent)); assert.equal(evidence.length, 8); const comments = evidence.map(entry => entry.traceChain.filter(node => node.kind === 'comment').map(node => node.detail)); @@ -109,6 +114,9 @@ try { assert.deepEqual(await inspect('opfs-reset', 8), baseline); assert.deepEqual(errors, []); checkLibrary(); if (process.env.TEAQL_BROWSER_ORDER_EVIDENCE) writeFileSync(process.env.TEAQL_BROWSER_ORDER_EVIDENCE, - JSON.stringify({receipts, generatedLibraryUnchanged: true, browserErrors: errors}, null, 2) + '\n', {flag: 'wx'}); + JSON.stringify({receipts, generatedLibraryUnchanged: true, browserErrors: errors, + rawMutationConsoleCount: rawMutationConsole.length}, null, 2) + '\n', {flag: 'wx'}); + console.log('BROWSER_RAW_SQL_OBSERVATION=' + JSON.stringify({rawMutationConsoleCount: rawMutationConsole.length})); + assert.equal(rawMutationConsole.length, 0, 'An ungoverned SQLite write tracer bypassed the runtime diagnostic policy'); console.log('PASS browser generated order TraceChain: memory/OPFS, refresh/reset, logging on/off, exact facets/counts/previews, actual SQL=8, unchanged generated library'); } finally { await browser?.close(); server.kill('SIGTERM'); } diff --git a/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs b/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs index 5d6a8b0fdf0fddc13342fa4a231567190664e825..60455a57879b0b33c21a3699410cc6c282ee3cbd 100644 --- a/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs +++ b/source/teaql-ts/examples/browser-sqlite/scripts/smoke.mjs @@ -79,6 +79,27 @@ try { || runtimeLanguages.links.some(language => !language.href.startsWith('https://github.com/teaql/'))) { throw new Error(`Seven-runtime selector is incomplete: ${JSON.stringify(runtimeLanguages)}`); } + const developmentProcess = await page.evaluate(() => ({ + title: document.querySelector('#development-process-title')?.textContent || '', + steps: [...document.querySelectorAll('.development-process-flow > li')].map(step => ({ + title: step.querySelector('strong')?.textContent || '', + code: step.querySelector('code')?.textContent || '', + })), + modelHref: document.querySelector('.source-link-primary')?.getAttribute('href') || '', + assistHref: document.querySelector('.development-process-links .source-link:not(.source-link-primary)')?.getAttribute('href') || '', + contextTitle: document.querySelector('.context-efficiency h3')?.textContent || '', + })); + if (developmentProcess.title !== 'From one domain model to executable evidence.' + || developmentProcess.steps.length !== 4 + || developmentProcess.steps.map(step => step.code).join('|') + !== 'order-model.xml|Q · E · Schema · Assist|comment · purpose · execute|Result · TraceChain · SQL' + || developmentProcess.modelHref + !== 'https://github.com/teaql/teaql-ts/blob/main/examples/browser-sqlite/order-model.xml' + || developmentProcess.assistHref + !== 'https://github.com/teaql/teaql-ts/tree/main/examples/browser-sqlite/assist' + || developmentProcess.contextTitle !== 'Spend context on the business change.') { + throw new Error(`Development process explanation is incomplete: ${JSON.stringify(developmentProcess)}`); + } const observabilityProof = await page.evaluate(() => { const image = document.querySelector('.observability-proof img'); return { @@ -373,6 +394,11 @@ try { title: document.querySelector('#query-browser-title')?.textContent || '', runtimeTitle: document.querySelector('#runtime-language-title')?.textContent || '', currentRuntime: document.querySelector('.runtime-language.active small')?.textContent || '', + developmentTitle: document.querySelector('#development-process-title')?.textContent || '', + modelLink: document.querySelector('.source-link-primary strong')?.textContent || '', + processSteps: [...document.querySelectorAll('.development-process-flow > li strong')] + .map(element => element.textContent || ''), + contextTitle: document.querySelector('.context-efficiency h3')?.textContent || '', observabilityTitle: document.querySelector('#observability-proof-title')?.textContent || '', observabilityCaption: document.querySelector('.observability-proof figcaption')?.textContent || '', evidenceTitle: document.querySelector('.sql-card-heading .query-card-label')?.textContent || '', @@ -383,6 +409,10 @@ try { if (chineseLocale.title !== '选择一个查询' || chineseLocale.runtimeTitle !== '这个演示在浏览器中运行 TypeScript。' || chineseLocale.currentRuntime !== '当前浏览器 runtime' + || chineseLocale.developmentTitle !== '从一份领域模型,到可以执行和审查的证据。' + || chineseLocale.modelLink !== '查看 order-model.xml' + || chineseLocale.processSteps.join('|') !== '建立领域模型|生成领域开发接口|构建一个有界的 Q 请求|运行并保留证据' + || chineseLocale.contextTitle !== '把上下文窗口留给真正的业务变更。' || chineseLocale.observabilityTitle !== 'OpenObserve 中的 TraceChain' || chineseLocale.observabilityCaption !== 'OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。' || chineseLocale.evidenceTitle !== '执行证据' diff --git a/source/teaql-ts/examples/browser-sqlite/src/main.ts b/source/teaql-ts/examples/browser-sqlite/src/main.ts index 8d925cf079d1f7ea48f6b3d190465fd11f419c83..2c3c2b8468563f299d41a9dfbe6a81e29d76d6ec 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/main.ts +++ b/source/teaql-ts/examples/browser-sqlite/src/main.ts @@ -70,6 +70,24 @@ const UI_COPY: Readonly> = { runtimeIntro: { en: 'The same model-driven Q and TraceChain contract is supported by seven TeaQL runtimes. Select a language to inspect its runtime source.', zh: '同一套模型驱动的 Q 与 TraceChain 契约支持七种 TeaQL runtime。选择一种语言,可以查看对应的 runtime 源码。' }, currentBrowserRuntime: { en: 'Current browser runtime', zh: '当前浏览器 runtime' }, supportedRuntime: { en: 'Supported runtime', zh: '已支持 runtime' }, + developmentProcess: { en: '00 / DEVELOPMENT PROCESS', zh: '00 / 开发过程' }, + developmentProcessTitle: { en: 'From one domain model to executable evidence.', zh: '从一份领域模型,到可以执行和审查的证据。' }, + developmentProcessIntro: { en: 'TeaQL keeps the business model small and readable, generates deterministic domain APIs, and carries request intent through the runtime to the SQL that actually ran.', zh: 'TeaQL 让业务模型保持精简、可读,从模型生成确定性的领域 API,并把请求意图一直带到 Runtime 实际执行的 SQL。' }, + modelSource: { en: 'MODEL SOURCE', zh: '模型源文件' }, + viewOrderModel: { en: 'View order-model.xml', zh: '查看 order-model.xml' }, + scopedGuidance: { en: 'SCOPED GUIDANCE', zh: '按需指导' }, + viewModelAssist: { en: 'View model-aware Assist', zh: '查看模型感知 Assist' }, + processModelTitle: { en: 'Model the domain', zh: '建立领域模型' }, + processModelBody: { en: 'Define entities, fields, relationships, constant objects, and constraints in one model file.', zh: '在一个模型文件中定义对象、字段、关系、常数对象和约束。' }, + processGenerateTitle: { en: 'Generate the working surface', zh: '生成领域开发接口' }, + processGenerateBody: { en: 'Generate typed Q and E APIs, schemas, audited mutations, and field-specific Assist from the model.', zh: '从模型生成强类型 Q 与 E API、Schema、可审计变更和字段级 Assist。' }, + processQueryTitle: { en: 'Build one bounded Q request', zh: '构建一个有界的 Q 请求' }, + processQueryBody: { en: 'Application code selects only what the page needs and attaches a readable comment and purpose.', zh: '应用代码只选择页面需要的内容,并附上可读的 comment 和 purpose。' }, + processEvidenceTitle: { en: 'Run and retain evidence', zh: '运行并保留证据' }, + processEvidenceBody: { en: 'The runtime enforces policy, executes SQLite/WASM, and retains a TraceChain from purpose and nested comments to timing and actual SQL.', zh: 'Runtime 执行策略和 SQLite/WASM,并保留从 purpose、嵌套 comment 到耗时和实际 SQL 的 TraceChain。' }, + contextEfficiency: { en: 'CONTEXT EFFICIENCY', zh: '上下文效率' }, + contextEfficiencyTitle: { en: 'Spend context on the business change.', zh: '把上下文窗口留给真正的业务变更。' }, + contextEfficiencyBody: { en: 'Instead of loading runtime internals and every generated file, an agent starts from the compact model and opens only the Assist for the current entity, action, or field. Typed domain operations compress provider details into a smaller working surface, reducing repeated context use while keeping behavior deterministic and reviewable.', zh: 'Agent 不需要加载 Runtime 内部实现和所有生成文件,而是从精简模型出发,只打开当前对象、动作或字段所需的 Assist。强类型领域操作把数据库和 Provider 细节压缩成更小的工作界面,减少重复占用上下文,同时保持行为确定、可审查。' }, observabilityTitle: { en: 'TraceChain in OpenObserve', zh: 'OpenObserve 中的 TraceChain' }, observabilityIntro: { en: 'A captured Order query rendered as business lineage: page purpose, nested request comments, and the actual SQL executions remain connected.', zh: '一条真实采集的订单查询被呈现为业务谱系:页面目的、嵌套 request 的 comment 与实际执行的 SQL 始终保持连接。' }, observabilityCaption: { en: 'OpenObserve dashboard showing one verified trace and its eight actual SQL executions.', zh: 'OpenObserve 仪表盘展示一条已验证的 trace,以及它实际执行的八条 SQL。' }, @@ -475,7 +493,7 @@ const QUERY_GROUPS: readonly QueryGroup[] = [ code: `const input = { "filter": { "currency": "CNY", - "totalAmount": { "$gte": 250 }, + "totalAmount": { "$gte": "250" }, "status": { "$in": ["PAID", "SHIPPED"] } }, "orderBy": [{ "field": "totalAmount", "direction": "desc" }] @@ -489,7 +507,7 @@ const data = await Q.customerOrders() run: active => dynamicOrderQuery(active, { filter: { currency: 'CNY', - totalAmount: { $gte: 250 }, + totalAmount: { $gte: '250' }, status: { $in: ['PAID', 'SHIPPED'] }, }, orderBy: [{ field: 'totalAmount', direction: 'desc' }], @@ -590,7 +608,13 @@ async function seedDemoData(active: Runtime): Promise { entity: record.entity, action: 'Create', id: record.id, - payload: record.payload, + // The fixture uses native JS member names; the mutation boundary uses + // model names from trusted metadata, never a guessed casing conversion. + payload: Object.fromEntries(Object.entries(record.payload).map(([field, value]) => { + const column = ORDER_SCHEMAS[record.entity]?.columns[field]; + if (!column) throw new Error(`Unknown fixture field ${record.entity}.${field}`); + return [column.modelName ?? field, value]; + })), })); for (const request of requests) active.client.preflightMutation(request); for (const request of requests) await active.client.executeMutation(request); diff --git a/source/teaql-ts/examples/browser-sqlite/src/orders.ts b/source/teaql-ts/examples/browser-sqlite/src/orders.ts index 604aa4f49559e4e0e803d9281a9f669eccebb871..050ee18bdd846bdcc0dc33ce1d8da024962a1518 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/orders.ts +++ b/source/teaql-ts/examples/browser-sqlite/src/orders.ts @@ -1,5 +1,5 @@ import { BrowserSQLiteTeaQLClient, type BrowserSQLiteStorage } from 'teaql-ts/sql/browser-sqlite'; -import { DelegatingMutationPolicyApprovalProvider, DelegatingMutationPolicyRegistry, UserContext } from 'teaql-ts'; +import { DelegatingMutationPolicyApprovalProvider, DelegatingMutationPolicyRegistry, UserContext, decimal } from 'teaql-ts'; import { SQLExecutionEvidenceStore, type SQLExecutionMetadata } from 'teaql-ts/sql/core'; import { Q } from '../orders-lib/src/generated/Q'; import { E } from '../orders-lib/src/generated/E'; @@ -50,18 +50,18 @@ async function seed({context}: Runtime): Promise { .comment('detect existing order demo').purpose('keep mutation seeding idempotent').executeForList(context); if (existing.length) return; const platform = (await Q.platforms().limit(2).comment('load bootstrap platform').purpose('prepare order demo').executeForList(context))[0]; - const customer = Q.customers().comment('initialize demo customer').purpose('prepare order demo').newEntity(context); + const customer = (await Q.customers().comment('initialize demo customer').purpose('prepare order demo').newEntity(context)); customer.updateName('North Star Retail').updatePlatform(platform.id); await customer.auditAs('seed browser order customer').save(context); for (let index = 1; index <= 4; index++) { - const order = Q.customerOrders().comment('initialize demo order').purpose('prepare order demo').newEntity(context); + const order = (await Q.customerOrders().comment('initialize demo order').purpose('prepare order demo').newEntity(context)); order.updateCustomer(customer.id).updateOrderNumber(index < 4 ? `KEEP-00${index}` : 'DROP-004') - .updateOrderDate(`2026-10-0${index}`).updateTotalAmount(index < 4 ? index * 100 : 900); + .updateOrderDate(`2026-10-0${index}`).updateTotalAmount(decimal(String(index < 4 ? index * 100 : 900))); if (index === 1) order.updateStatusToNew(); else order.updateStatusToPaid(); await order.auditAs('seed browser order').save(context); for (let item = 1; item <= 5; item++) { - const line = Q.orderItems().comment('initialize demo item').purpose('prepare item previews').newEntity(context); - line.updateCustomerOrder(order.id).updateProductName(`Box ${item}`).updateQuantity(item).updateUnitPrice(20); + const line = (await Q.orderItems().comment('initialize demo item').purpose('prepare item previews').newEntity(context)); + line.updateCustomerOrder(order.id).updateProductName(`Box ${item}`).updateQuantity(item).updateUnitPrice(decimal('20')); await line.auditAs('seed browser order item').save(context); } } diff --git a/source/teaql-ts/examples/browser-sqlite/src/style.css b/source/teaql-ts/examples/browser-sqlite/src/style.css index fff9f4626bae2b776d391fe0a9497ade1fb20276..e848e8e7c72b8f017bb029e00788d8d76b3f3c1d 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/style.css +++ b/source/teaql-ts/examples/browser-sqlite/src/style.css @@ -159,6 +159,82 @@ h1 { .runtime-language small { color: #78837a; font-size: 8px; line-height: 1.25; } .runtime-language.active small { color: #d5e7da; } +.development-process { + margin: 54px 0 28px; + padding: 42px; + border: 1px solid var(--line); + border-radius: 24px; + background: var(--paper); + box-shadow: 0 18px 48px rgba(33, 60, 40, .05); +} +.development-process-heading { + display: grid; + grid-template-columns: minmax(280px, .9fr) minmax(0, 1.1fr); + align-items: end; + gap: 48px; +} +.development-process-heading h2 { + margin: 0; + font-family: Georgia, "Noto Serif SC", serif; + font-size: clamp(30px, 3.5vw, 48px); + font-weight: 500; + line-height: 1.08; + letter-spacing: -.04em; +} +.development-process-intro > p { margin: 0; color: var(--muted); font-size: 16px; line-height: 1.7; } +.development-process-links { margin-top: 22px; display: flex; flex-wrap: wrap; gap: 10px; } +.source-link { + min-width: 210px; + padding: 12px 15px; + display: grid; + gap: 3px; + border: 1px solid #cad3c9; + border-radius: 10px; + color: var(--ink); + background: #f8faf5; + text-decoration: none; + transition: border-color .16s ease, background .16s ease, transform .16s ease; +} +.source-link:hover, .source-link:focus-visible { border-color: #819586; background: white; outline: none; transform: translateY(-1px); } +.source-link-primary { color: white; border-color: var(--green); background: var(--green); } +.source-link-primary:hover, .source-link-primary:focus-visible { border-color: var(--green-deep); background: var(--green-deep); } +.source-link span { color: #77847a; font-size: 10px; font-weight: 850; letter-spacing: .13em; } +.source-link-primary span { color: #c8dccd; } +.source-link strong { font-size: 14px; line-height: 1.35; } + +.development-process-flow { + margin: 38px 0 0; + padding: 0; + display: grid; + grid-template-columns: repeat(4, minmax(0, 1fr)); + border: 1px solid #d7ddd3; + border-radius: 16px; + background: #f8faf5; + list-style: none; + overflow: hidden; +} +.development-process-flow li { min-width: 0; padding: 22px; border-left: 1px solid #d7ddd3; } +.development-process-flow li:first-child { border-left: 0; } +.development-step { display: block; margin-bottom: 20px; color: var(--orange); font: 800 12px/1 ui-monospace, SFMono-Regular, Menlo, monospace; } +.development-process-flow strong { display: block; min-height: 48px; font-size: 16px; line-height: 1.45; } +.development-process-flow p { min-height: 92px; margin: 10px 0 18px; color: var(--muted); font-size: 14px; line-height: 1.6; } +.development-process-flow code { color: var(--green); font: 650 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; } + +.context-efficiency { + margin-top: 18px; + padding: 24px; + display: grid; + grid-template-columns: minmax(230px, .72fr) minmax(0, 1.28fr); + align-items: center; + gap: 34px; + border-radius: 14px; + color: #edf7ef; + background: var(--green-deep); +} +.context-efficiency .section-index { margin-bottom: 8px; color: var(--lime); } +.context-efficiency h3 { margin: 0; font: 500 24px/1.2 Georgia, "Noto Serif SC", serif; letter-spacing: -.025em; } +.context-efficiency > p { margin: 0; color: #c7d8cc; font-size: 15px; line-height: 1.7; } + .runtime-bar { min-height: 72px; padding: 14px 18px 14px 22px; @@ -484,6 +560,10 @@ footer { .model-map { min-height: 260px; } .runtime-language-panel { grid-template-columns: 1fr; } .runtime-language-selector { grid-template-columns: repeat(4, minmax(100px, 1fr)); } + .development-process-heading { grid-template-columns: 1fr; align-items: start; gap: 24px; } + .development-process-flow { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .development-process-flow li:nth-child(3) { border-left: 0; border-top: 1px solid #d7ddd3; } + .development-process-flow li:nth-child(4) { border-top: 1px solid #d7ddd3; } .result-panel { margin: 0 -24px; padding-left: 24px; padding-right: 24px; } .result-grid { grid-template-columns: 1fr; } .observability-proof-heading { grid-template-columns: 1fr; align-items: start; gap: 14px; } @@ -505,6 +585,16 @@ footer { .runtime-language-panel { padding: 20px 16px; gap: 20px; } .runtime-language-selector { grid-template-columns: repeat(2, minmax(0, 1fr)); } .runtime-language:last-child { grid-column: 1 / -1; } + .development-process { margin-top: 38px; padding: 26px 18px; } + .development-process-intro > p { font-size: 15px; } + .development-process-links { align-items: stretch; flex-direction: column; } + .source-link { min-width: 0; width: 100%; } + .development-process-flow { grid-template-columns: 1fr; } + .development-process-flow li { border-top: 1px solid #d7ddd3; border-left: 0; } + .development-process-flow li:first-child { border-top: 0; } + .development-process-flow li:nth-child(3), .development-process-flow li:nth-child(4) { border-left: 0; } + .development-process-flow strong, .development-process-flow p { min-height: 0; } + .context-efficiency { grid-template-columns: 1fr; gap: 16px; padding: 20px; } .runtime-bar, .section-heading, .result-heading { align-items: flex-start; flex-direction: column; } .runtime-bar { padding: 18px; } .controls { width: 100%; justify-content: space-between; } diff --git a/source/teaql-ts/examples/browser-sqlite/src/work-items.ts b/source/teaql-ts/examples/browser-sqlite/src/work-items.ts index 880284ff79723227e8c53c2b9acc85c7f823e393..83b4d252bdb3501b6db7c22144e6504e17e2549e 100644 --- a/source/teaql-ts/examples/browser-sqlite/src/work-items.ts +++ b/source/teaql-ts/examples/browser-sqlite/src/work-items.ts @@ -8,7 +8,6 @@ import { UserContext, } from 'teaql-ts'; import { Q } from '../../conformance/src/generated/Q'; -import { WorkItem } from '../../conformance/src/generated/models/WorkItem'; import { GENERATED_RUNTIME_MODULE } from '../../conformance/src/runtime-module'; import { ENTITY_SCHEMAS } from '../../conformance/src/teaql-node-sql'; import './work-items.css'; @@ -58,7 +57,8 @@ async function seedDemoData({ context }: Runtime): Promise { .executeForList(context); if (existing.length) return; for (const title of ['Evaluate semantic model', 'Generate typed library', 'Verify browser runtime']) { - await new WorkItem() + await (await Q.workItems().comment('reserve one browser demo work item') + .purpose('seed deterministic data through managed creation').newEntity(context)) .updateTitle(title) .updatePlatform('1') .auditAs('seed deterministic browser demo data') diff --git a/source/teaql-ts/examples/conformance/README.md b/source/teaql-ts/examples/conformance/README.md index a007f6c3ab88a3082cec8a4bc5859f7b8e56a111..bb1e6f3c4d030dd805f6fa765742e2b70e1f16c1 100644 --- a/source/teaql-ts/examples/conformance/README.md +++ b/source/teaql-ts/examples/conformance/README.md @@ -8,4 +8,15 @@ npm run build npm start ``` -The generated workspace targets `@teaql/teaql` 0.1.17. Regenerate it with the local code generator's `typescript-app-console` target before checking a new generator/runtime combination. +The example's `file:../..` dependency uses this repository's local runtime, not +an old public package. Generated model inputs retain their evaluated manifest; +this example does not hand-edit generated implementations. + +`operational-clock-verification.ts` additionally checks real LocalCache TTL +expiry with a positively calibrated, then unavailable Business Clock. Moving +the business calendar forwards/backwards cannot expire or revive entries; +zero/false/empty/null values and zero/omitted TTL retain their existing meaning. +The emitted `TYPESCRIPT_OPERATIONAL_CLOCK_EXAMPLE` contains no cached values. +Companion native tests cover local pagination-state TTLs and telemetry deadlines. +These tests do not add security-reference or local-lock APIs, which are outside +this runtime's current frontend-oriented scope. diff --git a/source/teaql-ts/examples/conformance/assist/create/work_item.md b/source/teaql-ts/examples/conformance/assist/create/work_item.md new file mode 100644 index 0000000000000000000000000000000000000000..f9a186191e0faa87bb01a2ff319db775f852c1b3 --- /dev/null +++ b/source/teaql-ts/examples/conformance/assist/create/work_item.md @@ -0,0 +1,87 @@ + + +# TypeScript Assist — Create `Work Item` + +Use the exact generated `Q.workItems()` entry point. The +trusted `UserContext` supplies actor, tenant, policy, provider, and audit sink; +none of those values may be accepted from the writable input. + +```typescript +import { Decimal, UserContext, decimal } from '../teaql-ts'; +import { Q } from './Q'; +import { WorkItem } from './models/WorkItem'; + +export interface CreateWorkItemInput { + title: string; + description: string; + platform: string | number; + +} + +export async function createWorkItem( + input: CreateWorkItemInput, + context: UserContext, +): Promise { + const entity = await Q.workItems() + .comment('what: initialize Work Item') + .purpose('why: create Work Item') + .newEntity(context); + + entity.updateTitle(input.title); + entity.updateDescription(input.description); + entity.updatePlatform(input.platform); + + await entity + .auditAs('Create Work Item for the requested business operation') + .save(context); + return entity; +} +``` + +Only the generated updater methods above are writable. Constant relation +candidates, when present, are also generated and must be copied exactly: + +For Decimal fields, construct exact values with `decimal('3.50')`. Do not pass a +JavaScript `number`, which can lose digits before the runtime sees it. + +Compile the result unchanged. Test persistence and query-back, and prove that +blank/missing intent, blank/missing audit reason, unknown fields, and attempted +trusted-context overrides fail. Do not edit generated sources. + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `create`. + +- Validate and allow-list writable business fields; never mass-assign dynamic JSON. +- Create through the generated request/entity API, attach a non-empty audit reason, + save with the same UserContext, and return the runtime's native save result. +- Add a negative test proving a missing audit reason cannot write. diff --git a/source/teaql-ts/examples/conformance/assist/query/work_item.md b/source/teaql-ts/examples/conformance/assist/query/work_item.md new file mode 100644 index 0000000000000000000000000000000000000000..2a07abb1d6c0fded89499bdf458623cf2afa6429 --- /dev/null +++ b/source/teaql-ts/examples/conformance/assist/query/work_item.md @@ -0,0 +1,107 @@ + + +# TypeScript Assist — Query `Work Item` + +Use the exact generated `Q.workItemsWithMinimalFields()` +entry point. Trusted runtime and policy state comes only from `UserContext`. + +```typescript +import { Q } from './Q'; +import { WorkItem } from './models/WorkItem'; +import { SmartList, UserContext } from '../teaql-ts'; + +export async function queryWorkItemById( + context: UserContext, + entityId: string, +): Promise> { + return Q.workItemsWithMinimalFields() + .withIdIs(entityId) + .orderByIdAscending() + .limit(20) + .comment('what: load the requested Work Item row') + .purpose('why: serve the authorized Work Item view') + .executeForList(context); +} +``` + +Compile and execute this source unchanged. Use only generated projection, +predicate, ordering, and relation-selection APIs. Missing or blank intent, +unknown fields, unbounded reads, and trusted-context inputs must fail. Use generated +relation loading rather than handwritten child-query loops; never guess a plural. + +## Facet results + +Configure the target request with `countAs(alias)` to expose the outer membership +count under that alias, then pass it to the field-specific `facetBy...As` API. +Facet target requests can themselves declare Facets. Read the returned +`SmartList.facets[name]`; each Facet is another SmartList, with nested Facets in +its own `facets`. Narrow count aliases from unknown to number; missing is not zero. +`includeAllFacets` includes target candidates with zero membership. Membership +counts use the active filter, not the visible page's offset or limit. + + + +## Field-specific Query Assist + +Use the canonical KSML field name from this list. Do not substitute a language member name, JSON name, or database column. + +| KSML field | Type | Field help | +| --- | --- | --- | +| `id` | `id` | `typescript-assist-query/work_item.id` | +| `title` | `string` | `typescript-assist-query/work_item.title` | +| `description` | `string` | `typescript-assist-query/work_item.description` | +| `platform` | `relation` | `typescript-assist-query/work_item.platform` | +| `version` | `version` | `typescript-assist-query/work_item.version` | + + +--- + +## TeaQL seven-language assist contract + +Apply the verified Rust semantic ceiling while using only the exact TYPESCRIPT generated and +runtime APIs. Discover APIs through the generated application AGENTS.md and progressive +model-aware Assist. Do not inspect generated domain-library source. + +- Do not create plurals by appending `s` or `es`; use the centralized generated plural. +- Human and non-human entities use different generated predicate vocabularies. Preserve + forms such as “who are active” and “whose email is”; never infer them from English. +- Configure filters, projection, paging, and other query options before `purpose(...)`. + Comment may appear anywhere in the chain. Purpose enters the executable stage; execution + requires both values, but comment does not have to immediately precede purpose. +- Every execute/list/stream and every save accepts exactly one context argument: + `UserContext`. Name that argument `context`, never `runtime`; data services and global + policy are injected when the context is built. Reserve `runtime` for process-level + runtime ownership, provider/pool setup, and module assembly. +- Tenant, merchant, identity, permissions, request policy, purpose policy, hard limit, + and continuous-page cursor policy come only from trusted context, never dynamic JSON or TFP. +- If the required operation is absent after current entity/action and required field + Assist, stop that path and report MISSING_ASSIST. Do not guess an API or search the + generated library as a fallback. +- Create each application-owned source file once. After its first compile attempt, + repair only the smallest block identified by the exact compiler or test diagnostic. + Preserve unrelated code; do not rewrite the complete file as an error-recovery loop. +- Before a repair that would replace more than 25% of an existing application file, + stop and report LARGE_REWRITE_REQUEST with the file, exact diagnostic, reason, and + estimated scope. Initial creation and model-driven regeneration are not repairs. + +Capability: `query`. + +- Use generated projection, relation, predicate, sort, and aggregate APIs; never + concatenate application SQL or silently ignore an unsupported filter. +- Rows, record count, facets, and aggregates must share the same active filter. +- Add negative tests for missing purpose/comment and forbidden dynamic fields. + +### Optional per-parent Top-N optimization + +- Configure `topNProbeParentThreshold(threshold)` on the nested child request before its intent/execution + stage. Use the field-specific relation Assist for the exact generated selector. +- Give the child a per-parent limit and deterministic ordering with an ID tie-breaker; + bound the parent query separately. A single-parent detail query is not batch Top-N. +- Server providers default to a window query (`threshold = 0`). A positive threshold + permits bounded probes only when the already-loaded parent count is at or below it; + above it, use the window plan. SQLite uses its internal AlwaysProbe policy by default. +- Measure before opting in. Do not infer a threshold from table size or execute COUNT + or statistics queries to choose a plan. Keep an index on foreign key + sort + ID. +- Inspect selected-plan, parent-count, per-parent-limit and probe-count telemetry. + Runtime-managed probes are not application-owned N+1 loops; neither strategy changes + authorization, loaded-state semantics or the required comment/purpose. diff --git a/source/teaql-ts/examples/conformance/current-generator-fixture.json b/source/teaql-ts/examples/conformance/current-generator-fixture.json new file mode 100644 index 0000000000000000000000000000000000000000..f7083dccce31c379b3698f94443c76d49a116150 --- /dev/null +++ b/source/teaql-ts/examples/conformance/current-generator-fixture.json @@ -0,0 +1,30 @@ +{ + "schema": "teaql.typescript-current-example-fixture/v1", + "modelSha256": "0a59f66db2487fdd0430087dd5985ae780225c088ad800679cb57c593c6bcee7", + "scope": "typescript-lib-core", + "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "files": { + "src/generated/Q.ts": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "src/generated/requests/PlatformRequest.ts": "9a6c8e75b393b977c6b53517f222104e67b1ea0c8dfba773f2fd770f22b124db", + "src/generated/requests/WorkItemRequest.ts": "8c2d20df65964c9a0ab1775fbb3c482fa54e7634032f34828c231e1954f2bd82", + "src/generated/E.ts": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "src/teaql-schemas.ts": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "src/runtime-module.ts": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "src/generated-bootstrap.ts": "10a1133555d160947deb5c2a2756cc28162ff7e75627aeb77029be345ad523e7", + "src/generated/models/Platform.ts": "edfcd2aa09444125e319036c2dd223b1c254bcd4b2047f7c25a5f9c30cd9c877", + "src/generated/models/WorkItem.ts": "d921e1a9eda92d6feb4ecae49beb14db642be0cc25c624aa103b5a33a7254066" + }, + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousFixtureManifestSha256": "078e2d9af5e933d5806d219b00e06ef3a346ac05137e05aaf33f70269a738afb", + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } +} diff --git a/source/teaql-ts/examples/conformance/managed-construction.test.ts b/source/teaql-ts/examples/conformance/managed-construction.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..75ce397ffa36bcebf7494f19159972113dfbf120 --- /dev/null +++ b/source/teaql-ts/examples/conformance/managed-construction.test.ts @@ -0,0 +1,50 @@ +import {UserContext} from 'teaql-ts'; +import {WorkItem} from './src/generated/models/WorkItem'; +import {Q} from './src/generated/Q'; + +const creation = (context: UserContext) => Q.workItems().comment('reserve a work item').purpose('verify creation boundary').newEntity(context); + +test('bare JavaScript construction cannot create an insert candidate', () => { + expect(() => Reflect.construct(WorkItem, [])).toThrow(); +}); + +test('awaited allocator validates exact IDs, propagates failure and recovers without fallback or shared ledgers', async () => { + const failure = new Error('allocator offline'); let step = 0; + const values = ['701', failure, '0', '9223372036854775808', '702']; + const context = new UserContext().withInternalIdGenerator({generateId: async (entity, actual) => { + expect(entity).toBe('WorkItem'); expect(actual).toBe(context); + const value = values[step++]; if (value instanceof Error) throw value; return value; + }}); + const first = await creation(context); expect(first.id).toBe('701'); + await expect(creation(context)).rejects.toBe(failure); + await expect(creation(context)).rejects.toThrow(); + await expect(creation(context)).rejects.toThrow(); + const second = await creation(context); expect(second.id).toBe('702'); expect(step).toBe(5); + first.updateTitle('first only'); expect(second.title).not.toBe('first only'); + expect((first as any)._root).not.toBe((second as any)._root); +}); + +test('hydrated complete record is a read view with no insert intent', () => { + const read = WorkItem.fromRecord({id: '77', version: 3, title: 'loaded', description: null, platform: '1'}); + expect((read as any)._action).toBe('Update'); + expect((read as any)._root.isNew((read as any).teaqlEntityKey())).toBe(false); + expect(JSON.stringify(read)).not.toContain('creationBaseline'); +}); + +test('writing the current version cannot forge missing persisted provenance and fails before provider or clock', async () => { + let callbacks = 0; + const context = new UserContext().withBusinessClock({now: () => {callbacks++; throw new Error('clock must not run');}}); + const read = WorkItem.fromRecord({id: '77', title: 'loaded', description: null, platform: '1'}); + read.updateTitle('changed'); read.updateVersion(1); + await expect(read.auditAs('reject versionless write').save(context)).rejects.toHaveProperty('code', 'ENTITY_CREATION_CONTEXT_REQUIRED'); + expect(callbacks).toBe(0); +}); + +test('unchanged empty hydration is inert without a provider or allocator', async () => { + const read = WorkItem.fromRecord({}); + await expect(read.auditAs('save inert read view').save(new UserContext())).resolves.toBe(read); +}); + +test('fixed bootstrap IDs cannot be minted outside Context schema execution', () => { + expect(() => (WorkItem as any).teaqlBootstrapNew('701')).toThrow(); +}); diff --git a/source/teaql-ts/examples/conformance/managed-sqlite.test.ts b/source/teaql-ts/examples/conformance/managed-sqlite.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..3928b00e1e3b291f3cd81e7b198db21b45365b9a --- /dev/null +++ b/source/teaql-ts/examples/conformance/managed-sqlite.test.ts @@ -0,0 +1,83 @@ +import {CheckException, UserContext} from 'teaql-ts'; +import {Q} from './src/generated/Q'; +import {E} from './src/generated/E'; +import {WorkItem} from './src/generated/models/WorkItem'; +import {SQLiteTeaQLClient} from './src/teaql-node-sqlite'; + +let context: UserContext, client: SQLiteTeaQLClient; +const create = () => Q.workItems().comment('reserve managed work item').purpose('verify SQLite creation boundary').newEntity(context); +const load = (id: string) => Q.workItems().withIdIs(id).limit(1).comment('read managed work item').purpose('verify persisted identity and values').executeForOne(context); +beforeAll(async () => { + if (!process.env.TEAQL_MANAGED_DATABASE) throw new Error('Retained database path required'); + client = new SQLiteTeaQLClient(process.env.TEAQL_MANAGED_DATABASE); + context = new UserContext().insertResource('dataService', client); client.setUserContext(context); + await context.ensureSchema(); +}); +afterAll(async () => {await client?.close();}); + +test('repeated Context schema reconciliation reuses the same single root', async () => { + await context.ensureSchema(); + const roots = await Q.platforms().limit(10).comment('inspect bootstrap roots').purpose('verify idempotent schema seed').executeForList(context); + expect(roots.length).toBe(1);expect(roots[0].id).toBe('1'); +}); + +test('reserve before return, save exactly that ID, and query through Q and E', async () => { + const allocation=jest.spyOn((client as any).driver,'nextId'); + try { + const entity=await create(), id=entity.id!;expect(allocation).toHaveBeenCalledTimes(1);expect(await load(id)).toBeUndefined(); + entity.updateTitle('managed persisted').updatePlatform('1'); + await entity.auditAs('persist already reserved ID').save(context); + expect(entity.id).toBe(id);expect(entity.version).toBe(1);expect(allocation).toHaveBeenCalledTimes(1); + const loaded=await load(id);expect(loaded).toBeDefined();expect(E.workItem(loaded!).title().eval()).toBe('managed persisted'); + } finally {allocation.mockRestore();} +}); + +test('business Checker rejects missing title before mutation SQL', async () => { + const entity=await create();entity.updatePlatform('1');const before=client.sqlTrace.length; + await expect(entity.auditAs('reject missing business title').save(context)).rejects.toBeInstanceOf(CheckException); + expect(client.sqlTrace.length).toBe(before);expect(await load(entity.id!)).toBeUndefined(); +}); + +test('complete hydrated update advances persisted original version', async () => { + const entity=await create();await entity.updateTitle('before update').updatePlatform('1').auditAs('create update fixture').save(context); + const loaded=(await load(entity.id!))!;await loaded.updateTitle('after update').auditAs('update hydrated row').save(context); + const actual=(await load(entity.id!))!;expect(actual.version).toBe(2);expect(E.workItem(actual).title().eval()).toBe('after update'); +}); + +test('unchanged sparse read is inert but a modified sparse read is rejected', async () => { + const entity=await create();await entity.updateTitle('sparse original').updatePlatform('1').auditAs('create sparse fixture').save(context); + const read=WorkItem.fromRecord({id:entity.id,version:1}),before=client.sqlTrace.length; + await expect(read.auditAs('inert sparse read').save(context)).resolves.toBe(read);expect(client.sqlTrace.length).toBe(before); + await expect(read.updateTitle('invalid partial').auditAs('reject partial write').save(context)).rejects.toBeInstanceOf(CheckException); + expect(client.sqlTrace.length).toBe(before);expect(E.workItem((await load(entity.id!))!).title().eval()).toBe('sparse original'); +}); + +test('missing persisted version rejects before provider transaction, clock or Fix', async () => { + const entity=await create();await entity.updateTitle('version original').updatePlatform('1').auditAs('create version fixture').save(context); + const read=WorkItem.fromRecord({id:entity.id,title:'version original',description:null,platform:'1'}); + const execute=jest.spyOn(client,'executeGraphSave'),before=client.sqlTrace.length; + try { + read.updateTitle('forged update').updateVersion(1); + await expect(read.auditAs('reject missing persisted version').save(context)).rejects.toHaveProperty('code','ENTITY_CREATION_CONTEXT_REQUIRED'); + expect(execute).not.toHaveBeenCalled();expect(client.sqlTrace.length).toBe(before); + } finally {execute.mockRestore();} +}); + +test('transaction rollback retains reservation and retry does not allocate again', async () => { + const entity=await create(),id=entity.id!;entity.updateTitle('rollback retry').updatePlatform('1'); + const allocation=jest.spyOn((client as any).driver,'nextId'),failure=new Error('test-only after-write failure'); + const real=client.executeMutation.bind(client),execute=jest.spyOn(client,'executeMutation'); + execute.mockImplementationOnce(async request=>{await real(request);throw failure;}); + try { + await expect(entity.auditAs('rollback business write').save(context)).rejects.toBe(failure); + expect(entity.id).toBe(id);expect(entity.version).toBeUndefined();expect(await load(id)).toBeUndefined(); + execute.mockRestore();await entity.auditAs('retry original reservation').save(context); + expect(entity.id).toBe(id);expect(entity.version).toBe(1);expect(allocation).not.toHaveBeenCalled();expect((await load(id))!.title).toBe('rollback retry'); + } finally {execute.mockRestore();allocation.mockRestore();} +}); + +test('saving one independent graph never saves its sibling in the same Context', async () => { + const first=await create(),second=await create();first.updateTitle('only saved').updatePlatform('1');second.updateTitle('still pending').updatePlatform('1'); + await first.auditAs('save only selected graph').save(context);expect(await load(first.id!)).toBeDefined();expect(await load(second.id!)).toBeUndefined(); + expect(second.version).toBeUndefined();expect((second as any)._root.hasPending({entity:'WorkItem',id:second.id!})).toBe(true); +}); diff --git a/source/teaql-ts/examples/conformance/package-lock.json b/source/teaql-ts/examples/conformance/package-lock.json index cfdb768821331f7cfbd96eec8faa2058b32e7c52..fcb3e97215d08afcc0e5c0f9024c45f4f3c84133 100644 --- a/source/teaql-ts/examples/conformance/package-lock.json +++ b/source/teaql-ts/examples/conformance/package-lock.json @@ -8,7 +8,7 @@ "name": "runtime-example-conformance-service-lib", "version": "1.0.0", "dependencies": { - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../.." }, "devDependencies": { @@ -16,11 +16,14 @@ "@types/node": "^22.0.0", "ts-node": "^10.9.2", "typescript": "^5.0.0" + }, + "engines": { + "node": ">=22" } }, "../..": { "name": "@teaql/teaql", - "version": "0.3.1", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" @@ -44,7 +47,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -71,7 +74,7 @@ "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", @@ -262,90 +265,19 @@ "dev": true, "license": "MIT" }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/better-sqlite3": { - "version": "12.11.1", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", - "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "bindings": "^1.5.0", - "prebuild-install": "^7.1.1" + "node-addon-api": "^8.0.0" }, "engines": { - "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" - } - }, - "node_modules/bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "license": "MIT", - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" + "node": ">=22" } }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", @@ -353,39 +285,6 @@ "dev": true, "license": "MIT" }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, "node_modules/diff": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", @@ -396,74 +295,6 @@ "node": ">=0.3.1" } }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "license": "MIT" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", @@ -471,247 +302,13 @@ "dev": true, "license": "ISC" }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.95.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.95.0.tgz", - "integrity": "sha512-T9iGctuocf0qIWFFOTxPzjT5q0SILqaBYXt272tlBHvTKC5+3JnkMirLxNJNkXHtFyBjU2Jx+NL4Zipr0B/c6Q==", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", - "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", - "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, - "engines": { - "node": ">=6" + "node": "^18 || ^20 || >= 21" } }, "node_modules/teaql-ts": { @@ -762,18 +359,6 @@ } } }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", @@ -795,12 +380,6 @@ "dev": true, "license": "MIT" }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", @@ -808,12 +387,6 @@ "dev": true, "license": "MIT" }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", diff --git a/source/teaql-ts/examples/conformance/package.json b/source/teaql-ts/examples/conformance/package.json index b77d589c5d8684c8d47cd5bb39828ce97352aeed..09cce57bceb20c060737657f2897b0bda76429cc 100644 --- a/source/teaql-ts/examples/conformance/package.json +++ b/source/teaql-ts/examples/conformance/package.json @@ -5,11 +5,13 @@ "main": "src/generated/Q.ts", "scripts": { "build": "tsc --noEmit", - "start": "ts-node src/main.ts" + "start": "ts-node src/main.ts", + "test:managed": "node verify-managed.cjs" }, "dependencies": { "teaql-ts": "file:../..", - "better-sqlite3": "^12.10.0"}, + "better-sqlite3": "^13.0.3"}, + "engines": { "node": ">=22" }, "devDependencies": { "typescript": "^5.0.0", "ts-node": "^10.9.2", diff --git a/source/teaql-ts/examples/conformance/src/fix-owner-verification.ts b/source/teaql-ts/examples/conformance/src/fix-owner-verification.ts new file mode 100644 index 0000000000000000000000000000000000000000..2a18320a2818175551edcf936c3ba1f152a259c5 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/fix-owner-verification.ts @@ -0,0 +1,41 @@ +import assert from 'node:assert/strict'; +import {UserContext, MutationIntent} from 'teaql-ts'; +import {AbstractSQLTeaQLClient} from 'teaql-ts/sql/core'; +import {SQLiteDriver} from 'teaql-ts/sql/sqlite'; + +/** A refused second owner must not change the admitted graph's Context state. */ +export async function verifyFixOwnerAdmission() { + class Client extends AbstractSQLTeaQLClient { + constructor() {super(new SQLiteDriver(':memory:'), {});} + } + let tick = 1000, release!: () => void, entered!: () => void; + const context = new UserContext().withBusinessClock({now: () => new Date(tick++)}); + const first = new Client().setUserContext(context), second = new Client().setUserContext(context); + const ready = new Promise(resolve => {entered = resolve;}); + const hold = new Promise(resolve => {release = resolve;}); + const observed: number[] = []; + const work = first.executeGraphSave(new MutationIntent('retain the admitted Fix snapshot'), async () => { + observed.push(context.requireResource('fixTime').getTime()); + context.recordFixEvidence({entityType: 'ClockProbe', modelPath: 'create_time', source: 'clock', sourceLabel: 'graphClock'}); + const evidence = context.getResource('fixEvidenceCurrent'); + entered(); await hold; + observed.push(context.requireResource('fixTime').getTime()); + assert.equal(context.getResource('fixEvidenceCurrent'), evidence); + }); + try { + await ready; + await assert.rejects(second.executeGraphSave(new MutationIntent('refuse another Context owner'), async () => { + throw new Error('a rejected graph must not execute its work'); + }), /mutation policy graph is already active/); + assert.equal(tick, 1001); release(); await work; + assert.deepEqual(observed, [1000, 1000]); + assert.equal(context.getResource('fixTime'), undefined); + assert.equal(context.getResource('fixEvidenceCurrent'), undefined); + assert.deepEqual(context.lastFixEvidence(), [{entityType: 'ClockProbe', modelPath: 'create_time', source: 'clock', sourceLabel: 'graphClock'}]); + console.log('TYPESCRIPT_FIX_OWNER_EXAMPLE=' + JSON.stringify({passed: true, observed, clockCaptures: 1, + rejectedBeforeClock: true, admittedEvidencePreserved: true, scopeReleased: true})); + } finally { + release(); + try {await work;} finally {await first.close(); await second.close();} + } +} diff --git a/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts b/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts index c970b56625635970689e62ec725b8d5feb41411f..0f966ebe8a3e52e37c0a3b850f465766a75e0226 100644 --- a/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts +++ b/source/teaql-ts/examples/conformance/src/generated-bootstrap.ts @@ -1,4 +1,4 @@ -import { UserContext } from './teaql-ts'; +import { UserContext, decimal, long, localTime } from './teaql-ts'; import { Q } from './generated/Q'; import { Platform } from './generated/models/Platform'; @@ -6,7 +6,7 @@ import { Platform } from './generated/models/Platform'; export async function ensureGeneratedBootstrap(context: UserContext): Promise { let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; if (!domainRoot) { - domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot = Platform.teaqlBootstrapNew(context, '1'); domainRoot.updateName("Runtime Example"); await domainRoot.auditAs('create generated Domain Root Platform').save(context); } diff --git a/source/teaql-ts/examples/conformance/src/generated/E.ts b/source/teaql-ts/examples/conformance/src/generated/E.ts index 5ccc5635ccd4119ac905d45e55cbd74d8673c17f..e5c5ac7284970e69dcbbeada14ef32be451121ea 100644 --- a/source/teaql-ts/examples/conformance/src/generated/E.ts +++ b/source/teaql-ts/examples/conformance/src/generated/E.ts @@ -1,40 +1,15 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; import { Platform } from './models/Platform'; import { WorkItem } from './models/WorkItem'; - -export class TeaQLNotLoadedError extends Error { - readonly details: Record; - - constructor( - readonly root: string, - readonly accessPath: string, - readonly breakPoint: string, - ) { - const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; - const details = { - error: 'TeaQLNotLoadedError', - root, - accessPath: accessPath.split('.'), - breakPoint, - missingPreload: [breakPoint], - suggestedFix, - severity: 'error', - humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, - }; - super(JSON.stringify(details)); - this.name = 'TeaQLNotLoadedError'; - this.details = details; - } -} - -function expressionPath(prefix: string, field: string): string { - return prefix ? `${prefix}.${field}` : field; -} +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; export class ValueExpression { constructor( private readonly value: T | null | undefined, private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, ) {} static missing(): ValueExpression { @@ -45,18 +20,26 @@ export class ValueExpression { return new ValueExpression(undefined, false, error); } + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + eval(): T | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; return this.present ? this.value : undefined; } isPresent(): boolean { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; return this.present; } orElse(fallback: T): T { - const value = this.eval(); + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; return this.present && value != null ? value : fallback; } } @@ -65,62 +48,62 @@ export class PlatformExpression { constructor( private readonly value: Platform | null | undefined, private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Platform | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } workItemList(): WorkItemListExpression { - const path = expressionPath(this.path, 'workItemList'); + const path = this.path.member('work_item_list', 'workItemList'); if (this.notLoaded) { - return new WorkItemListExpression([], this.root, path, false, this.notLoaded); + return new WorkItemListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return WorkItemListExpression.missing(this.root, path); if (!this.value.isLoaded('workItemList')) { return new WorkItemListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'workItemList')); + new TeaQLNotLoadedError(path.markMissing(), 'work_item_list')); } return new WorkItemListExpression( this.value.workItemList(), this.root, path, @@ -132,70 +115,70 @@ export class WorkItemExpression { constructor( private readonly value: WorkItem | null | undefined, private readonly root = 'WorkItem(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.workItem()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): WorkItem | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } title(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('title', 'title'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'title'); if (!this.value.isLoaded('title')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'title'), + new TeaQLNotLoadedError(path.markMissing(), 'title'), ); } return new ValueExpression(this.value.title); } - description(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'description'); + description(): ValueExpression { + const path = this.path.member('description', 'description'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('description')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'description'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'description'), ); } - return new ValueExpression(this.value.description); + return new ValueExpression(this.value.description); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -206,21 +189,23 @@ export class WorkItemExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } @@ -230,30 +215,34 @@ export class PlatformListExpression { constructor( private readonly items: readonly Platform[], private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PlatformListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { return new PlatformListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PlatformExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PlatformExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PlatformExpression(undefined, this.root, itemPath) @@ -265,30 +254,34 @@ export class WorkItemListExpression { constructor( private readonly items: readonly WorkItem[], private readonly root = 'WorkItem(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): WorkItemListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): WorkItemListExpression { return new WorkItemListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): WorkItemExpression { - return this.get(0); + return this.item(0, true); } get(index: number): WorkItemExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): WorkItemExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new WorkItemExpression(undefined, this.root, itemPath, this.notLoaded); + return new WorkItemExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new WorkItemExpression(undefined, this.root, itemPath) @@ -301,7 +294,7 @@ export class E { value: Platform | null | undefined, ): PlatformExpression { return new PlatformExpression( - value, `Platform(id=${value?.id ?? 'null'})`, + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), ); } @@ -309,7 +302,7 @@ export class E { value: WorkItem | null | undefined, ): WorkItemExpression { return new WorkItemExpression( - value, `WorkItem(id=${value?.id ?? 'null'})`, + value, 'WorkItem', ExpressionPath.root('E.workItem()', 'camelCase'), ); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts b/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts index a464f45ae27c6f1adfd653ca46350285ee11271b..05edede19972575c779acb6e1c42159779a7e133 100644 --- a/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts +++ b/source/teaql-ts/examples/conformance/src/generated/models/Platform.ts @@ -1,22 +1,28 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { WorkItem } from './WorkItem'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_workItemList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_workItemList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["workItemList"]; Object.assign(this, fields); if (Array.isArray((init as any).workItemList)) { @@ -31,24 +37,32 @@ export class Platform { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._workItemList) child.teaqlAttachRoot(root); + for (const child of (this as any)._workItemList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Platform { - const entity = new Platform(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("workItemList")) result["workItemList"] = (this as any)._workItemList; + return result; } isLoaded(field: string): boolean { @@ -67,12 +81,19 @@ export class Platform { } static refer(id: string | number): Platform { - return new Platform({ id: String(id) } as Partial); + return Platform.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Platform { - return new Platform().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -82,23 +103,126 @@ export class Platform { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._workItemList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._workItemList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("work_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._workItemList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "work_item_list": graph.sourceMembers((this as any)._workItemList) + })); + for (const child of (this as any)._workItemList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._workItemList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("work_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] @@ -106,6 +230,7 @@ export class Platform { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -116,7 +241,8 @@ export class Platform { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -125,22 +251,25 @@ export class Platform { for (const [index, child] of (this as any)._workItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("work_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -148,7 +277,7 @@ export class Platform { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -160,28 +289,27 @@ export class Platform { for (const [index, child] of (this as any)._workItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("work_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -190,12 +318,16 @@ export class Platform { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -206,24 +338,29 @@ export class Platform { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._workItemList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("work_item_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -236,6 +373,10 @@ export class Platform { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -250,7 +391,7 @@ export class Platform { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts b/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts index 3008446a91296326a7fa9835fa8f0cd4b77041b8..e1c4aa84d5661d3f71426d2a702b0a787bec954b 100644 --- a/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts +++ b/source/teaql-ts/examples/conformance/src/generated/models/WorkItem.ts @@ -1,23 +1,29 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; +const teaqlConstruction = Symbol("managed entity construction"); + export class WorkItem { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("WorkItem", + ["id", "title", "description", "platform", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; title?: string; - description?: string; + description?: string | null; platform?: Platform | string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --WorkItem.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { this.platform = (init as any).platform instanceof Platform @@ -27,13 +33,15 @@ export class WorkItem { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "WorkItem", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -42,8 +50,13 @@ export class WorkItem { } static fromRecord(record: Record, root?: EntityRoot): WorkItem { - const entity = new WorkItem(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new WorkItem(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -62,12 +75,19 @@ export class WorkItem { } static refer(id: string | number): WorkItem { - return new WorkItem({ id: String(id) } as Partial); + return WorkItem.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): WorkItem { - return new WorkItem().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): WorkItem { + return EntityCreation.bootstrap(context, "WorkItem", id, + reserved => new WorkItem({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "WorkItem", + reserved => new WorkItem({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -77,23 +97,100 @@ export class WorkItem { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(WorkItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(WorkItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + WorkItem.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "title", canonical: "title" }, { member: "description", canonical: "description" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "WorkItem", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(WorkItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "title", canonical: "title" }, { member: "description", canonical: "description" }, { member: "platform", canonical: "platform" }, { member: "version", canonical: "version" }] @@ -101,6 +198,7 @@ export class WorkItem { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "WorkItem", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -111,7 +209,8 @@ export class WorkItem { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -120,8 +219,10 @@ export class WorkItem { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -129,7 +230,7 @@ export class WorkItem { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -141,14 +242,12 @@ export class WorkItem { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -157,12 +256,16 @@ export class WorkItem { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -173,10 +276,14 @@ export class WorkItem { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -191,6 +298,10 @@ export class WorkItem { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -205,14 +316,14 @@ export class WorkItem { return this; } - updateDescription(value: string): this { + updateDescription(value: string | null): this { this.description = value; this.markLoaded("description"); (this as any)._root.set(this.teaqlEntityKey(), "description", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts index 13411fde2029f019a860ebf78f102aefeb026187..2ffb664f1ac678bd2d142fe55847403b1278e822 100644 --- a/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/conformance/src/generated/requests/PlatformRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PlatformRequest { else this.selectSelfFields(); } + get entityName(): "Platform" { + return "Platform"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PlatformRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -132,7 +139,7 @@ export class PlatformRequest { - selectWorkItemListWith(request: { toQuery(): SelectQuery }): this { + selectWorkItemListWith(request: { readonly entityName: "WorkItem"; toQuery(): SelectQuery }): this { this.query.relationQuery( "workItemList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectWorkItemListWith", relation: "workItemList" }); @@ -141,17 +148,19 @@ export class PlatformRequest { haveWorkItems(): this { return this.withWorkItemListMatching({ + entityName: "WorkItem", toQuery: () => new SelectQuery("WorkItem"), }); } haveNoWorkItems(): this { return this.withoutWorkItemListMatching({ + entityName: "WorkItem", toQuery: () => new SelectQuery("WorkItem"), }); } - withWorkItemListMatching(request: { toQuery(): SelectQuery }): this { + withWorkItemListMatching(request: { readonly entityName: "WorkItem"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -162,7 +171,7 @@ export class PlatformRequest { return this; } - withoutWorkItemListMatching(request: { toQuery(): SelectQuery }): this { + withoutWorkItemListMatching(request: { readonly entityName: "WorkItem"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -179,13 +188,13 @@ export class PlatformRequest { countWorkItemsAs(alias: string): this { const query = new SelectQuery("WorkItem").filter({ version: { "$gte": 1 } }); - this.countWorkItemsWith(alias, { toQuery: () => query }); + this.countWorkItemsWith(alias, { entityName: "WorkItem", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countWorkItemsAs", relation: "workItemList", alias }; return this; } - countWorkItemsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countWorkItemsWith(alias: string, child: { readonly entityName: "WorkItem"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -196,47 +205,47 @@ export class PlatformRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -261,42 +270,42 @@ export class PlatformRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -340,47 +349,47 @@ export class PlatformRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -449,7 +458,7 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -458,7 +467,7 @@ export class PlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByVersion(): this { @@ -467,7 +476,7 @@ export class PlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } @@ -580,9 +589,10 @@ export class ExecutablePlatformRequest { return this; } - newEntity(context: UserContext): Platform { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Platform(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts b/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts index 134b124febb994f01d43aac5cc4432c7dabf4007..28164fa8885c5fbbfa1861ad8675e8cfd276599d 100644 --- a/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts +++ b/source/teaql-ts/examples/conformance/src/generated/requests/WorkItemRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { WorkItem } from '../models/WorkItem'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class WorkItemRequest { else this.selectSelfFields(); } + get entityName(): "WorkItem" { + return "WorkItem"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class WorkItemRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -136,7 +143,7 @@ export class WorkItemRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -144,7 +151,7 @@ export class WorkItemRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -153,7 +160,7 @@ export class WorkItemRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -165,47 +172,47 @@ export class WorkItemRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -230,42 +237,42 @@ export class WorkItemRequest { return this; } - withTitleIsNot(val: any): this { + withTitleIsNot(val: string): this { this.filters.push({ "title": { "$ne": val } }); return this; } - withTitleIn(...vals: any[]): this { + withTitleIn(...vals: string[]): this { this.filters.push({ "title": { "$in": vals } }); return this; } - withTitleNotIn(...vals: any[]): this { + withTitleNotIn(...vals: string[]): this { this.filters.push({ "title": { "$notIn": vals } }); return this; } - withTitleGreaterThan(val: any): this { + withTitleGreaterThan(val: string): this { this.filters.push({ "title": { "$gt": val } }); return this; } - withTitleGreaterThanOrEqualTo(val: any): this { + withTitleGreaterThanOrEqualTo(val: string): this { this.filters.push({ "title": { "$gte": val } }); return this; } - withTitleLessThan(val: any): this { + withTitleLessThan(val: string): this { this.filters.push({ "title": { "$lt": val } }); return this; } - withTitleLessThanOrEqualTo(val: any): this { + withTitleLessThanOrEqualTo(val: string): this { this.filters.push({ "title": { "$lte": val } }); return this; } - withTitleBetween(lower: any, upper: any): this { + withTitleBetween(lower: string, upper: string): this { this.filters.push({ "title": { "$between": [lower, upper] } }); return this; } @@ -319,42 +326,42 @@ export class WorkItemRequest { return this; } - withDescriptionIsNot(val: any): this { + withDescriptionIsNot(val: string): this { this.filters.push({ "description": { "$ne": val } }); return this; } - withDescriptionIn(...vals: any[]): this { + withDescriptionIn(...vals: string[]): this { this.filters.push({ "description": { "$in": vals } }); return this; } - withDescriptionNotIn(...vals: any[]): this { + withDescriptionNotIn(...vals: string[]): this { this.filters.push({ "description": { "$notIn": vals } }); return this; } - withDescriptionGreaterThan(val: any): this { + withDescriptionGreaterThan(val: string): this { this.filters.push({ "description": { "$gt": val } }); return this; } - withDescriptionGreaterThanOrEqualTo(val: any): this { + withDescriptionGreaterThanOrEqualTo(val: string): this { this.filters.push({ "description": { "$gte": val } }); return this; } - withDescriptionLessThan(val: any): this { + withDescriptionLessThan(val: string): this { this.filters.push({ "description": { "$lt": val } }); return this; } - withDescriptionLessThanOrEqualTo(val: any): this { + withDescriptionLessThanOrEqualTo(val: string): this { this.filters.push({ "description": { "$lte": val } }); return this; } - withDescriptionBetween(lower: any, upper: any): this { + withDescriptionBetween(lower: string, upper: string): this { this.filters.push({ "description": { "$between": [lower, upper] } }); return this; } @@ -418,47 +425,47 @@ export class WorkItemRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -538,7 +545,7 @@ export class WorkItemRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByTitle(): this { @@ -547,7 +554,7 @@ export class WorkItemRequest { } groupByTitleAs(retName: string): this { - this.query.groupBy("title"); // In TS we don't alias group by yet natively + this.query.groupBy("title", retName); return this; } groupByDescription(): this { @@ -556,7 +563,7 @@ export class WorkItemRequest { } groupByDescriptionAs(retName: string): this { - this.query.groupBy("description"); // In TS we don't alias group by yet natively + this.query.groupBy("description", retName); return this; } groupByPlatform(): this { @@ -565,7 +572,7 @@ export class WorkItemRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupByVersion(): this { @@ -574,14 +581,14 @@ export class WorkItemRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -697,9 +704,10 @@ export class ExecutableWorkItemRequest { return this; } - newEntity(context: UserContext): WorkItem { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new WorkItem(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return WorkItem.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/conformance/src/main.ts b/source/teaql-ts/examples/conformance/src/main.ts index 06bb0f2d09280f7e405de863e0f7ba890e87230f..a7c52a2c193b8618913a59c2cc5362c36f0a61a8 100644 --- a/source/teaql-ts/examples/conformance/src/main.ts +++ b/source/teaql-ts/examples/conformance/src/main.ts @@ -1,12 +1,15 @@ +import {internalId} from 'teaql-ts'; import assert from "node:assert/strict"; import fs from "node:fs"; import path from "node:path"; -import { CheckException, EntityRoot, UserContext } from "./teaql-ts"; +import { CheckException, EntityRoot, UserContext, nextEntityVersion } from "./teaql-ts"; import { E, TeaQLNotLoadedError } from "./generated/E"; import { Q } from "./generated/Q"; -import { WorkItem } from "./generated/models/WorkItem"; import { SQLiteTeaQLClient } from "./teaql-node-sqlite"; import { verifyMaskingLifecycle } from './masking-verification'; +import { LocalCache } from 'teaql-ts'; +import { verifyOperationalClock } from './operational-clock-verification'; +import { verifyFixOwnerAdmission } from './fix-owner-verification'; async function main(): Promise { const orderKey = { entity: "Order", id: 1 } as const; @@ -23,7 +26,6 @@ async function main(): Promise { const database = path.resolve(__dirname, "../.local/conformance.sqlite"); fs.mkdirSync(path.dirname(database), { recursive: true }); - fs.rmSync(database, { force: true }); const client = new SQLiteTeaQLClient(database); const context = new UserContext().insertResource("dataService", client); client.setUserContext(context); @@ -31,8 +33,9 @@ async function main(): Promise { await context.ensureSchema(); console.log("PASS ensureSchema (explicit SQLite DDL and Platform(1) bootstrap)"); + const invalid = (await Q.workItems().comment('reserve the invalid Checker fixture') + .purpose('verify business validation before mutation SQL').newEntity(context)).updatePlatform("1"); const sqlBeforeInvalidSave = client.sqlTrace.length; - const invalid = new WorkItem().updatePlatform("1"); await assert.rejects(invalid.auditAs("Checker must reject a missing title").save(context), (error: unknown) => { assert(error instanceof CheckException); assert(error.violations.some(item => item.ruleId === "required" && String(item.location).includes("title"))); @@ -41,7 +44,8 @@ async function main(): Promise { assert.equal(client.sqlTrace.length, sqlBeforeInvalidSave, "Checker must run before mutation SQL"); console.log("PASS Checker (canonical title key, rejected before SQL)"); - const created = await new WorkItem() + const created = await (await Q.workItems().comment('reserve a conformance work item') + .purpose('verify managed creation through the Context allocator').newEntity(context)) .updateTitle("Verify TypeScript runtime") .updatePlatform("1") .auditAs("Create conformance work item").save(context); @@ -49,7 +53,7 @@ async function main(): Promise { assert.equal(created.version, 1); console.log(`PASS Create (id=${created.id}, version=${created.version})`); - const queried = await Q.workItems().withIdIs(created.id) + const queried = await Q.workItems().withIdIs(internalId(created.id)) .selectPlatformWith(Q.platforms().selectName()) .comment("Load the complete work item before mutation") .purpose("Verify typed Q API and update semantics").executeForOne(context); @@ -60,7 +64,7 @@ async function main(): Promise { assert.equal(E.workItem(queried).title().eval(), "Verify TypeScript runtime"); assert.equal(E.workItem(queried).description().orElse("N/A"), "N/A"); - const minimal = await Q.workItemsWithMinimalFields().withIdIs(created.id) + const minimal = await Q.workItemsWithMinimalFields().withIdIs(internalId(created.id)) .comment("Load only mandatory identity fields") .purpose("Verify E not-loaded semantics").executeForOne(context); assert(minimal); @@ -70,11 +74,11 @@ async function main(): Promise { const previousVersion = queried.version!; await queried.updateTitle("Verified TypeScript runtime") .auditAs("Update conformance work item").save(context); - assert.equal(queried.version, previousVersion + 1); + assert.equal(queried.version, nextEntityVersion('Update', previousVersion)); console.log(`PASS Update (version ${previousVersion} -> ${queried.version})`); await queried.markForDeletion().auditAs("Delete conformance work item").save(context); - const remaining = await Q.workItems().withIdIs(created.id) + const remaining = await Q.workItems().withIdIs(internalId(created.id)) .comment("Verify soft-deleted work item is excluded") .purpose("Verify delete semantics").executeForList(context); assert.equal(remaining.length, 0); @@ -83,6 +87,8 @@ async function main(): Promise { await client.close(); console.log("PASS TypeScript minimum runtime conformance: 8/8"); await verifyMaskingLifecycle(); + console.log('TYPESCRIPT_OPERATIONAL_CLOCK_EXAMPLE=' + JSON.stringify(await verifyOperationalClock(new UserContext(), new LocalCache()))); + await verifyFixOwnerAdmission(); } main().catch(error => { console.error(error); process.exitCode = 1; }); diff --git a/source/teaql-ts/examples/conformance/src/operational-clock-verification.ts b/source/teaql-ts/examples/conformance/src/operational-clock-verification.ts new file mode 100644 index 0000000000000000000000000000000000000000..c72fff5526dcc389058c9ada84b5028f67372b19 --- /dev/null +++ b/source/teaql-ts/examples/conformance/src/operational-clock-verification.ts @@ -0,0 +1,37 @@ +import assert from 'node:assert/strict'; +import {setTimeout as delay} from 'node:timers/promises'; + +type ClockContext = {withBusinessClock(clock: {now(): Date}): unknown; businessTime(): Date}; +type Cache = {put(key: string, value: unknown, ttl?: number): void; get(key: string): unknown}; + +/** Inject real runtime instances; no alternate cache or private-state adapter. */ +export async function verifyOperationalClock(context: ClockContext, cache: Cache) { + let calls = 0, unreadable = false; + let business = new Date('2099-12-31T23:59:59Z'); + context.withBusinessClock({now: () => { + calls++; + if (unreadable) throw new Error('BUSINESS_CLOCK_UNAVAILABLE_FOR_OPERATIONAL_WORK'); + return new Date(business); + }}); + assert.equal(context.businessTime().toISOString(), business.toISOString()); + unreadable = true; + assert.throws(() => context.businessTime(), /BUSINESS_CLOCK_UNAVAILABLE/); + const calibrationCalls = calls; + cache.put('permanent-zero', 0, 0); cache.put('permanent-false', false); + cache.put('permanent-empty', ''); cache.put('permanent-null', null); + cache.put('real-expiry', 'live', 0.2); + assert.equal(cache.get('real-expiry'), 'live'); + business = new Date('2199-01-01T00:00:00Z'); + assert.equal(cache.get('real-expiry'), 'live', 'business-calendar changes cannot expire a live entry'); + const deadline = performance.now() + 2_000; + while (cache.get('real-expiry') !== undefined && performance.now() < deadline) await delay(10); + assert.equal(cache.get('real-expiry'), undefined, 'operational TTL must expire with an unreadable Business Clock'); + business = new Date('1900-01-01T00:00:00Z'); + assert.equal(cache.get('real-expiry'), undefined, 'business time cannot revive a discarded entry'); + assert.equal(cache.get('permanent-zero'), 0); assert.equal(cache.get('permanent-false'), false); + assert.equal(cache.get('permanent-empty'), ''); assert.equal(cache.get('permanent-null'), null); + assert.equal(calls, calibrationCalls, 'operational cache must not consume Business Clock'); + return {passed: true, calibrationCalls, additionalBusinessReads: calls - calibrationCalls, + facts: {realExpiry: true, unavailableBusinessCalibrated: true, forwardCannotExpire: true, backwardCannotRevive: true, + zeroTtlRemains: true, zeroFalseEmptyNullRemainValues: true}}; +} diff --git a/source/teaql-ts/examples/conformance/src/runtime-module.ts b/source/teaql-ts/examples/conformance/src/runtime-module.ts index 086251a3faf86275edfe441ff7ab737a6c7fd46e..0de99c299d4a7ae348a579280c45ffc113a9be8b 100644 --- a/source/teaql-ts/examples/conformance/src/runtime-module.ts +++ b/source/teaql-ts/examples/conformance/src/runtime-module.ts @@ -1,3 +1,4 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; import { ObjectLocation, RuntimeModule } from "teaql-ts"; import { ENTITY_SCHEMAS } from "./teaql-schemas"; import { ensureGeneratedBootstrap } from "./generated-bootstrap"; diff --git a/source/teaql-ts/examples/conformance/src/teaql-ts.ts b/source/teaql-ts/examples/conformance/src/teaql-ts.ts index b54a29ac3c12fb072cf4c292e22bb2e644b56319..9983b00b27c90dc429fca76441f2bf077f825921 100644 --- a/source/teaql-ts/examples/conformance/src/teaql-ts.ts +++ b/source/teaql-ts/examples/conformance/src/teaql-ts.ts @@ -1,14 +1,26 @@ import { - CheckException, EntityChecker, RuntimeModule, + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, SelectQuery as RuntimeSelectQuery, UserContext, - executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, } from "teaql-ts"; export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; -export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; export type { EntityKey } from "teaql-ts"; export type { TeaQLPage } from "teaql-ts"; import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; function soundex(input: unknown): string { const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); @@ -41,7 +53,8 @@ export class SelectQuery extends RuntimeSelectQuery { } export interface TeaQLDataService { - executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; preflightMutation(mutation: any): any; afterGraphCommit(work: () => void): void; afterGraphRollback(work: () => void): void; @@ -52,18 +65,24 @@ export interface TeaQLDataService { close?(): Promise; } -export class TeaQLClient implements TeaQLDataService { +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { private data: Record> = {}; private nextIds: Record = {}; private readonly checkers: Record = {}; + private readonly schemas: Record = {}; private userContext = new UserContext(); private graphSaveActive = false; + private activeGraph?: GraphMutationSession; private graphCommitActions: Array<() => void> = []; private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; private graphSaveTail: Promise = Promise.resolve(); private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; constructor(private storagePath?: string) { + super(); if (storagePath) { const fs = require("fs"); if (fs.existsSync(storagePath)) { @@ -76,10 +95,74 @@ export class TeaQLClient implements TeaQLDataService { /** Installs passive generated metadata. It never mutates storage. */ install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); return this; } + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + setUserContext(context: UserContext): this { this.userContext = context; return this; @@ -89,6 +172,33 @@ export class TeaQLClient implements TeaQLDataService { return [...this.mutationGovernanceEvents]; } + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + private persist() { if (!this.storagePath) return; const fs = require("fs"); @@ -99,8 +209,15 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } - async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } const predecessor = this.graphSaveTail; let release!: () => void; this.graphSaveTail = new Promise(resolve => { release = resolve; }); @@ -109,32 +226,57 @@ export class TeaQLClient implements TeaQLDataService { const nextIdsSnapshot = { ...this.nextIds }; let fixEvidenceStarted = false; let mutationPolicyGraphStarted = false; + let committed = false; try { + graph.validatePreparedSources(); this.graphSaveActive = true; + this.activeGraph = graph; this.graphCommitActions = []; this.graphRollbackActions = []; - this.userContext.insertResource("fixTime", new Date()); - this.userContext.beginFixEvidence(); - fixEvidenceStarted = true; - this.userContext.beginMutationPolicyGraph(); + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); const result = await work(graph); - this.userContext.ensureMutationPolicyGraphComplete(); - this.persist(); - for (const action of this.graphCommitActions) action(); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); return result; } catch (error) { - this.data = dataSnapshot; - this.nextIds = nextIdsSnapshot; - for (const action of [...this.graphRollbackActions].reverse()) action(); + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } throw error; } finally { this.graphSaveActive = false; + this.activeGraph = undefined; this.graphCommitActions = []; this.graphRollbackActions = []; - if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); - this.userContext.removeResource("fixTime"); - if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); release(); } } @@ -150,84 +292,145 @@ export class TeaQLClient implements TeaQLDataService { } preflightMutation(mutation: any): any { - mutation = this.checkAndFixMutation(mutation); - this.userContext.recordMutationPolicyPreflight(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); return mutation; } private checkAndFixMutation(mutation: any): any { - if (mutation instanceof MutationRequest) mutation = mutation.mutation; - if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; - const checker = this.checkers[String(mutation.entity)]; - if (!checker) return mutation; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } const results: any[] = []; const ownsFixTime = this.userContext.getResource("fixTime") === undefined; - if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); try { checker.checkAndFix(this.userContext, mutation, results); - if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); - this.userContext.translateCheckResults(results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); if (results.length) throw new CheckException(results); - return mutation; + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } } async executeMutation(mutation: any): Promise { - mutation = this.checkAndFixMutation(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); const mutationGovernance = this.userContext.enterMutationPolicy(mutation); - this.mutationGovernanceEvents.push(mutationGovernance); const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); if (mutation.action === "Create") { const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); - this.nextIds[mutation.entity] = Number(id) + 1; - const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; table[String(id)] = record; if (!this.graphSaveActive) this.persist(); - return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; - } - if (mutation.action === "Update") { - const id = String(mutation.id); - if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { - throw new Error( - `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); - } - table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; - if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); } - if (mutation.action === "Delete") { + if (["Update", "Delete", "Recover"].includes(mutation.action)) { const id = String(mutation.id); if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { throw new Error( `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); } - table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); } throw new Error(`Unsupported mutation action: ${mutation.action}`); } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } async query(context: any, req: any): Promise { return { rows: [] }; } async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; if (!(query instanceof RuntimeSelectQuery)) { throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); } query.prepareForList(); - let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); const matches = (row: any, expression: any): boolean => { if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { - if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); - if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); @@ -235,15 +438,17 @@ export class TeaQLClient implements TeaQLDataService { if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); - if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; - if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; - if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; - if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; - if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; return true; }); }; @@ -257,17 +462,19 @@ export class TeaQLClient implements TeaQLDataService { }))]; } for (const order of [...query.orderItems].reverse()) { - rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); } const start = query.offsetValue || 0; rows = rows.slice(start, start + query.limitValue); for (const relation of (query.relations || []) as any[]) { - const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); - const relatedRows = (await this.executeQuery(relation.query)).filter( - (row: any) => localValues.has(row[relation.foreignKey || "id"])); for (const row of rows) { - const matches = relatedRows.filter( - (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); row[relation.name] = relation.many === false ? matches[0] : matches; } } @@ -277,6 +484,8 @@ export class TeaQLClient implements TeaQLDataService { rows = rows.map((row: any) => Object.fromEntries( Object.entries(row).filter(([field]) => selections.has(field)))); } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); return rows; } async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { @@ -294,6 +503,7 @@ export class TeaQLClient implements TeaQLDataService { return value; } async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); const rows = await this.executeQuery(query); for (let offset = 0; offset < rows.length; offset += chunkSize) { diff --git a/source/teaql-ts/examples/conformance/verify-managed.cjs b/source/teaql-ts/examples/conformance/verify-managed.cjs new file mode 100644 index 0000000000000000000000000000000000000000..910f298ae77bc36ab201dd993c8a453b78bbbbde --- /dev/null +++ b/source/teaql-ts/examples/conformance/verify-managed.cjs @@ -0,0 +1,37 @@ +'use strict'; +// Local repository source, original generated fixture, two unreset SQLite rounds. +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),assert=require('node:assert/strict'),crypto=require('node:crypto'); +const {createOwnedRunner,ownedBytes}=require('../fix-e-alignment/owned-command.cjs'); +const repo=path.resolve(__dirname,'../..'),sha=b=>crypto.createHash('sha256').update(b).digest('hex'); +function fixture(){ + const m=JSON.parse(fs.readFileSync(path.join(__dirname,'current-generator-fixture.json'))); + assert.equal(sha(fs.readFileSync(path.join(__dirname,'model.xml'))),m.modelSha256); + for(const[n,h]of Object.entries(m.files))assert.equal(sha(fs.readFileSync(path.join(__dirname,n))),h,n); + return m; +} +async function main(){ + const requested=process.env.TEAQL_MANAGED_EVIDENCE_DIR,output=requested?path.resolve(requested):fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-managed-evidence-')); + if(requested){assert(path.isAbsolute(requested)&&!fs.existsSync(output));fs.mkdirSync(output,{recursive:true});} + const r={schema:'teaql.typescript-managed-example/v1',passed:false,rounds:[],sameDatabase:true,sourceOnly:true,installedSdkAccepted:false};let scratch,runner; + try{ + scratch=fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-managed-example-'));runner=createOwnedRunner();const before=fixture();r.modelSha256=before.modelSha256; + const config=path.join(scratch,'jest.cjs'),tsconfig=path.join(scratch,'tsconfig.json'); + fs.writeFileSync(tsconfig,JSON.stringify({extends:path.join(repo,'tsconfig.json'),compilerOptions:{baseUrl:repo,types:['node','jest'],typeRoots:[path.join(repo,'node_modules/@types')],lib:['ES2022','DOM'],paths:{'teaql-ts':[path.join(repo,'src/index.ts')],'teaql-ts/*':[path.join(repo,'src/*')]}}})); + fs.writeFileSync(config,'module.exports='+JSON.stringify({rootDir:repo,roots:[__dirname],testEnvironment:'node',testTimeout:30000,testMatch:[__dirname+'/managed-*.test.ts'],moduleNameMapper:{'^teaql-ts$':repo+'/src/index.ts','^teaql-ts/(.*)$':repo+'/src/$1'},transform:{'^.+\\.tsx?$':['ts-jest',{tsconfig}]}})+';\n'); + for(const round of [1,2]){ + const results=path.join(output,'round-'+round+'.json'),log=path.join(output,'round-'+round+'.log'),fd=fs.openSync(log,'wx');let q; + const command=[process.execPath,path.join(repo,'node_modules/jest/bin/jest.js'),'--config',config,'--runInBand','--no-cache','--json','--outputFile',results]; + try{q=await runner.run(command,{cwd:repo,env:{...process.env,TEAQL_MANAGED_DATABASE:path.join(output,'managed.sqlite')},timeout:120000,stdio:['ignore',fd,fd]});}finally{fs.closeSync(fd);} + r.rounds.push({round,command,exitCode:q.status,signal:q.signal,logSha256:sha(fs.readFileSync(log))}); + assert.equal(q.status,0,'inspect retained '+log);assert.equal(q.signal,null); + const native=JSON.parse(fs.readFileSync(results));assert.equal(native.numFailedTests+native.numRuntimeErrorTestSuites+native.numPendingTests,0);assert.equal(native.numPassedTests,14);assert.equal(native.numTotalTestSuites,2); + const cases=native.testResults.flatMap(s=>s.assertionResults.map(t=>({name:t.fullName,status:t.status}))).sort((a,b)=>a.name.localeCompare(b.name)); + Object.assign(r.rounds.at(-1),{passed:native.numPassedTests,resultsSha256:sha(fs.readFileSync(results)),cases});assert.deepEqual(fixture(),before); + } + assert.deepEqual(r.rounds[0].cases,r.rounds[1].cases);r.databaseSha256=sha(fs.readFileSync(path.join(output,'managed.sqlite')));r.passed=true; + console.log('PASS TypeScript managed creation example: 6 boundary and 8 SQLite cases twice on one database'); + }catch(error){r.error=error.stack;console.error(error.stack);process.exitCode=1;} + finally{r.cleanup={scratchRemoved:false,sharedCachesDeleted:false,sourceOrDatabasesDeleted:false};try{assert(!runner||runner.safeToClean);r.cleanup.disposedOwnedBytes=scratch?ownedBytes(scratch):0;if(scratch)fs.rmSync(scratch,{recursive:true});r.cleanup.scratchRemoved=true;}catch(error){r.cleanup.error=error.stack;r.cleanup.retained=scratch;process.exitCode=1;r.passed=false;} + runner?.dispose();fs.writeFileSync(path.join(output,'report.json'),JSON.stringify(r,null,2)+'\n');console.log('Retained managed example evidence: '+output);} +} +main().catch(error=>{console.error(error.stack);process.exitCode=1;}); diff --git a/source/teaql-ts/examples/context-derived/README.md b/source/teaql-ts/examples/context-derived/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cb654463ac54bfbd794d25069135b00279622827 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/README.md @@ -0,0 +1,26 @@ +# Staged Context Fix with generated Q/E and audited save + +Run `npm ci` at the runtime root, then: + +```sh +node examples/context-derived/verify-local.cjs +``` + +This verifies both SQLite and the generated file-backed client, twice against +the same per-provider database. Every generated import is mapped to this local +runtime's source. The verifier checks source and generated-fixture hashes and +removes its owned compiler/Jest scratch directory on exit. To retain compact +logs, receipts and test databases, set `TEAQL_CONTEXT_FIX_EVIDENCE_DIR` to a new +directory. No public package publication or remote runtime fallback is used. + +The two-entity fixture covers changed clock/IP/actor with an unchanged save, +real update versus create-only fields, located provider/type/validation errors, +retained caller edits, graph-wide Context rollback and retry. IP/actor ownership +is application metadata/Checker customization, not a new built-in KSML type. +`contextFixResolver` is synchronous: prepare external/async values before save; +an async provider is rejected with a safe field-level Check error. + +Regenerate the immutable fixture from the generator's +`TypescriptContextFixGenerationTest` using +`-Dteaql.ts.context.fixture.output=`. Do not edit +generated library files to make a test pass. diff --git a/source/teaql-ts/examples/context-derived/fixture/generated-files.json b/source/teaql-ts/examples/context-derived/fixture/generated-files.json new file mode 100644 index 0000000000000000000000000000000000000000..242d9cb8088566a93cdd4811c8d704ec4e2e2f7c --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/generated-files.json @@ -0,0 +1,18 @@ +{ + "package.json" : "4b295c799088ba0e2ff40f1966d0a217d422ba7701a93a0d754b0bb376b41d2e", + "src/generated-bootstrap.ts" : "677a9cf250a379a43c2be66dec7c34ba16f7c40902ace18ac4848956244a25d2", + "src/generated-search-models.ts" : "0aae657219f68a015137b6d671ea86187af6df454a5cc7d5ea85bbd7b5e61838", + "src/generated/E.ts" : "dcb6d1c0cc2e170efaadeb9948e8c1f9a4b06888e4d4dbdd0eb78d5ccee11b60", + "src/generated/Q.ts" : "482e727f3b0cb5c10dce9924a3aff1d64b0b68d90f2f20374cc2b89018fa9f82", + "src/generated/models/Catalog.ts" : "f92aaedff2688e897239d149d6f2723792da22588a8737c38f597344de012aea", + "src/generated/models/Entry.ts" : "40291a11993fbbd68761599e7ef2e3b6bf4e5e4e9f668c599d70c940f2fbafcf", + "src/generated/requests/CatalogRequest.ts" : "accacd09d03c992cef2c7a93cf634387d93c37a58c021879fc52ccb0d59283ba", + "src/generated/requests/EntryRequest.ts" : "faaa7c3c77cc001c21dea3b2f97c24fcf08cd182946527828603eef4c1a341bf", + "src/runtime-module.ts" : "32b10a4acc8ca3bb140fe79859ae18986587cd2e6ab706bf8c05fbb678ff1d3a", + "src/teaql-node-sql.ts" : "bdbda133ec9fcae78daaf8155753558a25820cb1e1dcdc852b2932cf3ed4c8d5", + "src/teaql-node-sqlite.ts" : "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/teaql-ts.ts" : "097d31e104cbdec030b2afdf51774ba88390f7b576fef641e97383672f5125a5", + "teaql-i18n.json" : "872f2be4fb4df7d76c732d627ae016b07cb39591ef833169277c67db4ec726e8", + "teaql/model-provenance.json" : "2fce8608af8dc31b56c3e98779917206e1b076b81dcc2e17bd2fe0db4d6d1a82", + "tsconfig.json" : "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" +} diff --git a/source/teaql-ts/examples/context-derived/fixture/model.xml b/source/teaql-ts/examples/context-derived/fixture/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..f5dd9e1f440ddab9a756e3c00efd0e18a74c1c85 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/model.xml @@ -0,0 +1,5 @@ + + + + diff --git a/source/teaql-ts/examples/context-derived/fixture/package.json b/source/teaql-ts/examples/context-derived/fixture/package.json new file mode 100644 index 0000000000000000000000000000000000000000..ec1952a667e95c5f4e773ff4c34cf6c9260448bc --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/package.json @@ -0,0 +1,18 @@ +{ + "name": "context-fix-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.4.0", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated-bootstrap.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..63c96a67e0d10df872681959dd87ef07027dcef1 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { Catalog } from './generated/models/Catalog'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.catalogs().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = Catalog.teaqlBootstrapNew('1'); + domainRoot.updateName("Catalog"); + await domainRoot.auditAs('create generated Domain Root Catalog').save(context); + } + context.withActiveRoot({ entity: 'Catalog', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated-search-models.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffd0a2c0cf1218a12ada9ec6dc23588bed51e16c --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated-search-models.ts @@ -0,0 +1,65 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "Catalog": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "entryList": "Entry", + }), + }), + "Entry": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "catalog": "integer" as const, + "name": "string" as const, + "born_at": "timestamp" as const, + "bornAt": "timestamp" as const, + "touched_at": "timestamp" as const, + "touchedAt": "timestamp" as const, + "source_ip": "string" as const, + "sourceIp": "string" as const, + "last_ip": "string" as const, + "lastIp": "string" as const, + "opened_by": "string" as const, + "openedBy": "string" as const, + "changed_by": "string" as const, + "changedBy": "string" as const, + "guarded_token": "string" as const, + "guardedToken": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "catalog": "catalog", + "name": "name", + "born_at": "bornAt", + "bornAt": "bornAt", + "touched_at": "touchedAt", + "touchedAt": "touchedAt", + "source_ip": "sourceIp", + "sourceIp": "sourceIp", + "last_ip": "lastIp", + "lastIp": "lastIp", + "opened_by": "openedBy", + "openedBy": "openedBy", + "changed_by": "changedBy", + "changedBy": "changedBy", + "guarded_token": "guardedToken", + "guardedToken": "guardedToken", + "version": "version", + }), + relations: Object.freeze({ + "catalog": "Catalog", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated/E.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..44d97542ee89c3d55a36b734cb847adabda91138 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated/E.ts @@ -0,0 +1,380 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { Catalog } from './models/Catalog'; +import { Entry } from './models/Entry'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class CatalogExpression { + constructor( + private readonly value: Catalog | null | undefined, + private readonly root = 'Catalog(null)', + private readonly path = ExpressionPath.root('E.catalog()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Catalog | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + entryList(): EntryListExpression { + const path = this.path.member('entry_list', 'entryList'); + if (this.notLoaded) { + return new EntryListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return EntryListExpression.missing(this.root, path); + if (!this.value.isLoaded('entryList')) { + return new EntryListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'entry_list')); + } + return new EntryListExpression( + this.value.entryList(), this.root, path, + ); + } +} + +export class EntryExpression { + constructor( + private readonly value: Entry | null | undefined, + private readonly root = 'Entry(null)', + private readonly path = ExpressionPath.root('E.entry()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Entry | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + bornAt(): ValueExpression { + const path = this.path.member('born_at', 'bornAt'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('bornAt')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'born_at'), + ); + } + return new ValueExpression(this.value.bornAt); + } + + touchedAt(): ValueExpression { + const path = this.path.member('touched_at', 'touchedAt'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('touchedAt')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'touched_at'), + ); + } + return new ValueExpression(this.value.touchedAt); + } + + sourceIp(): ValueExpression { + const path = this.path.member('source_ip', 'sourceIp'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('sourceIp')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'source_ip'), + ); + } + return new ValueExpression(this.value.sourceIp); + } + + lastIp(): ValueExpression { + const path = this.path.member('last_ip', 'lastIp'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('lastIp')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'last_ip'), + ); + } + return new ValueExpression(this.value.lastIp); + } + + openedBy(): ValueExpression { + const path = this.path.member('opened_by', 'openedBy'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('openedBy')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'opened_by'), + ); + } + return new ValueExpression(this.value.openedBy); + } + + changedBy(): ValueExpression { + const path = this.path.member('changed_by', 'changedBy'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('changedBy')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'changed_by'), + ); + } + return new ValueExpression(this.value.changedBy); + } + + guardedToken(): ValueExpression { + const path = this.path.member('guarded_token', 'guardedToken'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('guardedToken')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'guarded_token'), + ); + } + return new ValueExpression(this.value.guardedToken); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + catalogId(): ValueExpression { + const path = this.path.member('catalog', 'catalogId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('catalog')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'catalog'), + ); + } + const reference = this.value.catalog; + return new ValueExpression( + reference instanceof Catalog + ? reference.id : reference as string | number | undefined, + ); + } + + catalog(): CatalogExpression { + const path = this.path.member('catalog', 'catalog'); + if (this.notLoaded) { + return new CatalogExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new CatalogExpression(undefined, this.root, path); + if (!this.value.isLoaded('catalog')) { + return new CatalogExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'catalog')); + } + const relation = this.value.catalog; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Catalog)) { + return new CatalogExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'catalog')); + } + const target = relation instanceof Catalog ? relation : undefined; + return new CatalogExpression(target, this.root, path); + } + +} + +export class CatalogListExpression { + constructor( + private readonly items: readonly Catalog[], + private readonly root = 'Catalog(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): CatalogListExpression { + return new CatalogListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): CatalogExpression { + return this.item(0, true); + } + + get(index: number): CatalogExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): CatalogExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new CatalogExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new CatalogExpression(undefined, this.root, itemPath) + : new CatalogExpression(this.items[index], this.root, itemPath); + } +} + +export class EntryListExpression { + constructor( + private readonly items: readonly Entry[], + private readonly root = 'Entry(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): EntryListExpression { + return new EntryListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): EntryExpression { + return this.item(0, true); + } + + get(index: number): EntryExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): EntryExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new EntryExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new EntryExpression(undefined, this.root, itemPath) + : new EntryExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static catalog( + value: Catalog | null | undefined, + ): CatalogExpression { + return new CatalogExpression( + value, 'Catalog', ExpressionPath.root('E.catalog()', 'camelCase'), + ); + } + + static entry( + value: Entry | null | undefined, + ): EntryExpression { + return new EntryExpression( + value, 'Entry', ExpressionPath.root('E.entry()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated/Q.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e5a7216c93e8384c6449f6ba5763d54f3e66df6 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { CatalogRequest } from './requests/CatalogRequest'; +import { EntryRequest } from './requests/EntryRequest'; + +export class Q { + static catalogs(): CatalogRequest { + return new CatalogRequest(false); + } + + static catalogsWithMinimalFields(): CatalogRequest { + return new CatalogRequest(true); + } + static entries(): EntryRequest { + return new EntryRequest(false); + } + + static entriesWithMinimalFields(): EntryRequest { + return new EntryRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated/models/Catalog.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated/models/Catalog.ts new file mode 100644 index 0000000000000000000000000000000000000000..eb51496702102dab008b4622f666df9d2b3a37c0 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated/models/Catalog.ts @@ -0,0 +1,403 @@ +import { CheckException, integer32Error, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Entry } from './Entry'; + +export class Catalog { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Catalog", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Catalog.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_entryList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + delete fields["entryList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).entryList)) { + const selected = (init as any).entryList; + (this as any)._entryList = new SmartList(selected.map( + (child: unknown) => child instanceof Entry + ? child + : Entry.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("entryList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Catalog", id: (this as any)._ledgerId }; } + /** @internal Restore known equal scalars after the prepared graph completes. */ + private teaqlRestoreFixedValues(values: Readonly>): void { + for (const field of [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }]) { + if (Object.prototype.hasOwnProperty.call(values, field.canonical)) (this as any)[field.member] = values[field.canonical]; + } + } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._entryList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Catalog { + const entity = new Catalog(record as Partial); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + return this.teaqlJson(new Set()); + } + + private static teaqlJsonValue(value: any, active: Set): any { + if (value === null || value === undefined) return value; + if (typeof value.teaqlJson === "function") return value.teaqlJson(active); + if (Array.isArray(value)) return Array.from(value, item => this.teaqlJsonValue(item, active)); + if (typeof value.toJSON === "function") return value.toJSON(); + if (typeof value === "object") return Object.fromEntries(Object.entries(value).map( + ([key, item]) => [key, this.teaqlJsonValue(item, active)])); + return typeof value === "bigint" ? value.toString() : value; + } + + private teaqlJson(active: Set): Record { + if (active.has(this)) return { id: this.id, version: this.version }; + active.add(this); + try { + // Only enumerable business/query data participates; runtime state is private. + const payload = Object.fromEntries(Object.entries(this).filter(([key]) => this.isLoaded(key)) + .map(([key, value]) => [key, Catalog.teaqlJsonValue(value, active)])); + const childrenEntryList = this.entryList(); + if (childrenEntryList.isLoaded || childrenEntryList.some(child => + (child as any)._root.hasPending((child as any).teaqlEntityKey()))) { + payload["entryList"] = Catalog.teaqlJsonValue(childrenEntryList, active); + } + return payload; + } finally { active.delete(this); } + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Catalog { + return new Catalog({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Catalog { + return new Catalog().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._entryList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Catalog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._entryList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Catalog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "entry_list": graph.sourceMembers((this as any)._entryList) + })); + for (const child of (this as any)._entryList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Catalog.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? this.version); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Catalog", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._entryList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + graph.discardRestoredFields(Catalog.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Catalog", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Catalog", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._entryList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + try { child.teaqlPreflightGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Catalog", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._entryList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._entryList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.catalog; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("catalog") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateCatalog(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("entry_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + entryList(): SmartList { + return (this as any)._entryList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated/models/Entry.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated/models/Entry.ts new file mode 100644 index 0000000000000000000000000000000000000000..01eba0fc3f28639d98b40a06ed10ac6043f6bafc --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated/models/Entry.ts @@ -0,0 +1,390 @@ +import { CheckException, integer32Error, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Catalog } from './Catalog'; + +export class Entry { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Entry", + ["id", "catalog", "name", "born_at", "touched_at", "source_ip", "last_ip", "opened_by", "changed_by", "guarded_token", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + catalog?: Catalog | string; + name?: string; + bornAt?: string; + touchedAt?: string; + sourceIp?: string; + lastIp?: string; + openedBy?: string; + changedBy?: string; + guardedToken?: string; + version?: EntityVersion; + + constructor(init?: Partial) { + Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Entry.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + Object.assign(this, fields); + if ((init as any).catalog && typeof (init as any).catalog === "object") { + this.catalog = (init as any).catalog instanceof Catalog + ? (init as any).catalog + : Catalog.fromRecord((init as any).catalog); + this.markLoaded("catalog"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Entry", id: (this as any)._ledgerId }; } + /** @internal Restore known equal scalars after the prepared graph completes. */ + private teaqlRestoreFixedValues(values: Readonly>): void { + for (const field of [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "bornAt", canonical: "born_at" }, { member: "touchedAt", canonical: "touched_at" }, { member: "sourceIp", canonical: "source_ip" }, { member: "lastIp", canonical: "last_ip" }, { member: "openedBy", canonical: "opened_by" }, { member: "changedBy", canonical: "changed_by" }, { member: "guardedToken", canonical: "guarded_token" }, { member: "version", canonical: "version" }]) { + if (Object.prototype.hasOwnProperty.call(values, field.canonical)) (this as any)[field.member] = values[field.canonical]; + } + } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Entry { + const entity = new Entry(record as Partial); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + return this.teaqlJson(new Set()); + } + + private static teaqlJsonValue(value: any, active: Set): any { + if (value === null || value === undefined) return value; + if (typeof value.teaqlJson === "function") return value.teaqlJson(active); + if (Array.isArray(value)) return Array.from(value, item => this.teaqlJsonValue(item, active)); + if (typeof value.toJSON === "function") return value.toJSON(); + if (typeof value === "object") return Object.fromEntries(Object.entries(value).map( + ([key, item]) => [key, this.teaqlJsonValue(item, active)])); + return typeof value === "bigint" ? value.toString() : value; + } + + private teaqlJson(active: Set): Record { + if (active.has(this)) return { id: this.id, version: this.version }; + active.add(this); + try { + // Only enumerable business/query data participates; runtime state is private. + const payload = Object.fromEntries(Object.entries(this).filter(([key]) => this.isLoaded(key)) + .map(([key, value]) => [key, Entry.teaqlJsonValue(value, active)])); + return payload; + } finally { active.delete(this); } + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Entry { + return new Entry({ id: String(id) } as Partial); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(id: string | number): Entry { + return new Entry().updateId(String(id)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Entry.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Entry.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "catalog": "Catalog" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Entry.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? this.version); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "catalog", canonical: "catalog" }, { member: "name", canonical: "name" }, { member: "bornAt", canonical: "born_at" }, { member: "touchedAt", canonical: "touched_at" }, { member: "sourceIp", canonical: "source_ip" }, { member: "lastIp", canonical: "last_ip" }, { member: "openedBy", canonical: "opened_by" }, { member: "changedBy", canonical: "changed_by" }, { member: "guardedToken", canonical: "guarded_token" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Entry", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + graph.discardRestoredFields(Entry.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "catalog", canonical: "catalog" }, { member: "name", canonical: "name" }, { member: "bornAt", canonical: "born_at" }, { member: "touchedAt", canonical: "touched_at" }, { member: "sourceIp", canonical: "source_ip" }, { member: "lastIp", canonical: "last_ip" }, { member: "openedBy", canonical: "opened_by" }, { member: "changedBy", canonical: "changed_by" }, { member: "guardedToken", canonical: "guarded_token" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Entry", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Entry", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + if (!parent) new MutationIntent((this as any)._comment); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Entry", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: (this as any)._root.originalVersion(this.teaqlEntityKey()) ?? (this as any).version, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "catalog": this.catalog, + "name": this.name, + "born_at": this.bornAt, + "touched_at": this.touchedAt, + "source_ip": this.sourceIp, + "last_ip": this.lastIp, + "opened_by": this.openedBy, + "changed_by": this.changedBy, + "guarded_token": this.guardedToken, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateBornAt(value: string): this { + this.bornAt = value; + this.markLoaded("bornAt"); + (this as any)._root.set(this.teaqlEntityKey(), "born_at", value); + return this; + } + + updateTouchedAt(value: string): this { + this.touchedAt = value; + this.markLoaded("touchedAt"); + (this as any)._root.set(this.teaqlEntityKey(), "touched_at", value); + return this; + } + + updateSourceIp(value: string): this { + this.sourceIp = value; + this.markLoaded("sourceIp"); + (this as any)._root.set(this.teaqlEntityKey(), "source_ip", value); + return this; + } + + updateLastIp(value: string): this { + this.lastIp = value; + this.markLoaded("lastIp"); + (this as any)._root.set(this.teaqlEntityKey(), "last_ip", value); + return this; + } + + updateOpenedBy(value: string): this { + this.openedBy = value; + this.markLoaded("openedBy"); + (this as any)._root.set(this.teaqlEntityKey(), "opened_by", value); + return this; + } + + updateChangedBy(value: string): this { + this.changedBy = value; + this.markLoaded("changedBy"); + (this as any)._root.set(this.teaqlEntityKey(), "changed_by", value); + return this; + } + + updateGuardedToken(value: string): this { + this.guardedToken = value; + this.markLoaded("guardedToken"); + (this as any)._root.set(this.teaqlEntityKey(), "guarded_token", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateCatalog(value: any): this { + this.catalog = value?.id ?? value; + this.markLoaded("catalog"); + (this as any)._root.set(this.teaqlEntityKey(), "catalog", this.catalog); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated/requests/CatalogRequest.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated/requests/CatalogRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..c978c8d22ed8105da2ae7353278f57b78d1f0667 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated/requests/CatalogRequest.ts @@ -0,0 +1,616 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Catalog } from '../models/Catalog'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class CatalogRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Catalog"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableCatalogRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableCatalogRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectEntryListWith(request: { toQuery(): SelectQuery }): this { + this.query.relationQuery( + "entryList", request.toQuery(), "id", "catalog", true, + { kind: "relation-select", method: "selectEntryListWith", relation: "entryList" }); + return this; + } + + haveEntries(): this { + return this.withEntryListMatching({ + toQuery: () => new SelectQuery("Entry"), + }); + } + + haveNoEntries(): this { + return this.withoutEntryListMatching({ + toQuery: () => new SelectQuery("Entry"), + }); + } + + withEntryListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "catalog", + }, + }, + }); + return this; + } + + withoutEntryListMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "catalog", + }, + }, + }); + return this; + } + + countEntries(): this { + return this.countEntriesAs("countEntries"); + } + + countEntriesAs(alias: string): this { + const query = new SelectQuery("Entry").filter({ version: { "$gte": 1 } }); + this.countEntriesWith(alias, { toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countEntriesAs", relation: "entryList", alias }; + return this; + } + + countEntriesWith(alias: string, child: { toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("entryList", alias, query, true, + { kind: "relation-count", method: "countEntriesWith", relation: "entryList", alias }); + return this; + } + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this.query.groupByItems.length > 0) throw new Error("Grouped projections require executeForRows"); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Catalog + ? row + : Catalog.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const aggregateOnly = pageQuery.aggregateItems.length > 0; + const data = new SmartList(aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Catalog + ? row + : Catalog.fromRecord(row as Record, new EntityRoot()))); + if (aggregateOnly && rows[0]) Object.assign(data.aggregations, rows[0]); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + if (preparedQuery.aggregateItems.length > 0 || preparedQuery.groupByItems.length > 0) { + throw new Error("Entity streams require entity rows; use a record or aggregation query"); + } + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Catalog + ? entity + : Catalog.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableCatalogRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Catalog { + this.ensureIntent(); + return new Catalog(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/generated/requests/EntryRequest.ts b/source/teaql-ts/examples/context-derived/fixture/src/generated/requests/EntryRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..e099f3ff6c8fd64b1e12c3497f3c63c85b860020 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/generated/requests/EntryRequest.ts @@ -0,0 +1,1343 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { Entry } from '../models/Entry'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class EntryRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("Entry"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableEntryRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableEntryRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "catalog", "name", "bornAt", "touchedAt", "sourceIp", "lastIp", "openedBy", "changedBy", "guardedToken", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectBornAt(): this { + this.query.select(["bornAt"]); + return this; + } + + selectTouchedAt(): this { + this.query.select(["touchedAt"]); + return this; + } + + selectSourceIp(): this { + this.query.select(["sourceIp"]); + return this; + } + + selectLastIp(): this { + this.query.select(["lastIp"]); + return this; + } + + selectOpenedBy(): this { + this.query.select(["openedBy"]); + return this; + } + + selectChangedBy(): this { + this.query.select(["changedBy"]); + return this; + } + + selectGuardedToken(): this { + this.query.select(["guardedToken"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectCatalogWith(request: { toQuery(): SelectQuery }): this { + this.query.select(["catalog"]); + this.query.relationQuery( + "catalog", request.toQuery(), "catalog", "id", false, + { kind: "relation-select", method: "selectCatalogWith", relation: "catalog" }); + return this; + } + + withCatalogMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "catalog": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutCatalogMatching(request: { toQuery(): SelectQuery }): this { + this.filters.push({ + "catalog": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: any): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: any): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: any[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: any[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: any): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: any): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: any): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: any, upper: any): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByCatalog(val: any): this { + this.filters.push({ "catalog": { "$eq": val } }); + return this; + } + + filterByCatalogIn(...vals: any[]): this { + this.filters.push({ "catalog": { "$in": vals } }); + return this; + } + + withCatalogIsKnown(): this { + this.filters.push({ "catalog": { "$isNull": false } }); + return this; + } + + withCatalogIsUnknown(): this { + this.filters.push({ "catalog": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: any): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: any[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: any[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: any): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: any): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: any): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: any, upper: any): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withBornAtIs(val: any): this { + this.filters.push({ "bornAt": { "$eq": val } }); + return this; + } + + withBornAtIsNot(val: any): this { + this.filters.push({ "bornAt": { "$ne": val } }); + return this; + } + + withBornAtIn(...vals: any[]): this { + this.filters.push({ "bornAt": { "$in": vals } }); + return this; + } + + withBornAtNotIn(...vals: any[]): this { + this.filters.push({ "bornAt": { "$notIn": vals } }); + return this; + } + + withBornAtGreaterThan(val: any): this { + this.filters.push({ "bornAt": { "$gt": val } }); + return this; + } + + withBornAtGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "bornAt": { "$gte": val } }); + return this; + } + + withBornAtLessThan(val: any): this { + this.filters.push({ "bornAt": { "$lt": val } }); + return this; + } + + withBornAtLessThanOrEqualTo(val: any): this { + this.filters.push({ "bornAt": { "$lte": val } }); + return this; + } + + withBornAtBetween(lower: any, upper: any): this { + this.filters.push({ "bornAt": { "$between": [lower, upper] } }); + return this; + } + + withBornAtIsKnown(): this { + this.filters.push({ "bornAt": { "$isNull": false } }); + return this; + } + + withBornAtIsUnknown(): this { + this.filters.push({ "bornAt": { "$isNull": true } }); + return this; + } + + withTouchedAtIs(val: any): this { + this.filters.push({ "touchedAt": { "$eq": val } }); + return this; + } + + withTouchedAtIsNot(val: any): this { + this.filters.push({ "touchedAt": { "$ne": val } }); + return this; + } + + withTouchedAtIn(...vals: any[]): this { + this.filters.push({ "touchedAt": { "$in": vals } }); + return this; + } + + withTouchedAtNotIn(...vals: any[]): this { + this.filters.push({ "touchedAt": { "$notIn": vals } }); + return this; + } + + withTouchedAtGreaterThan(val: any): this { + this.filters.push({ "touchedAt": { "$gt": val } }); + return this; + } + + withTouchedAtGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "touchedAt": { "$gte": val } }); + return this; + } + + withTouchedAtLessThan(val: any): this { + this.filters.push({ "touchedAt": { "$lt": val } }); + return this; + } + + withTouchedAtLessThanOrEqualTo(val: any): this { + this.filters.push({ "touchedAt": { "$lte": val } }); + return this; + } + + withTouchedAtBetween(lower: any, upper: any): this { + this.filters.push({ "touchedAt": { "$between": [lower, upper] } }); + return this; + } + + withTouchedAtIsKnown(): this { + this.filters.push({ "touchedAt": { "$isNull": false } }); + return this; + } + + withTouchedAtIsUnknown(): this { + this.filters.push({ "touchedAt": { "$isNull": true } }); + return this; + } + + withSourceIpContaining(val: string): this { + this.filters.push({ "sourceIp": { "$contains": val } }); + return this; + } + + withSourceIpIs(val: string): this { + this.filters.push({ "sourceIp": { "$eq": val } }); + return this; + } + + withSourceIpIsNot(val: any): this { + this.filters.push({ "sourceIp": { "$ne": val } }); + return this; + } + + withSourceIpIn(...vals: any[]): this { + this.filters.push({ "sourceIp": { "$in": vals } }); + return this; + } + + withSourceIpNotIn(...vals: any[]): this { + this.filters.push({ "sourceIp": { "$notIn": vals } }); + return this; + } + + withSourceIpGreaterThan(val: any): this { + this.filters.push({ "sourceIp": { "$gt": val } }); + return this; + } + + withSourceIpGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "sourceIp": { "$gte": val } }); + return this; + } + + withSourceIpLessThan(val: any): this { + this.filters.push({ "sourceIp": { "$lt": val } }); + return this; + } + + withSourceIpLessThanOrEqualTo(val: any): this { + this.filters.push({ "sourceIp": { "$lte": val } }); + return this; + } + + withSourceIpBetween(lower: any, upper: any): this { + this.filters.push({ "sourceIp": { "$between": [lower, upper] } }); + return this; + } + + withSourceIpIsKnown(): this { + this.filters.push({ "sourceIp": { "$isNull": false } }); + return this; + } + + withSourceIpIsUnknown(): this { + this.filters.push({ "sourceIp": { "$isNull": true } }); + return this; + } + withSourceIpNotContaining(val: string): this { + this.filters.push({ "sourceIp": { "$notContains": val } }); + return this; + } + + withSourceIpStartingWith(val: string): this { + this.filters.push({ "sourceIp": { "$startsWith": val } }); + return this; + } + + withSourceIpNotStartingWith(val: string): this { + this.filters.push({ "sourceIp": { "$notStartsWith": val } }); + return this; + } + + withSourceIpEndingWith(val: string): this { + this.filters.push({ "sourceIp": { "$endsWith": val } }); + return this; + } + + withSourceIpNotEndingWith(val: string): this { + this.filters.push({ "sourceIp": { "$notEndsWith": val } }); + return this; + } + + withSourceIpSoundingLike(val: string): this { + this.filters.push({ "sourceIp": { "$soundLike": val } }); + return this; + } + + withLastIpContaining(val: string): this { + this.filters.push({ "lastIp": { "$contains": val } }); + return this; + } + + withLastIpIs(val: string): this { + this.filters.push({ "lastIp": { "$eq": val } }); + return this; + } + + withLastIpIsNot(val: any): this { + this.filters.push({ "lastIp": { "$ne": val } }); + return this; + } + + withLastIpIn(...vals: any[]): this { + this.filters.push({ "lastIp": { "$in": vals } }); + return this; + } + + withLastIpNotIn(...vals: any[]): this { + this.filters.push({ "lastIp": { "$notIn": vals } }); + return this; + } + + withLastIpGreaterThan(val: any): this { + this.filters.push({ "lastIp": { "$gt": val } }); + return this; + } + + withLastIpGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "lastIp": { "$gte": val } }); + return this; + } + + withLastIpLessThan(val: any): this { + this.filters.push({ "lastIp": { "$lt": val } }); + return this; + } + + withLastIpLessThanOrEqualTo(val: any): this { + this.filters.push({ "lastIp": { "$lte": val } }); + return this; + } + + withLastIpBetween(lower: any, upper: any): this { + this.filters.push({ "lastIp": { "$between": [lower, upper] } }); + return this; + } + + withLastIpIsKnown(): this { + this.filters.push({ "lastIp": { "$isNull": false } }); + return this; + } + + withLastIpIsUnknown(): this { + this.filters.push({ "lastIp": { "$isNull": true } }); + return this; + } + withLastIpNotContaining(val: string): this { + this.filters.push({ "lastIp": { "$notContains": val } }); + return this; + } + + withLastIpStartingWith(val: string): this { + this.filters.push({ "lastIp": { "$startsWith": val } }); + return this; + } + + withLastIpNotStartingWith(val: string): this { + this.filters.push({ "lastIp": { "$notStartsWith": val } }); + return this; + } + + withLastIpEndingWith(val: string): this { + this.filters.push({ "lastIp": { "$endsWith": val } }); + return this; + } + + withLastIpNotEndingWith(val: string): this { + this.filters.push({ "lastIp": { "$notEndsWith": val } }); + return this; + } + + withLastIpSoundingLike(val: string): this { + this.filters.push({ "lastIp": { "$soundLike": val } }); + return this; + } + + withOpenedByContaining(val: string): this { + this.filters.push({ "openedBy": { "$contains": val } }); + return this; + } + + withOpenedByIs(val: string): this { + this.filters.push({ "openedBy": { "$eq": val } }); + return this; + } + + withOpenedByIsNot(val: any): this { + this.filters.push({ "openedBy": { "$ne": val } }); + return this; + } + + withOpenedByIn(...vals: any[]): this { + this.filters.push({ "openedBy": { "$in": vals } }); + return this; + } + + withOpenedByNotIn(...vals: any[]): this { + this.filters.push({ "openedBy": { "$notIn": vals } }); + return this; + } + + withOpenedByGreaterThan(val: any): this { + this.filters.push({ "openedBy": { "$gt": val } }); + return this; + } + + withOpenedByGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "openedBy": { "$gte": val } }); + return this; + } + + withOpenedByLessThan(val: any): this { + this.filters.push({ "openedBy": { "$lt": val } }); + return this; + } + + withOpenedByLessThanOrEqualTo(val: any): this { + this.filters.push({ "openedBy": { "$lte": val } }); + return this; + } + + withOpenedByBetween(lower: any, upper: any): this { + this.filters.push({ "openedBy": { "$between": [lower, upper] } }); + return this; + } + + withOpenedByIsKnown(): this { + this.filters.push({ "openedBy": { "$isNull": false } }); + return this; + } + + withOpenedByIsUnknown(): this { + this.filters.push({ "openedBy": { "$isNull": true } }); + return this; + } + withOpenedByNotContaining(val: string): this { + this.filters.push({ "openedBy": { "$notContains": val } }); + return this; + } + + withOpenedByStartingWith(val: string): this { + this.filters.push({ "openedBy": { "$startsWith": val } }); + return this; + } + + withOpenedByNotStartingWith(val: string): this { + this.filters.push({ "openedBy": { "$notStartsWith": val } }); + return this; + } + + withOpenedByEndingWith(val: string): this { + this.filters.push({ "openedBy": { "$endsWith": val } }); + return this; + } + + withOpenedByNotEndingWith(val: string): this { + this.filters.push({ "openedBy": { "$notEndsWith": val } }); + return this; + } + + withOpenedBySoundingLike(val: string): this { + this.filters.push({ "openedBy": { "$soundLike": val } }); + return this; + } + + withChangedByContaining(val: string): this { + this.filters.push({ "changedBy": { "$contains": val } }); + return this; + } + + withChangedByIs(val: string): this { + this.filters.push({ "changedBy": { "$eq": val } }); + return this; + } + + withChangedByIsNot(val: any): this { + this.filters.push({ "changedBy": { "$ne": val } }); + return this; + } + + withChangedByIn(...vals: any[]): this { + this.filters.push({ "changedBy": { "$in": vals } }); + return this; + } + + withChangedByNotIn(...vals: any[]): this { + this.filters.push({ "changedBy": { "$notIn": vals } }); + return this; + } + + withChangedByGreaterThan(val: any): this { + this.filters.push({ "changedBy": { "$gt": val } }); + return this; + } + + withChangedByGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "changedBy": { "$gte": val } }); + return this; + } + + withChangedByLessThan(val: any): this { + this.filters.push({ "changedBy": { "$lt": val } }); + return this; + } + + withChangedByLessThanOrEqualTo(val: any): this { + this.filters.push({ "changedBy": { "$lte": val } }); + return this; + } + + withChangedByBetween(lower: any, upper: any): this { + this.filters.push({ "changedBy": { "$between": [lower, upper] } }); + return this; + } + + withChangedByIsKnown(): this { + this.filters.push({ "changedBy": { "$isNull": false } }); + return this; + } + + withChangedByIsUnknown(): this { + this.filters.push({ "changedBy": { "$isNull": true } }); + return this; + } + withChangedByNotContaining(val: string): this { + this.filters.push({ "changedBy": { "$notContains": val } }); + return this; + } + + withChangedByStartingWith(val: string): this { + this.filters.push({ "changedBy": { "$startsWith": val } }); + return this; + } + + withChangedByNotStartingWith(val: string): this { + this.filters.push({ "changedBy": { "$notStartsWith": val } }); + return this; + } + + withChangedByEndingWith(val: string): this { + this.filters.push({ "changedBy": { "$endsWith": val } }); + return this; + } + + withChangedByNotEndingWith(val: string): this { + this.filters.push({ "changedBy": { "$notEndsWith": val } }); + return this; + } + + withChangedBySoundingLike(val: string): this { + this.filters.push({ "changedBy": { "$soundLike": val } }); + return this; + } + + withGuardedTokenContaining(val: string): this { + this.filters.push({ "guardedToken": { "$contains": val } }); + return this; + } + + withGuardedTokenIs(val: string): this { + this.filters.push({ "guardedToken": { "$eq": val } }); + return this; + } + + withGuardedTokenIsNot(val: any): this { + this.filters.push({ "guardedToken": { "$ne": val } }); + return this; + } + + withGuardedTokenIn(...vals: any[]): this { + this.filters.push({ "guardedToken": { "$in": vals } }); + return this; + } + + withGuardedTokenNotIn(...vals: any[]): this { + this.filters.push({ "guardedToken": { "$notIn": vals } }); + return this; + } + + withGuardedTokenGreaterThan(val: any): this { + this.filters.push({ "guardedToken": { "$gt": val } }); + return this; + } + + withGuardedTokenGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "guardedToken": { "$gte": val } }); + return this; + } + + withGuardedTokenLessThan(val: any): this { + this.filters.push({ "guardedToken": { "$lt": val } }); + return this; + } + + withGuardedTokenLessThanOrEqualTo(val: any): this { + this.filters.push({ "guardedToken": { "$lte": val } }); + return this; + } + + withGuardedTokenBetween(lower: any, upper: any): this { + this.filters.push({ "guardedToken": { "$between": [lower, upper] } }); + return this; + } + + withGuardedTokenIsKnown(): this { + this.filters.push({ "guardedToken": { "$isNull": false } }); + return this; + } + + withGuardedTokenIsUnknown(): this { + this.filters.push({ "guardedToken": { "$isNull": true } }); + return this; + } + withGuardedTokenNotContaining(val: string): this { + this.filters.push({ "guardedToken": { "$notContains": val } }); + return this; + } + + withGuardedTokenStartingWith(val: string): this { + this.filters.push({ "guardedToken": { "$startsWith": val } }); + return this; + } + + withGuardedTokenNotStartingWith(val: string): this { + this.filters.push({ "guardedToken": { "$notStartsWith": val } }); + return this; + } + + withGuardedTokenEndingWith(val: string): this { + this.filters.push({ "guardedToken": { "$endsWith": val } }); + return this; + } + + withGuardedTokenNotEndingWith(val: string): this { + this.filters.push({ "guardedToken": { "$notEndsWith": val } }); + return this; + } + + withGuardedTokenSoundingLike(val: string): this { + this.filters.push({ "guardedToken": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: any): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: any): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: any[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: any[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: any): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: any): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: any): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: any, upper: any): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByBornAtAscending(): this { + this.query.orderBy("bornAt", "asc"); + return this; + } + + orderByBornAtDescending(): this { + this.query.orderBy("bornAt", "desc"); + return this; + } + + orderByTouchedAtAscending(): this { + this.query.orderBy("touchedAt", "asc"); + return this; + } + + orderByTouchedAtDescending(): this { + this.query.orderBy("touchedAt", "desc"); + return this; + } + + orderBySourceIpAscending(): this { + this.query.orderBy("sourceIp", "asc"); + return this; + } + + orderBySourceIpDescending(): this { + this.query.orderBy("sourceIp", "desc"); + return this; + } + + orderByLastIpAscending(): this { + this.query.orderBy("lastIp", "asc"); + return this; + } + + orderByLastIpDescending(): this { + this.query.orderBy("lastIp", "desc"); + return this; + } + + orderByOpenedByAscending(): this { + this.query.orderBy("openedBy", "asc"); + return this; + } + + orderByOpenedByDescending(): this { + this.query.orderBy("openedBy", "desc"); + return this; + } + + orderByChangedByAscending(): this { + this.query.orderBy("changedBy", "asc"); + return this; + } + + orderByChangedByDescending(): this { + this.query.orderBy("changedBy", "desc"); + return this; + } + + orderByGuardedTokenAscending(): this { + this.query.orderBy("guardedToken", "asc"); + return this; + } + + orderByGuardedTokenDescending(): this { + this.query.orderBy("guardedToken", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id"); // In TS we don't alias group by yet natively + return this; + } + groupByCatalog(): this { + this.query.groupBy("catalog"); + return this; + } + + groupByCatalogAs(retName: string): this { + this.query.groupBy("catalog"); // In TS we don't alias group by yet natively + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name"); // In TS we don't alias group by yet natively + return this; + } + groupByBornAt(): this { + this.query.groupBy("bornAt"); + return this; + } + + groupByBornAtAs(retName: string): this { + this.query.groupBy("bornAt"); // In TS we don't alias group by yet natively + return this; + } + groupByTouchedAt(): this { + this.query.groupBy("touchedAt"); + return this; + } + + groupByTouchedAtAs(retName: string): this { + this.query.groupBy("touchedAt"); // In TS we don't alias group by yet natively + return this; + } + groupBySourceIp(): this { + this.query.groupBy("sourceIp"); + return this; + } + + groupBySourceIpAs(retName: string): this { + this.query.groupBy("sourceIp"); // In TS we don't alias group by yet natively + return this; + } + groupByLastIp(): this { + this.query.groupBy("lastIp"); + return this; + } + + groupByLastIpAs(retName: string): this { + this.query.groupBy("lastIp"); // In TS we don't alias group by yet natively + return this; + } + groupByOpenedBy(): this { + this.query.groupBy("openedBy"); + return this; + } + + groupByOpenedByAs(retName: string): this { + this.query.groupBy("openedBy"); // In TS we don't alias group by yet natively + return this; + } + groupByChangedBy(): this { + this.query.groupBy("changedBy"); + return this; + } + + groupByChangedByAs(retName: string): this { + this.query.groupBy("changedBy"); // In TS we don't alias group by yet natively + return this; + } + groupByGuardedToken(): this { + this.query.groupBy("guardedToken"); + return this; + } + + groupByGuardedTokenAs(retName: string): this { + this.query.groupBy("guardedToken"); // In TS we don't alias group by yet natively + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version"); // In TS we don't alias group by yet natively + return this; + } + + // --- Facets --- + facetByCatalogAs( + facetName: string, + request: { toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "catalog", request, includeAllFacets, + { kind: "facet", method: "facetByCatalogAs", relation: "catalog", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this.query.groupByItems.length > 0) throw new Error("Grouped projections require executeForRows"); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Entry + ? row + : Entry.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const aggregateOnly = pageQuery.aggregateItems.length > 0; + const data = new SmartList(aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof Entry + ? row + : Entry.fromRecord(row as Record, new EntityRoot()))); + if (aggregateOnly && rows[0]) Object.assign(data.aggregations, rows[0]); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + if (preparedQuery.aggregateItems.length > 0 || preparedQuery.groupByItems.length > 0) { + throw new Error("Entity streams require entity rows; use a record or aggregation query"); + } + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof Entry + ? entity + : Entry.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableEntryRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + newEntity(context: UserContext): Entry { + this.ensureIntent(); + return new Entry(); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/runtime-module.ts b/source/teaql-ts/examples/context-derived/fixture/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..6ff82f73e92842921c013bc37090147eb2717b08 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/runtime-module.ts @@ -0,0 +1,101 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ContextFix, ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "Catalog": Object.freeze({ + entityType: "Catalog", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "Entry": Object.freeze({ + entityType: "Entry", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "catalog": Object.freeze({ canonicalName: "catalog", wireName: "catalog", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "born_at": Object.freeze({ canonicalName: "born_at", wireName: "bornAt", aliases: Object.freeze([] as string[]) }), + "touched_at": Object.freeze({ canonicalName: "touched_at", wireName: "touchedAt", aliases: Object.freeze([] as string[]) }), + "source_ip": Object.freeze({ canonicalName: "source_ip", wireName: "sourceIp", aliases: Object.freeze([] as string[]) }), + "last_ip": Object.freeze({ canonicalName: "last_ip", wireName: "lastIp", aliases: Object.freeze([] as string[]) }), + "opened_by": Object.freeze({ canonicalName: "opened_by", wireName: "openedBy", aliases: Object.freeze([] as string[]) }), + "changed_by": Object.freeze({ canonicalName: "changed_by", wireName: "changedBy", aliases: Object.freeze([] as string[]) }), + "guarded_token": Object.freeze({ canonicalName: "guarded_token", wireName: "guardedToken", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "Catalog": { + checkAndFix(context, mutation, results) { + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "Entry": { + checkAndFix(context, mutation, results) { + if (mutation.action === "Create") { + ContextFix.apply(context, mutation, "born_at", "now", []); + } + + if (mutation.action === "Create") { + ContextFix.apply(context, mutation, "touched_at", "now", []); + } + if (mutation.action === "Update") { + ContextFix.apply(context, mutation, "touched_at", "now", []); + } + + + + + + if (mutation.action === "Create") { + ContextFix.apply(context, mutation, "guarded_token", "uniStr", [""]); + } + + + if ((mutation.action === "Create" && mutation.payload["catalog"] === undefined) || mutation.payload["catalog"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("catalog") }); + + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["born_at"] === undefined) || mutation.payload["born_at"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("born_at") }); + + if ((mutation.action === "Create" && mutation.payload["touched_at"] === undefined) || mutation.payload["touched_at"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("touched_at") }); + + if ((mutation.action === "Create" && mutation.payload["source_ip"] === undefined) || mutation.payload["source_ip"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("source_ip") }); + if (mutation.payload["source_ip"] != null && [...String(mutation.payload["source_ip"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("source_ip"), inputValue: mutation.payload["source_ip"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["last_ip"] === undefined) || mutation.payload["last_ip"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("last_ip") }); + if (mutation.payload["last_ip"] != null && [...String(mutation.payload["last_ip"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("last_ip"), inputValue: mutation.payload["last_ip"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["opened_by"] === undefined) || mutation.payload["opened_by"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("opened_by") }); + if (mutation.payload["opened_by"] != null && [...String(mutation.payload["opened_by"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("opened_by"), inputValue: mutation.payload["opened_by"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["changed_by"] === undefined) || mutation.payload["changed_by"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("changed_by") }); + if (mutation.payload["changed_by"] != null && [...String(mutation.payload["changed_by"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("changed_by"), inputValue: mutation.payload["changed_by"], systemValue: 100 }); + + if ((mutation.action === "Create" && mutation.payload["guarded_token"] === undefined) || mutation.payload["guarded_token"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("guarded_token") }); + if (mutation.payload["guarded_token"] != null && [...String(mutation.payload["guarded_token"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("guarded_token"), inputValue: mutation.payload["guarded_token"], systemValue: 100 }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "Catalog", id: "1", values: { "name": "Catalog" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/teaql-node-sql.ts b/source/teaql-ts/examples/context-derived/fixture/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..a71c590593e2129ae06fd68ef8230a96e4ed302c --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/teaql-node-sql.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"Catalog": { + table: "catalog_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"entryList": { targetEntity: "Entry", localKey: "id", foreignKey: "catalog", many: true }} +}, +"Entry": { + table: "entry_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "catalog": { columnName: "catalog", modelName: "catalog", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "bornAt": { columnName: "born_at", modelName: "born_at", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false, createFunction: "now" }, "touchedAt": { columnName: "touched_at", modelName: "touched_at", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false, createFunction: "now", updateFunction: "now" }, "sourceIp": { columnName: "source_ip", modelName: "source_ip", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "lastIp": { columnName: "last_ip", modelName: "last_ip", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "openedBy": { columnName: "opened_by", modelName: "opened_by", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "changedBy": { columnName: "changed_by", modelName: "changed_by", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "guardedToken": { columnName: "guarded_token", modelName: "guarded_token", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false, createFunction: "uniStr" }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"catalog": { targetEntity: "Catalog", localKey: "catalog", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/context-derived/fixture/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/src/teaql-ts.ts b/source/teaql-ts/examples/context-derived/fixture/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..00fbea5d5dce69d5562913a07a7a6b5203634cde --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/src/teaql-ts.ts @@ -0,0 +1,502 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, ContextFix, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + mutation = this.checkAndFixMutation(request); + const normalized = request.graphSession?.normalizePreparedMutation(mutation); + if (normalized?.restore) { + this.afterGraphCommit(normalized.restore); + this.afterGraphRollback(normalized.restore); + } + if (normalized?.empty) return mutation; + request.graphSession?.recordPreparedMutation(); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + ContextFix.run(this.userContext, mutation, schema, () => checker.checkAndFix(this.userContext, mutation, results)); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) { + const undo = ContextFix.captureUndo(mutation, schema); + if (request.graphSession && undo) this.graphRollbackActions.push(undo); + for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + } + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/teaql-i18n.json b/source/teaql-ts/examples/context-derived/fixture/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..c64cb98a2905af46c21bf7264db14849d48f3602 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/teaql-i18n.json @@ -0,0 +1,112 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "entity.catalog": "Catalog", + "property.entry.name": "Name", + "property.catalog.id": "Id", + "property.entry.touchedAt": "Touched At", + "property.entry.lastIp": "Last Ip", + "property.entry.id": "Id", + "property.entry.changedBy": "Changed By", + "property.catalog.name": "Name", + "property.catalog.version": "Version", + "property.entry.sourceIp": "Source Ip", + "property.entry.version": "Version", + "property.entry.openedBy": "Opened By", + "entity.entry": "Entry", + "property.entry.guardedToken": "Guarded Token", + "property.entry.bornAt": "Born At", + "property.entry.catalog": "Catalog" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/teaql/model-provenance.json b/source/teaql-ts/examples/context-derived/fixture/teaql/model-provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..caf9b5b85553931504d96f4fa3c77664ebf2818c --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/teaql/model-provenance.json @@ -0,0 +1 @@ +{"schemaVersion":1,"modelUuid":null,"revisionHash":null,"generatorVersion":"3aac056d"} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/fixture/tsconfig.json b/source/teaql-ts/examples/context-derived/fixture/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/context-derived/fixture/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/context-derived/verify-local.cjs b/source/teaql-ts/examples/context-derived/verify-local.cjs new file mode 100644 index 0000000000000000000000000000000000000000..0d1b1b89509baf1d46f8fb57f7547c4b3bbf7437 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/verify-local.cjs @@ -0,0 +1,75 @@ +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),crypto=require('node:crypto'),cp=require('node:child_process'),assert=require('node:assert/strict'); +const {createOwnedRunner,ownedBytes}=require('../fix-e-alignment/owned-command.cjs'); +const repo=path.resolve(__dirname,'../..'),fixture=path.join(__dirname,'fixture'),sha=bytes=>crypto.createHash('sha256').update(bytes).digest('hex'); +const requested=process.env.TEAQL_CONTEXT_FIX_EVIDENCE_DIR; +const output=requested?path.resolve(requested):fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-context-evidence-')); +if(requested){assert(!fs.existsSync(output),'use a new evidence directory');fs.mkdirSync(output,{recursive:true});} +const scratch=fs.mkdtempSync(path.join(os.tmpdir(),'teaql-ts-context-build-')),runner=createOwnedRunner(); +const report={schema:'teaql.typescript-context-derived-mutation/v1',passed:false,rounds:[],publicPublication:false,runtimeSource:path.join(repo,'src')}; +function inputs(){ + const bytes=fs.readFileSync(path.join(fixture,'generated-files.json')),files=JSON.parse(bytes); + const actual=[]; + function walk(directory){for(const name of fs.readdirSync(directory)){ + const file=path.join(directory,name),stat=fs.lstatSync(file);assert(!stat.isSymbolicLink()); + if(stat.isDirectory())walk(file);else{assert(stat.isFile());actual.push(path.relative(fixture,file));} + }} + walk(fixture); + assert.deepEqual(actual.sort(),[...Object.keys(files),'model.xml','generated-files.json'].sort(),'unexpected generated fixture input'); + for(const[name,hash]of Object.entries(files)){ + assert(!path.isAbsolute(name)&&!name.split('/').includes('..')); + const file=path.join(fixture,name);assert.equal(fs.realpathSync(file),file);assert.equal(sha(fs.readFileSync(file)),hash,name); + } + return{files,manifestSha256:sha(bytes),modelSha256:sha(fs.readFileSync(path.join(fixture,'model.xml')))}; +} +function sourceHash(){ + const hash=crypto.createHash('sha256'); + function walk(directory){for(const name of fs.readdirSync(directory).sort()){ + const file=path.join(directory,name),stat=fs.lstatSync(file);assert(!stat.isSymbolicLink()); + if(stat.isDirectory())walk(file);else{hash.update(path.relative(repo,file)+'\0');hash.update(fs.readFileSync(file));} + }} + walk(path.join(repo,'src')); + for(const name of ['package.json','package-lock.json','tsconfig.json']){hash.update(name+'\0');hash.update(fs.readFileSync(path.join(repo,name)));} + return hash.digest('hex'); +} +async function main(){ + try{ + const disk=fs.statfsSync(scratch);assert(disk.bavail*disk.bsize>2*1024**3); + report.fixture=inputs();report.sourceSha256=sourceHash();report.sourceCommit=cp.execFileSync('git',['-C',repo,'rev-parse','HEAD']).toString().trim(); + report.applicationSha256=sha(fs.readFileSync(path.join(__dirname,'verify.test.ts'))); + assert(fs.existsSync(path.join(repo,'node_modules/jest/bin/jest.js')),'run npm ci at the runtime root first'); + const tsconfig=path.join(scratch,'tsconfig.json'),config=path.join(scratch,'jest.cjs'); + fs.writeFileSync(tsconfig,JSON.stringify({extends:path.join(repo,'tsconfig.json'),compilerOptions:{types:['node','jest'], + typeRoots:[path.join(repo,'node_modules/@types')],baseUrl:repo,paths:{'teaql-ts':[path.join(repo,'src/index.ts')], + 'teaql-ts/*':[path.join(repo,'src/*')],'context-generated/*':[path.join(fixture,'src/*')]}}})); + fs.writeFileSync(config,'module.exports='+JSON.stringify({rootDir:repo,roots:[__dirname],testEnvironment:'node', + testMatch:['**/examples/context-derived/verify.test.ts'],moduleNameMapper:{'^teaql-ts$':path.join(repo,'src/index.ts'), + '^teaql-ts/(.*)$':path.join(repo,'src/$1'),'^context-generated/(.*)$':path.join(fixture,'src/$1')}, + transform:{'^.+\\.tsx?$':['ts-jest',{tsconfig}]}})+';\n'); + for(const round of[1,2]){ + const command=[process.execPath,path.join(repo,'node_modules/jest/bin/jest.js'),'--config',config,'--runInBand','--cacheDirectory',path.join(scratch,'jest')]; + const file=path.join(output,'round-'+round+'.log'),fd=fs.openSync(file,'wx');let result; + try{result=await runner.run(command,{cwd:repo,timeout:120000,env:{...process.env, + TEAQL_EXPECTED_RUNTIME_ENTRY:path.join(repo,'src/index.ts'),TEAQL_CONTEXT_FIX_DB:path.join(output,'fixture')},stdio:['ignore',fd,fd]});} + finally{fs.closeSync(fd);} + const bytes=fs.readFileSync(file),rows=[...bytes.toString().matchAll(/^TS_CONTEXT_FIX_CASE=(.+)$/gm)].map(match=>JSON.parse(match[1])); + report.rounds.push({round,command,exitCode:result.status,logSha256:sha(bytes),observations:rows}); + assert(!result.error&&!result.signal&&result.status===0,bytes.toString().slice(-7000)); + assert.deepEqual(rows.map(row=>row.provider).sort(),['file','sqlite']); + for(const row of rows){assert.equal(row.passed,true);assert.equal(row.noOpProviderCalls,0);assert.equal(row.failedCheckProviderCalls,0);assert.equal(row.updateAudits,1);assert.equal(row.objectLocation,true);assert.equal(row.graphRollback,true);} + assert.deepEqual(inputs(),report.fixture);assert.equal(sourceHash(),report.sourceSha256); + } + report.sameDatabase=true;report.stores={}; + for(const name of ['fixture.sqlite','fixture.json'])report.stores[name]=sha(fs.readFileSync(path.join(output,name))); + report.passed=true; + }catch(error){report.error=error.stack;process.exitCode=1;console.error(error.stack);} + finally{ + report.disposedOwnedBytes=runner.safeToClean?ownedBytes(scratch):0; + if(runner.safeToClean)fs.rmSync(scratch,{recursive:true});else report.unsafeBuildRetention=scratch; + report.scratchRemoved=!fs.existsSync(scratch);runner.dispose(); + fs.writeFileSync(path.join(output,'receipt.json'),JSON.stringify(report,null,2)+'\n'); + console.log(JSON.stringify({passed:report.passed,rounds:report.rounds.length,evidence:output})); + if(!requested&&report.passed&&report.scratchRemoved)fs.rmSync(output,{recursive:true}); + } +} +main().catch(error=>{console.error(error.stack);process.exitCode=1;}); diff --git a/source/teaql-ts/examples/context-derived/verify.test.ts b/source/teaql-ts/examples/context-derived/verify.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..5f357436a61786713b7840a01f31293c30b89d31 --- /dev/null +++ b/source/teaql-ts/examples/context-derived/verify.test.ts @@ -0,0 +1,139 @@ +import {CheckException, ContextFix, ContextFixResolver, FixedBusinessClock, RuntimeModule, + UserContext, checkResultToWire} from '../../src'; +import {Q} from 'context-generated/generated/Q'; +import {E} from 'context-generated/generated/E'; +import {Entry} from 'context-generated/generated/models/Entry'; +import {SQLiteTeaQLClient} from 'context-generated/teaql-node-sqlite'; +import {TeaQLClient} from 'context-generated/teaql-ts'; +import {GENERATED_RUNTIME_MODULE} from 'context-generated/runtime-module'; + +const A = new Date('2033-01-01T00:00:00Z'), B = new Date('2033-01-02T00:00:00Z'), C = new Date('2033-01-03T00:00:00Z'); +const milliseconds = (value:unknown) => value instanceof Date ? value.getTime() : new Date(String(value)).getTime(); +function located(error:unknown,path:string):CheckException { + expect(error).toBeInstanceOf(CheckException); + const failure=error as CheckException; + expect(failure.violations.some(result=>result.entityType && checkResultToWire(result).instancePath===path)).toBe(true); + return failure; +} +async function rejected(work:()=>Promise,path:string):Promise{ + try{await work();throw new Error('expected a failed check');}catch(error){return located(error,path);} +} + +test.each(['sqlite','file'] as const)('generated Context Fix: %s provider',async kind=>{ + expect(require.resolve('teaql-ts')).toBe(process.env.TEAQL_EXPECTED_RUNTIME_ENTRY); + const base=process.env.TEAQL_CONTEXT_FIX_DB;if(!base)throw new Error('use verify-local.cjs for isolated retained databases'); + const context=new UserContext().withBusinessClock(new FixedBusinessClock(A)); + const client=kind==='sqlite'?new SQLiteTeaQLClient(base+'.sqlite').setDiagnosticSQLLogSink(undefined) + :new TeaQLClient(base+'.json').install(GENERATED_RUNTIME_MODULE); + client.setUserContext(context);context.insertResource('dataService',client); + try{ + await context.ensureSchema(); + const schema=GENERATED_RUNTIME_MODULE.schemas.Entry; + for(const [name,column] of Object.entries(schema.columns)){ + const field=column.modelName??name; + if(['source_ip','opened_by','last_ip','changed_by'].includes(field)){ + column.createFunction='identity';if(field==='last_ip'||field==='changed_by')column.updateFunction='identity'; + } + } + const generated=GENERATED_RUNTIME_MODULE.checkers.Entry; + let normalizedName='first'; + client.install(new RuntimeModule({}, {Entry:{checkAndFix(ctx,mutation,results){ + for(const field of ['source_ip','opened_by','last_ip','changed_by']){ + if(mutation.action!=='Create' && (field==='source_ip'||field==='opened_by'))continue; + ContextFix.apply(ctx,mutation,field,'identity'); + } + generated.checkAndFix(ctx,mutation,results); + if(mutation.payload.name==='NORMALIZE')mutation.payload.name=normalizedName; + }}})); + let phase='A',failToken=false,invalidIP=false; + const resolver:ContextFixResolver=(_ctx,input)=>{ + if(input.function==='now')return input.now; + if(input.function==='uniStr'){if(failToken)throw new Error('PRIVATE_CONTEXT_PROVIDER_CANARY');return 'fixture-token';} + return invalidIP&&input.field==='last_ip'?'x'.repeat(101):`${phase}:${input.field}`; + }; + context.insertResource('contextFixResolver',resolver); + const provider=kind==='sqlite'?(client as any).driver:client; + const write=jest.spyOn(provider,kind==='sqlite'?'query':'persist'); + const transaction=kind==='sqlite'?jest.spyOn(provider,'transaction'):undefined; + const clear=()=>{write.mockClear();transaction?.mockClear();}; + const noWrites=()=>{expect(write).not.toHaveBeenCalled();if(transaction)expect(transaction).not.toHaveBeenCalled();}; + const make=(name:string)=>Q.entries().comment('Prepare one Context fixture entity') + .purpose('Verify automatic values cannot manufacture mutations').newEntity(context).updateName(name).updateCatalog('1'); + const load=async(id:string)=>{ + const rows=await Q.entries().withIdIs(id).limit(1).comment('Reload stored Context fixture') + .purpose('Observe committed values through generated Q and E').executeForList(context); + expect(rows).toHaveLength(1);return rows[0]; + }; + const initialAudits=client.auditTrace.length; + const broken=make('failed token');failToken=true;clear(); + const error=await rejected(()=>broken.auditAs('Reject failed Context source before persistence').save(context),'/guardedToken'); + expect(String(error)).not.toContain('PRIVATE_CONTEXT_PROVIDER_CANARY');noWrites();expect(client.auditTrace).toHaveLength(initialAudits); + expect(broken.bornAt).toBeUndefined();expect(broken.name).toBe('failed token');failToken=false; + let first=make('first');await first.auditAs('Create the first Context A row').save(context); + let second=make('second');await second.auditAs('Create an independent Context A sibling').save(context); + first=await load(first.id!);const id=first.id!,version=first.version; + expect(milliseconds(E.entry(first).bornAt().eval())).toBe(A.getTime()); + expect(E.entry(first).lastIp().eval()).toBe('A:last_ip'); + phase='B';context.withBusinessClock(new FixedBusinessClock(B)); + let audits=client.auditTrace.length;clear(); + for(let round=0;round<2;round++)await first.auditAs('Save unchanged row under Context B').save(context); + noWrites();expect(client.auditTrace).toHaveLength(audits); + let stored=await load(id);expect(stored.version).toBe(version);expect(milliseconds(stored.touchedAt)).toBe(A.getTime()); + expect(stored.lastIp).toBe('A:last_ip'); + first.updateName('NORMALIZE');clear(); + await first.auditAs('Normalize the final business edit back to its persisted value').save(context); + noWrites();expect(client.auditTrace).toHaveLength(audits); + expect(first.name).toBe('first');expect(first.version).toBe(version); + expect(milliseconds(first.touchedAt)).toBe(A.getTime()); + first.updateName('n'.repeat(101));clear();await rejected(()=>first.auditAs('Reject invalid caller value').save(context),'/name'); + noWrites();expect(client.auditTrace).toHaveLength(audits);expect(first.name).toHaveLength(101); + first.updateName('first');clear();await first.auditAs('Revert rejected edit and remain unchanged').save(context);noWrites(); + first.updateName('renamed');invalidIP=true;clear(); + await rejected(()=>first.auditAs('Reject invalid Context supplied IP').save(context),'/lastIp');noWrites();invalidIP=false; + expect(first.lastIp).toBe('A:last_ip');expect(first.name).toBe('renamed'); + await first.auditAs('Commit one independently established business change').save(context); + expect(client.auditTrace).toHaveLength(audits+1);stored=await load(id); + expect(E.entry(stored).name().eval()).toBe('renamed');expect(stored.version).toBe(Number(version)+1); + expect(milliseconds(stored.bornAt)).toBe(A.getTime());expect(milliseconds(stored.touchedAt)).toBe(B.getTime()); + expect(stored.sourceIp).toBe('A:source_ip');expect(stored.openedBy).toBe('A:opened_by'); + expect(stored.lastIp).toBe('B:last_ip');expect(stored.changedBy).toBe('B:changed_by'); + + // A valid earlier child must not keep Fix from an invalid graph attempt. + const parents=await Q.catalogs().withIdIs('1').limit(1).comment('Load unchanged graph ancestor') + .purpose('Verify Context Fix isolation and graph rollback').executeForList(context); + expect(parents).toHaveLength(1);const parent=parents[0],parentVersion=parent.version; + first=await load(id);second=await load(second.id!);parent.entryList().push(first,second); + first.updateName('graph edit');second.updateName('z'.repeat(101));phase='C';context.withBusinessClock(new FixedBusinessClock(C)); + audits=client.auditTrace.length;clear(); + await rejected(()=>parent.auditAs('Reject the later child after preparing its sibling').save(context),'/entryList/1/name'); + noWrites();expect(client.auditTrace).toHaveLength(audits); + expect(first.name).toBe('graph edit');expect(first.lastIp).toBe('B:last_ip'); + const ledger=(first as any)._root,key={entity:'Entry',id:first.id!}; + expect(Object.keys(ledger.change(key))).toEqual(['name']); + second.updateName('second');await parent.auditAs('Retry one independently changed child').save(context); + expect(client.auditTrace).toHaveLength(audits+1);expect(parent.version).toBe(parentVersion); + expect((await load(id)).lastIp).toBe('C:last_ip');expect((await load(second.id!)).lastIp).toBe('A:last_ip'); + + const mixedParents=await Q.catalogs().withIdIs('1').limit(1).comment('Load mixed normalization graph') + .purpose('Keep valid sibling writes and preparation guards').executeForList(context); + const mixed=mixedParents[0];first=await load(id);second=await load(second.id!); + mixed.entryList().push(first,second);normalizedName='graph edit'; + const normalizedVersion=first.version; + first.updateName('NORMALIZE');second.updateName('mixed sibling');audits=client.auditTrace.length;clear(); + await mixed.auditAs('Normalize one child while committing the other').save(context); + expect(client.auditTrace).toHaveLength(audits+1);expect(first.version).toBe(normalizedVersion); + expect(first.name).toBe('graph edit');expect(milliseconds(first.touchedAt)).toBe(C.getTime()); + if(kind==='sqlite')expect(write.mock.calls.filter(args=>/^\s*UPDATE\s/i.test(String(args[0])))).toHaveLength(1); + else expect(write).toHaveBeenCalledTimes(1); + + first.updateName('NORMALIZE');second.updateName('z'.repeat(101));audits=client.auditTrace.length;clear(); + await rejected(()=>mixed.auditAs('Reject a sibling after normalizing another child').save(context),'/entryList/1/name'); + noWrites();expect(client.auditTrace).toHaveLength(audits); + expect(first.name).toBe('graph edit');expect(second.name).toHaveLength(101); + second.updateName('mixed sibling');clear(); + await mixed.auditAs('Restore the invalid sibling and remain a no-op').save(context);noWrites(); + process.stdout.write('TS_CONTEXT_FIX_CASE='+JSON.stringify({provider:kind,passed:true,noOpProviderCalls:0, + failedCheckProviderCalls:0,updateAudits:1,typedQ:true,typedE:true,objectLocation:true,graphRollback:true})+'\n'); + write.mockRestore();transaction?.mockRestore(); + }finally{if(kind==='sqlite')await (client as SQLiteTeaQLClient).close();} +},30000); diff --git a/source/teaql-ts/examples/creation-fixtures.json b/source/teaql-ts/examples/creation-fixtures.json new file mode 100644 index 0000000000000000000000000000000000000000..457506c370f297bc6fb392b3eb8c7c8279358734 --- /dev/null +++ b/source/teaql-ts/examples/creation-fixtures.json @@ -0,0 +1,1731 @@ +{ + "schema": "teaql.typescript-creation-fixture-import/v1", + "generatorCommit": "54dccd3b534d568c03590eae89f61a002f189e25", + "generatorSourceContentsSha256": "a09764dead9746a0e4f521957c3cad4e4368835c98ab1d73fc55bd429bc52e1d", + "producerReportSha256": "df47b2daf172ecfbdd25c18557230ce4d8f0d1bd897926c0315dd9e87d8fb586", + "generatedManifestSha256": "25d505b42f105f9130b6ace8597ef07124207fb0bc95f044866786749d4b8e93", + "rawExport": "typescript-creation-fixtures-v2", + "generatedImplementationHandEdited": false, + "fixtures": [ + { + "id": "conformance", + "model": "examples/conformance/model.xml", + "modelSha256": "0a59f66db2487fdd0430087dd5985ae780225c088ad800679cb57c593c6bcee7", + "target": "examples/conformance", + "files": { + "src/generated/Q.ts": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "src/generated/requests/PlatformRequest.ts": "fe5a1387d2f630767a6aa1e076382f00f55adaf1ab26716c6f7e46b0ce6f3bd5", + "src/generated/requests/WorkItemRequest.ts": "0641a721e4a0c718a52a16ab6c097e3095fa906b62bb5d2794e8d72cac86bbeb", + "src/generated/E.ts": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "src/teaql-schemas.ts": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "src/runtime-module.ts": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "src/generated-bootstrap.ts": "3a760a0942f5e1c9a6767a319d1d3b5f217c06b065f0b1af3ba93157f98b1510", + "src/generated/models/Platform.ts": "378bf89701194d94aa3ca2fe6eb89331c2a77943bbad30bd607d02ac39125c89", + "src/generated/models/WorkItem.ts": "3739c2602861a6e1c96287af8f6f682b151dfcf6c422d862c4c046d25c288f41" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": false, + "sourceCommit": "00f371926933492dc45c213faa0f37ce2a2b03e3", + "differences": [ + { + "name": "src/generated/models/Platform.ts", + "expected": "016e9b537e124b79a11321fcbcf37155d46e028cf6d77c04406a8a379313c0e5", + "actual": "b86aa80274e59dde2b89ac816beaf997edf417eff1e7ff82d97cff2b867f2aeb" + }, + { + "name": "src/generated/models/WorkItem.ts", + "expected": "8ae5221919f4ad99a7d1ae0a2f785173ab5bc2624b6bc9ed283368239965f30b", + "actual": "49211b446abffe8e8616a91c838cc947d290f9488f0e93a7e0438b2a43203ca6" + } + ] + } + }, + { + "id": "trace-chain", + "model": "examples/trace-chain/model.xml", + "modelSha256": "95502038a66686580e7399dc4252df51f95cc0dc10a54657f5779dc2a5dd1e76", + "target": "examples/trace-chain/lib", + "files": { + "src/generated/Q.ts": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "src/generated/requests/PlatformRequest.ts": "39c046990fca0f78bff7f061fb8f80df445e38299c58a68fb2ada753b6eebcc8", + "src/generated/requests/CustomerOrderRequest.ts": "f28f1c1c7143a7e9708bd19df338eb09cb766e89ba9bb3b0b6f2752e632c3028", + "src/generated/requests/OrderItemRequest.ts": "20030ab7968e281b5705ce617762af9447d2ec31f3d7d662b1f9c94d40cdabe9", + "src/generated/requests/PaymentRequest.ts": "9a710f503ddc386e0902f47a3caaef932b69c7fe4fb9e8a83b7a28a3d7e119b4", + "src/generated/requests/PaymentAttemptRequest.ts": "4aac4c415a27f4007ee0ba7468e6739ce6775be0b59b6c2cda9c2bdb0c1ea981", + "src/generated/requests/ShipmentRequest.ts": "6846607eca4b581798563ca5f4e99cd739bb90b5d1d109a7809919807bf2aedd", + "src/generated/E.ts": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "src/teaql-schemas.ts": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "src/runtime-module.ts": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "src/generated-bootstrap.ts": "91e1f178624c29d92475497b27f522ad20963694494e2541a48e5b01f21a31d0", + "src/generated/models/Platform.ts": "cddc3065ef5203d8eb0425d35bfb953c15cf9b921e9d715749e0c497bab92b45", + "src/generated/models/CustomerOrder.ts": "d2b76f37907186c454c4f4e01af784f19efc1f8fc9fe30752feb7cb1744bbc55", + "src/generated/models/OrderItem.ts": "b3dbbb4be23b9f491f53b086e5a6116712dbffea94f9ac3ca21fa9c79418acd7", + "src/generated/models/Payment.ts": "195c5647261abc1f375e799b4cec94ab59a2c542b06d9730ff88fa769a1b4542", + "src/generated/models/PaymentAttempt.ts": "3eaf48d693743c8a8d8441c74a5d397322ddbb6cda39b5df602523c5947a1c3f", + "src/generated/models/Shipment.ts": "5654989bcd567954872a6c08800a5a564698a20a6dd90e453e2f85e445f0d390" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": false, + "sourceCommit": "00f371926933492dc45c213faa0f37ce2a2b03e3", + "differences": [ + { + "name": "src/generated/models/Platform.ts", + "expected": "bfe56aa9c73bb1301462d771a28856258dfa5eb717f2948842d21ac3b80e34bd", + "actual": "f7c49e94a4b28fcf74c676601371beee6e4d2417cf4e6e07c3eca40581754d14" + }, + { + "name": "src/generated/models/CustomerOrder.ts", + "expected": "48e534361c3b7af37ec74327e0bc7edebd3b5dca5df6cffbc81c037f3030617f", + "actual": "294c174429288ef813d5d1127b5ea501f4b2aad7568c8ee3fcd3696f7ac11de4" + }, + { + "name": "src/generated/models/OrderItem.ts", + "expected": "1b8830553ff23253bca228f0f20040fccf00ce9b5f9611ae3f6852d83003afad", + "actual": "8c2a7f06d80b14015c259b5f798337e589a34cbf0520b14a0b4a4f33ca2c46b0" + }, + { + "name": "src/generated/models/Payment.ts", + "expected": "331a422c60853e3d82a83ab3dbc09ee6627ab0941ad46eda93093ad2166f59e7", + "actual": "d61247fdf23471aa44cb1abf858e2936c57f43f9c6481fb64081c3d190c5ec79" + }, + { + "name": "src/generated/models/PaymentAttempt.ts", + "expected": "c8597a8bbb1514c05cd115705752ee7bef0141e91b2930d0a218e6725797e484", + "actual": "9ce92d085ae1f48082420151ffd87141e6afb06988771a4d0902c234922507f5" + }, + { + "name": "src/generated/models/Shipment.ts", + "expected": "1de5f9f41d6753f51a77d69a045435a05ef79202aafe2cf72710fa96f33851b9", + "actual": "9f480997aaad0cbd0c549160d61d60f5a4e938017faa60584731dd244dfcbe7c" + } + ] + } + }, + { + "id": "facet-trace", + "model": "examples/facet-trace/model.xml", + "modelSha256": "9fc6724c828e10aca8cea9f53b65460f26577f74ba5396f04376ad4f20ddc30e", + "target": "examples/facet-trace/lib", + "files": { + "src/generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "src/generated/requests/PlatformRequest.ts": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "src/generated/requests/SchoolTypeRequest.ts": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "src/generated/requests/SchoolRequest.ts": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb", + "src/generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "src/teaql-schemas.ts": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "src/runtime-module.ts": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "src/generated-bootstrap.ts": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "src/generated/models/Platform.ts": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "src/generated/models/SchoolType.ts": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "src/generated/models/School.ts": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": false, + "sourceCommit": "00f371926933492dc45c213faa0f37ce2a2b03e3", + "differences": [ + { + "name": "src/generated/models/Platform.ts", + "expected": "3b6ee4bcae34fb0ba2e267f048c671a97d7ebc058e0a188b857f665a17c040c2", + "actual": "db69ea5d998104c1398f54d22fa2720dc55cd93d853fcdfa0d79341c077b6673" + }, + { + "name": "src/generated/models/SchoolType.ts", + "expected": "a0466df6922511ce356072f2dc511edf9cd3d30a8dc77611f48eb3d8a20e5bfc", + "actual": "422d533965dd8bc6e226e1944592e3de44d16b7f46fc842651a19c230e9aaf49" + }, + { + "name": "src/generated/models/School.ts", + "expected": "ce931a9b31676805239db5f51ce4eadb65c6b328ac58a842773ecfa4a1e3e028", + "actual": "dcec1738d0a739bdbd6f9df0ab0a700bd698653ddaac6b8a20e55296854aacdf" + } + ] + } + }, + { + "id": "school-management", + "model": "examples/school-management/model.xml", + "modelSha256": "b5cd06ae44464fc29ed24de82654b47c80f546110496756aa15923cee1c511b4", + "target": "examples/school-management", + "files": { + "src/generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "src/generated/requests/PlatformRequest.ts": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "src/generated/requests/SchoolTypeRequest.ts": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "src/generated/requests/SchoolRequest.ts": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb", + "src/generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "src/teaql-schemas.ts": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "src/runtime-module.ts": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "src/generated-bootstrap.ts": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "src/generated/models/Platform.ts": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "src/generated/models/SchoolType.ts": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "src/generated/models/School.ts": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": false, + "sourceCommit": "00f371926933492dc45c213faa0f37ce2a2b03e3", + "differences": [ + { + "name": "src/generated/models/Platform.ts", + "expected": "3b6ee4bcae34fb0ba2e267f048c671a97d7ebc058e0a188b857f665a17c040c2", + "actual": "db69ea5d998104c1398f54d22fa2720dc55cd93d853fcdfa0d79341c077b6673" + }, + { + "name": "src/generated/models/SchoolType.ts", + "expected": "a0466df6922511ce356072f2dc511edf9cd3d30a8dc77611f48eb3d8a20e5bfc", + "actual": "422d533965dd8bc6e226e1944592e3de44d16b7f46fc842651a19c230e9aaf49" + }, + { + "name": "src/generated/models/School.ts", + "expected": "ce931a9b31676805239db5f51ce4eadb65c6b328ac58a842773ecfa4a1e3e028", + "actual": "dcec1738d0a739bdbd6f9df0ab0a700bd698653ddaac6b8a20e55296854aacdf" + } + ] + } + }, + { + "id": "school-reconciled", + "model": "examples/school-management/model-reconciled.xml", + "modelSha256": "896c579f3c9dded55c9728cb4af23cc8b920776e93ddcb95c8b0e95efdbcb451", + "target": "examples/school-management/src/reconciled", + "files": { + "generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generated/requests/PlatformRequest.ts": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "generated/requests/SchoolTypeRequest.ts": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "generated/requests/SchoolRequest.ts": "fac23dbff189b41421432bb7efd6dcddcfe4fd96d6eaf004fda78e17567c62cd", + "generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "teaql-schemas.ts": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "runtime-module.ts": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "generated-bootstrap.ts": "1513d365488b3f1016973c158034e450b06c6601dec5c109c4fa2bd369aef736", + "generated/models/Platform.ts": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "generated/models/SchoolType.ts": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "generated/models/School.ts": "125e5812cf6a9b2ac14614ea98b6e0f514d09c15db605a55c347ff1ac35a8185" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": false, + "sourceCommit": "00f371926933492dc45c213faa0f37ce2a2b03e3", + "differences": [ + { + "name": "generated/models/Platform.ts", + "expected": "3b6ee4bcae34fb0ba2e267f048c671a97d7ebc058e0a188b857f665a17c040c2", + "actual": "db69ea5d998104c1398f54d22fa2720dc55cd93d853fcdfa0d79341c077b6673" + }, + { + "name": "generated/models/SchoolType.ts", + "expected": "a0466df6922511ce356072f2dc511edf9cd3d30a8dc77611f48eb3d8a20e5bfc", + "actual": "422d533965dd8bc6e226e1944592e3de44d16b7f46fc842651a19c230e9aaf49" + }, + { + "name": "generated/models/School.ts", + "expected": "64d8e1cce7df0c85fca0bf844c429a375a8e251b0455241df6243221994b7635", + "actual": "d12b86ed017a2df90e22f117783fdf4b64ac9be0e2f87b4993790884f9eb8f01" + } + ] + } + }, + { + "id": "browser-orders", + "model": "examples/browser-sqlite/order-model.xml", + "modelSha256": "44d20c0d236de9c79f767054deba773e11aa6ae4eaed1ede98cf7c6ed8d18495", + "target": "examples/browser-sqlite/orders-lib", + "files": { + "src/generated/Q.ts": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "src/generated/requests/PlatformRequest.ts": "d4aeb3fc4d61fcca6628617e61b11eedbe0df48920275a8ad50c7f97e401e890", + "src/generated/requests/OrderStatusRequest.ts": "735cffc0e97d95bf2be8af3efebd815ed4beb9a7ea49b0762b7234ae9f67139f", + "src/generated/requests/CustomerRequest.ts": "e949e3b0f03613224e8c756e1217672e9e1a972527797461539fb3e539b7b0c9", + "src/generated/requests/CustomerOrderRequest.ts": "bc9aee5b8b9ee262d6aa52f243b06a8b6527493b9284e3a6a2ac3e6c86ec7c4d", + "src/generated/requests/OrderItemRequest.ts": "1bace871f045b60e27f8cc184e491a8cbf44a9a90aa8f3af74ea4be53d5df2d6", + "src/generated/E.ts": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "src/teaql-schemas.ts": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "src/runtime-module.ts": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "src/generated-bootstrap.ts": "01e5a1a0501f7cb756d74b2f4c13ab8654ab0b6623b0d276f6c120508af6b2d5", + "src/generated/models/Platform.ts": "be35c375bd7f267e8df179e6aade7d4c158bb86274b2c6823975e9bda4362a70", + "src/generated/models/OrderStatus.ts": "ae5b3bbbe9ecaa46048eb3fb99cd767c347d312afcb604d4f5bc0cb921b4dfe2", + "src/generated/models/Customer.ts": "47e2a271fbd84be36affa0e7e5fe77d489f32735e69f137371ffcf0edeb3bcba", + "src/generated/models/CustomerOrder.ts": "11dd27a3b310cb88a495df5df3241bdc0d7e42834593b7a5b475d7d76755ee3c", + "src/generated/models/OrderItem.ts": "45543cf484bf7b57b542bedd42d7f6f1c2650678d80b11da2ddc63925e32e706" + }, + "dependencyBindings": [], + "previousSourceGuard": { + "accepted": false, + "sourceCommit": "00f371926933492dc45c213faa0f37ce2a2b03e3", + "differences": [ + { + "name": "src/generated/models/Platform.ts", + "expected": "d5ccaabeceefbfba15ec1c90f0602c10033476b6d53ab7352d5fda41433f0abd", + "actual": "94da2759b338a3be4ebd5310e71db128d741b7bdafd94d94bb68950249f705ef" + }, + { + "name": "src/generated/models/OrderStatus.ts", + "expected": "1fd1875def868241a206e77a71c2f7cb567c9a6f84dac647dc0264d6ddde3ca6", + "actual": "6ab043c7044fe392aa9f1f96716066eed51b1419920e783978e28deb2c955f01" + }, + { + "name": "src/generated/models/Customer.ts", + "expected": "50f4b5ceff2858320136579cf637001a05bf1c08db6a6f64d82992150eb179d3", + "actual": "e3cee2717ea883ed1071f42e11e9560ec31079932ff0127b6c26c60083a67a95" + }, + { + "name": "src/generated/models/CustomerOrder.ts", + "expected": "0fcae54183cbd0012d7f930726070602a4c2a8752985fcd81bf52d6c596c29c9", + "actual": "90a832c2ba6bc2051c7c1e8667a0c9ecf300ff070b8ded7cfd500a290de97a11" + }, + { + "name": "src/generated/models/OrderItem.ts", + "expected": "afaadab085e477f0d7b4037a3eda542e31124430ebe18d72acec3671eea508c5", + "actual": "ab789105e4ceb01b7cb579dff72de916a50f33fd013cfdcece9141752b0e0766" + } + ] + } + }, + { + "id": "fix-e-alignment", + "model": "examples/fix-e-alignment/model.xml", + "modelSha256": "a2cf4c907cb084cb0946e993eeba586c8c0701a89fdc4a849808aa743be033b7", + "target": "examples/fix-e-alignment/generated", + "files": { + "src/generated/Q.ts": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "src/generated/requests/TenantRequest.ts": "3686c7f2c2d18bb7960b88c4f4a636c83d96ba97a6d31620cefee2f218722e3c", + "src/generated/requests/PurchaseOrderRequest.ts": "5e6c59ead789538fdd469a70255f09144dc12c93c9ad10017629f0b618ab7653", + "src/generated/requests/OrderItemRequest.ts": "896c43cb390a9b5d9ac76cde78dc296fa55a2b0e8e2aca344daa3ebb33fa5a63", + "teaql-i18n.json": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "src/generated/E.ts": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "package.json": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "src/teaql-node-sql.ts": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "src/runtime-module.ts": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "src/generated-bootstrap.ts": "f16c9576076922c99fab0b88ab36c7c21b1560dce451d99d44b281bbedc5c237", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/Tenant.ts": "18ecfca38a353d05fb3a28ca82d9a54e0b466d91c4c5225deafa95d9cdf11434", + "src/generated/models/PurchaseOrder.ts": "ab23220c528f82e51a507ce17aea90e706234b638aa4b89eee326d15bb39d9e0", + "src/generated/models/OrderItem.ts": "84408c401d116fb8edce9d0ef5bbbc2ed568c46ab0dc8ac517743e9fd80a8ae6" + }, + "dependencyBindings": [] + }, + { + "id": "scalar-type-probe", + "model": "examples/scalar-type-probe/model.xml", + "modelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762", + "target": "examples/scalar-type-probe/generated", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "src/generated/requests/ScalarTypeProbeRequest.ts": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "src/generated-bootstrap.ts": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "src/generated/models/ScalarTypeProbe.ts": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + "dependencyBindings": [] + }, + { + "id": "order-management", + "model": "examples/order-management/model.xml", + "modelSha256": "a50951aa0df35cac1f4ed64ef0646860941916aed1ec0919b5b299ef4ad6a303", + "target": "examples/order-management/typescript-node-lib-core", + "files": { + "src/generated/Q.ts": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a", + "src/generated/requests/CommercePlatformRequest.ts": "b52beef112067fdec2f4ad0ea49d6edc12faf982bd9943b25424a5807ca0461c", + "src/generated/requests/CustomerRequest.ts": "f5ef064cc780f439173e1b78e643bbc53f92f07cfb63dca60374bbe220207f4e", + "src/generated/requests/OrderStatusRequest.ts": "1682ba1e66ed78eb7870c8b947f6f6cc61d91629fe0f0e360379763ba9afddd3", + "src/generated/requests/CustomerOrderRequest.ts": "42d0af0b3f801f8a9086cf9bf945e82ccbf99fd93377a6dfc23eba8b655ac8ee", + "src/generated/requests/ProductRequest.ts": "4dbd632a3c0d1f1e0191af73633200c5ce2102531fc8c275b600ae628685275d", + "src/generated/requests/OrderLineRequest.ts": "c7625ef9ebe20f8ee0a6f0dc1c7be4bfc42a6751ded68735be17478254bcaa62", + "src/generated/requests/OrderSearchPresetRequest.ts": "02808647c11620de5098c6d6ec01e06b3738d0c0563c26c000fd6b191bdf64c6", + "teaql-i18n.json": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135", + "src/generated/E.ts": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae", + "package.json": "81de7f3d7b09de596d3462ddbdd148e1a7b4b889680186efc52a3b5ae0918b11", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5", + "src/teaql-node-sql.ts": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf", + "src/runtime-module.ts": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c", + "src/generated-bootstrap.ts": "5273e61aca2b4f61980d12b239850c2cbe53034ab4ff2728aec79331202e0218", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/CommercePlatform.ts": "e1b01e6a42c8fdadc1634f45e8f700eed0d3c3fa841fb22cb9b3c7cf22199a81", + "src/generated/models/Customer.ts": "aafef115b28e5075aa280d9eacfd06feefff4ecf298f35a7c9057ae221738ede", + "src/generated/models/OrderStatus.ts": "dc8467ddfa4bd759d4a30cd49f8990a5bbcd67d6a36467c4e23623fa23c44a2d", + "src/generated/models/CustomerOrder.ts": "47bd5e38d16373e70860e021383921ee4c6d22f9db2de7d46d07d3592b0a7363", + "src/generated/models/Product.ts": "cedd9d09a18ccdb8f68943729e300390da46c9790b9601506124cfd968b085ef", + "src/generated/models/OrderLine.ts": "1a63ec46b4f02d04efeed5bbe3c7377293c6cea09d336556a84db2c6f67d3e2e", + "src/generated/models/OrderSearchPreset.ts": "e02d8a9db91b94756869a067922f47b638f347c2051900f4f786762c1e3b1266" + }, + "dependencyBindings": [ + { + "name": "teaql-ts", + "generated": "npm:@teaql/teaql@0.3.1", + "selected": "file:../../.." + } + ] + }, + { + "id": "task-board", + "model": "examples/task-board/model.xml", + "modelSha256": "4a1ec513cb362e4c25a5bc9479fe27a2034558633a9e5760245919af7c601856", + "target": "examples/task-board/ts-lib-core", + "files": { + "src/generated/Q.ts": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "src/generated/requests/PlatformRequest.ts": "d02f8397132992a40731bdeecb4d321bcd4807a48a940d211b7bea8ef38f9d08", + "src/generated/requests/TaskStatusRequest.ts": "501ed560c7fef2143b6df6dd80084824ae3bfa623c499cf624613465352e19ba", + "src/generated/requests/TaskRequest.ts": "a66bb1ce89a44a1c91219f6f26c002f20d496a6ae58611bf596fd59eb2c46185", + "src/generated/requests/TaskExecutionLogRequest.ts": "451abd611b6bec0ea8470a1d4337ad48e389892d9475e8f5efd6dcba9517de28", + "teaql-i18n.json": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "src/generated/E.ts": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "package.json": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "src/teaql-node-sql.ts": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "src/runtime-module.ts": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "src/generated-bootstrap.ts": "89796bbdfdcf09c31cffbd64c654853a163b66511776b996594fe5cbf7c5ab01", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/Platform.ts": "2e8dc7c1c3ca171b352b1ed7d318b8b2506f02645f167e30f569ce9be4011707", + "src/generated/models/TaskStatus.ts": "cf236b6d0b08056c578e9fa6681dc141ab7b155aacaa44e339c9974a504ad456", + "src/generated/models/Task.ts": "a80de823264c6abda17d177b762462b3791f6d2d377adfdb9282a67b5239feaf", + "src/generated/models/TaskExecutionLog.ts": "271b9d3a51cbf86cd2190b1f6798bca3414594c4d41b74719c7d3c50ff3873ef" + }, + "dependencyBindings": [] + }, + { + "id": "expression-camelcase", + "model": "examples/expression-profiles/generated/camelCase/model.xml", + "modelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762", + "target": "examples/expression-profiles/generated/camelCase", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "src/generated/requests/ScalarTypeProbeRequest.ts": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "src/generated-bootstrap.ts": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "src/generated/models/ScalarTypeProbe.ts": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + "dependencyBindings": [] + }, + { + "id": "expression-snake-case", + "model": "examples/expression-profiles/generated/snake_case/model.xml", + "modelSha256": "2dbbcfea6057a5dc7c7c356ea4d0dacec5d5165538f6a9c5903d4d3b64ee13c6", + "target": "examples/expression-profiles/generated/snake_case", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "src/generated/requests/ScalarTypeProbeRequest.ts": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "src/generated-bootstrap.ts": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "src/generated/models/ScalarTypeProbe.ts": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + "dependencyBindings": [] + }, + { + "id": "expression-pascalcase", + "model": "examples/expression-profiles/generated/PascalCase/model.xml", + "modelSha256": "f836540a765f8c372bd7103a25a83ca316797253079ac63f8a1ef5ee4ded027d", + "target": "examples/expression-profiles/generated/PascalCase", + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "src/generated/requests/ScalarTypeProbeRequest.ts": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "src/generated-search-models.ts": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "src/generated-bootstrap.ts": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "src/generated/models/ScalarTypeProbe.ts": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + "dependencyBindings": [] + } + ], + "applied": [ + { + "relative": "examples/conformance/src/generated/Q.ts", + "beforeSha256": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "generatedSha256": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027", + "sha256": "4e7f90a3b34385ab94a44d1bdf84a91c1294d5a51784588bd3da22b983bd3027" + }, + { + "relative": "examples/conformance/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "4fe45fd10d7bf6c127774989f079ee5d7afa8e40668eb0c65232ed871a76906a", + "generatedSha256": "fe5a1387d2f630767a6aa1e076382f00f55adaf1ab26716c6f7e46b0ce6f3bd5", + "sha256": "fe5a1387d2f630767a6aa1e076382f00f55adaf1ab26716c6f7e46b0ce6f3bd5" + }, + { + "relative": "examples/conformance/src/generated/requests/WorkItemRequest.ts", + "beforeSha256": "1b029dc2e742b133cd8021e5d6d64e67faf21301aa6eb18224d2f78f71acbca2", + "generatedSha256": "0641a721e4a0c718a52a16ab6c097e3095fa906b62bb5d2794e8d72cac86bbeb", + "sha256": "0641a721e4a0c718a52a16ab6c097e3095fa906b62bb5d2794e8d72cac86bbeb" + }, + { + "relative": "examples/conformance/src/generated/E.ts", + "beforeSha256": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "generatedSha256": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7", + "sha256": "b757b7dee2a5c8b018ebe8aae2c2f92622d90ed71d270b2c523c1ec49d42b5a7" + }, + { + "relative": "examples/conformance/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/conformance/src/generated-search-models.ts", + "beforeSha256": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "generatedSha256": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39", + "sha256": "1d044e55eefc0415502f51cfff10a9d71b5261be4e99aeac287af55af56acb39" + }, + { + "relative": "examples/conformance/src/teaql-schemas.ts", + "beforeSha256": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "generatedSha256": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83", + "sha256": "ebc992b7f7850e0324a9be563b663cba3d5c7d2bbafd5269f38d54b06ddf9e83" + }, + { + "relative": "examples/conformance/src/runtime-module.ts", + "beforeSha256": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "generatedSha256": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e", + "sha256": "fb0e3dc8299b2607139d0e077b37ad8e2d19dc307220ec5d41296667aa3a068e" + }, + { + "relative": "examples/conformance/src/generated-bootstrap.ts", + "beforeSha256": "3a760a0942f5e1c9a6767a319d1d3b5f217c06b065f0b1af3ba93157f98b1510", + "generatedSha256": "3a760a0942f5e1c9a6767a319d1d3b5f217c06b065f0b1af3ba93157f98b1510", + "sha256": "3a760a0942f5e1c9a6767a319d1d3b5f217c06b065f0b1af3ba93157f98b1510" + }, + { + "relative": "examples/conformance/src/generated/models/Platform.ts", + "beforeSha256": "b86aa80274e59dde2b89ac816beaf997edf417eff1e7ff82d97cff2b867f2aeb", + "generatedSha256": "378bf89701194d94aa3ca2fe6eb89331c2a77943bbad30bd607d02ac39125c89", + "sha256": "378bf89701194d94aa3ca2fe6eb89331c2a77943bbad30bd607d02ac39125c89" + }, + { + "relative": "examples/conformance/src/generated/models/WorkItem.ts", + "beforeSha256": "49211b446abffe8e8616a91c838cc947d290f9488f0e93a7e0438b2a43203ca6", + "generatedSha256": "3739c2602861a6e1c96287af8f6f682b151dfcf6c422d862c4c046d25c288f41", + "sha256": "3739c2602861a6e1c96287af8f6f682b151dfcf6c422d862c4c046d25c288f41" + }, + { + "relative": "examples/trace-chain/lib/src/generated/Q.ts", + "beforeSha256": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "generatedSha256": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833", + "sha256": "ec633c6c5c488e3a2f0dd77a2c9cc5b40cece976f8439caf6782bb9f5cd49833" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "a404634943261d700950fdfe35dd6164eaacdd6e0e2dee3648350c9415ad1cdf", + "generatedSha256": "39c046990fca0f78bff7f061fb8f80df445e38299c58a68fb2ada753b6eebcc8", + "sha256": "39c046990fca0f78bff7f061fb8f80df445e38299c58a68fb2ada753b6eebcc8" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/CustomerOrderRequest.ts", + "beforeSha256": "2fc4934365ca804fb98f242c4b2b6bbbc7d2d67c5e8bf53a0d7a2424214bdf1b", + "generatedSha256": "f28f1c1c7143a7e9708bd19df338eb09cb766e89ba9bb3b0b6f2752e632c3028", + "sha256": "f28f1c1c7143a7e9708bd19df338eb09cb766e89ba9bb3b0b6f2752e632c3028" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/OrderItemRequest.ts", + "beforeSha256": "dd87bfad0287176c23f152d148c76d8731b7e7edcd0c83ea0c83cb8a7a73c96d", + "generatedSha256": "20030ab7968e281b5705ce617762af9447d2ec31f3d7d662b1f9c94d40cdabe9", + "sha256": "20030ab7968e281b5705ce617762af9447d2ec31f3d7d662b1f9c94d40cdabe9" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/PaymentRequest.ts", + "beforeSha256": "d6535b3752555f0daabed1f708c94cd71e04c6ba5c7cd1ad3cba93d793131ba1", + "generatedSha256": "9a710f503ddc386e0902f47a3caaef932b69c7fe4fb9e8a83b7a28a3d7e119b4", + "sha256": "9a710f503ddc386e0902f47a3caaef932b69c7fe4fb9e8a83b7a28a3d7e119b4" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/PaymentAttemptRequest.ts", + "beforeSha256": "32b650043a3fc8286aef63ec95c22fe63d27fb5efb33de48a69df5811bf06762", + "generatedSha256": "4aac4c415a27f4007ee0ba7468e6739ce6775be0b59b6c2cda9c2bdb0c1ea981", + "sha256": "4aac4c415a27f4007ee0ba7468e6739ce6775be0b59b6c2cda9c2bdb0c1ea981" + }, + { + "relative": "examples/trace-chain/lib/src/generated/requests/ShipmentRequest.ts", + "beforeSha256": "2ae7b4bb74fbb68ea1379bf70428aa5df9df99cc0a8f915e21b7eaad3db0ad93", + "generatedSha256": "6846607eca4b581798563ca5f4e99cd739bb90b5d1d109a7809919807bf2aedd", + "sha256": "6846607eca4b581798563ca5f4e99cd739bb90b5d1d109a7809919807bf2aedd" + }, + { + "relative": "examples/trace-chain/lib/src/generated/E.ts", + "beforeSha256": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "generatedSha256": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0", + "sha256": "5b2dd375da6ee57c91fd4c752e6ec27aa2372ec5abd639f702d5c32b3053bee0" + }, + { + "relative": "examples/trace-chain/lib/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/trace-chain/lib/src/generated-search-models.ts", + "beforeSha256": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "generatedSha256": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820", + "sha256": "b2793ced879531ebf0b7d1a87fbbe0357bad746f43b9d8fc900dce458dc07820" + }, + { + "relative": "examples/trace-chain/lib/src/teaql-schemas.ts", + "beforeSha256": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "generatedSha256": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8", + "sha256": "bf09100425eaa11c09ae3a412cea5706c2c60dcb0e4ed05effc5158b78a6e8a8" + }, + { + "relative": "examples/trace-chain/lib/src/runtime-module.ts", + "beforeSha256": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "generatedSha256": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33", + "sha256": "e47fcc695cd64599ee5314950b29bfbb278b5499060634643e2850c43a5f9d33" + }, + { + "relative": "examples/trace-chain/lib/src/generated-bootstrap.ts", + "beforeSha256": "91e1f178624c29d92475497b27f522ad20963694494e2541a48e5b01f21a31d0", + "generatedSha256": "91e1f178624c29d92475497b27f522ad20963694494e2541a48e5b01f21a31d0", + "sha256": "91e1f178624c29d92475497b27f522ad20963694494e2541a48e5b01f21a31d0" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/Platform.ts", + "beforeSha256": "f7c49e94a4b28fcf74c676601371beee6e4d2417cf4e6e07c3eca40581754d14", + "generatedSha256": "cddc3065ef5203d8eb0425d35bfb953c15cf9b921e9d715749e0c497bab92b45", + "sha256": "cddc3065ef5203d8eb0425d35bfb953c15cf9b921e9d715749e0c497bab92b45" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/CustomerOrder.ts", + "beforeSha256": "294c174429288ef813d5d1127b5ea501f4b2aad7568c8ee3fcd3696f7ac11de4", + "generatedSha256": "d2b76f37907186c454c4f4e01af784f19efc1f8fc9fe30752feb7cb1744bbc55", + "sha256": "d2b76f37907186c454c4f4e01af784f19efc1f8fc9fe30752feb7cb1744bbc55" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/OrderItem.ts", + "beforeSha256": "8c2a7f06d80b14015c259b5f798337e589a34cbf0520b14a0b4a4f33ca2c46b0", + "generatedSha256": "b3dbbb4be23b9f491f53b086e5a6116712dbffea94f9ac3ca21fa9c79418acd7", + "sha256": "b3dbbb4be23b9f491f53b086e5a6116712dbffea94f9ac3ca21fa9c79418acd7" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/Payment.ts", + "beforeSha256": "d61247fdf23471aa44cb1abf858e2936c57f43f9c6481fb64081c3d190c5ec79", + "generatedSha256": "195c5647261abc1f375e799b4cec94ab59a2c542b06d9730ff88fa769a1b4542", + "sha256": "195c5647261abc1f375e799b4cec94ab59a2c542b06d9730ff88fa769a1b4542" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/PaymentAttempt.ts", + "beforeSha256": "9ce92d085ae1f48082420151ffd87141e6afb06988771a4d0902c234922507f5", + "generatedSha256": "3eaf48d693743c8a8d8441c74a5d397322ddbb6cda39b5df602523c5947a1c3f", + "sha256": "3eaf48d693743c8a8d8441c74a5d397322ddbb6cda39b5df602523c5947a1c3f" + }, + { + "relative": "examples/trace-chain/lib/src/generated/models/Shipment.ts", + "beforeSha256": "9f480997aaad0cbd0c549160d61d60f5a4e938017faa60584731dd244dfcbe7c", + "generatedSha256": "5654989bcd567954872a6c08800a5a564698a20a6dd90e453e2f85e445f0d390", + "sha256": "5654989bcd567954872a6c08800a5a564698a20a6dd90e453e2f85e445f0d390" + }, + { + "relative": "examples/facet-trace/lib/src/generated/Q.ts", + "beforeSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generatedSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "sha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33" + }, + { + "relative": "examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "2cf29a04ac38258292e5290485bf53fa05c06f58d7aed129125280178540da3f", + "generatedSha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "sha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859" + }, + { + "relative": "examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts", + "beforeSha256": "3ba24192b1b91a36584b62b0fe43ebc0ef13094638194a603f11022807c03e26", + "generatedSha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "sha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650" + }, + { + "relative": "examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts", + "beforeSha256": "e2e0058d05fed3bc7e9652bc36a034db748a6b10777a2f5588c20df8e5784d50", + "generatedSha256": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb", + "sha256": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb" + }, + { + "relative": "examples/facet-trace/lib/src/generated/E.ts", + "beforeSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "generatedSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "sha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53" + }, + { + "relative": "examples/facet-trace/lib/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/facet-trace/lib/src/generated-search-models.ts", + "beforeSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "generatedSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "sha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5" + }, + { + "relative": "examples/facet-trace/lib/src/teaql-schemas.ts", + "beforeSha256": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "generatedSha256": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "sha256": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9" + }, + { + "relative": "examples/facet-trace/lib/src/runtime-module.ts", + "beforeSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "generatedSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "sha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae" + }, + { + "relative": "examples/facet-trace/lib/src/generated-bootstrap.ts", + "beforeSha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "generatedSha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "sha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442" + }, + { + "relative": "examples/facet-trace/lib/src/generated/models/Platform.ts", + "beforeSha256": "db69ea5d998104c1398f54d22fa2720dc55cd93d853fcdfa0d79341c077b6673", + "generatedSha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "sha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178" + }, + { + "relative": "examples/facet-trace/lib/src/generated/models/SchoolType.ts", + "beforeSha256": "422d533965dd8bc6e226e1944592e3de44d16b7f46fc842651a19c230e9aaf49", + "generatedSha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "sha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411" + }, + { + "relative": "examples/facet-trace/lib/src/generated/models/School.ts", + "beforeSha256": "dcec1738d0a739bdbd6f9df0ab0a700bd698653ddaac6b8a20e55296854aacdf", + "generatedSha256": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a", + "sha256": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a" + }, + { + "relative": "examples/school-management/src/generated/Q.ts", + "beforeSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generatedSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "sha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33" + }, + { + "relative": "examples/school-management/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "2cf29a04ac38258292e5290485bf53fa05c06f58d7aed129125280178540da3f", + "generatedSha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "sha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859" + }, + { + "relative": "examples/school-management/src/generated/requests/SchoolTypeRequest.ts", + "beforeSha256": "3ba24192b1b91a36584b62b0fe43ebc0ef13094638194a603f11022807c03e26", + "generatedSha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "sha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650" + }, + { + "relative": "examples/school-management/src/generated/requests/SchoolRequest.ts", + "beforeSha256": "e2e0058d05fed3bc7e9652bc36a034db748a6b10777a2f5588c20df8e5784d50", + "generatedSha256": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb", + "sha256": "dc816696497fa63adb8bd735c0e7b059129357f511767a9b66333f03248b7aeb" + }, + { + "relative": "examples/school-management/src/generated/E.ts", + "beforeSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "generatedSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "sha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53" + }, + { + "relative": "examples/school-management/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/school-management/src/generated-search-models.ts", + "beforeSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "generatedSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "sha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5" + }, + { + "relative": "examples/school-management/src/teaql-schemas.ts", + "beforeSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "generatedSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "sha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c" + }, + { + "relative": "examples/school-management/src/runtime-module.ts", + "beforeSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "generatedSha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "sha256": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae" + }, + { + "relative": "examples/school-management/src/generated-bootstrap.ts", + "beforeSha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "generatedSha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442", + "sha256": "101de343f33b3e5013a3e42ff126fdae293745f50226ea1337730b692a11c442" + }, + { + "relative": "examples/school-management/src/generated/models/Platform.ts", + "beforeSha256": "db69ea5d998104c1398f54d22fa2720dc55cd93d853fcdfa0d79341c077b6673", + "generatedSha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "sha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178" + }, + { + "relative": "examples/school-management/src/generated/models/SchoolType.ts", + "beforeSha256": "422d533965dd8bc6e226e1944592e3de44d16b7f46fc842651a19c230e9aaf49", + "generatedSha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "sha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411" + }, + { + "relative": "examples/school-management/src/generated/models/School.ts", + "beforeSha256": "dcec1738d0a739bdbd6f9df0ab0a700bd698653ddaac6b8a20e55296854aacdf", + "generatedSha256": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a", + "sha256": "e663e1fa343fdc3b27291ee371f9b800d35d4bb63ab76f4b1c65311ebe6bbf1a" + }, + { + "relative": "examples/school-management/src/reconciled/generated/Q.ts", + "beforeSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "generatedSha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "sha256": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33" + }, + { + "relative": "examples/school-management/src/reconciled/generated/requests/PlatformRequest.ts", + "beforeSha256": "2cf29a04ac38258292e5290485bf53fa05c06f58d7aed129125280178540da3f", + "generatedSha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859", + "sha256": "03adb49953f5e947b1402ecf534077721f97ff302042888b2bd5ca88ebc89859" + }, + { + "relative": "examples/school-management/src/reconciled/generated/requests/SchoolTypeRequest.ts", + "beforeSha256": "3ba24192b1b91a36584b62b0fe43ebc0ef13094638194a603f11022807c03e26", + "generatedSha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650", + "sha256": "9051a61d269dd716b681b0e02c32a3db843f3b49b9bc9add062cf7b028fa2650" + }, + { + "relative": "examples/school-management/src/reconciled/generated/requests/SchoolRequest.ts", + "beforeSha256": "a9f6bc26b5b30d25810d6f7aa0f447d980fe64e1d30c9dfcb10a4318de163d6a", + "generatedSha256": "fac23dbff189b41421432bb7efd6dcddcfe4fd96d6eaf004fda78e17567c62cd", + "sha256": "fac23dbff189b41421432bb7efd6dcddcfe4fd96d6eaf004fda78e17567c62cd" + }, + { + "relative": "examples/school-management/src/reconciled/generated/E.ts", + "beforeSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "generatedSha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "sha256": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53" + }, + { + "relative": "examples/school-management/src/reconciled/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/school-management/src/reconciled/generated-search-models.ts", + "beforeSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "generatedSha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "sha256": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5" + }, + { + "relative": "examples/school-management/src/reconciled/teaql-schemas.ts", + "beforeSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "generatedSha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c", + "sha256": "b326b194b719290d5a3f5e5945195846f88f5d8b537441066fa13483d0cf454c" + }, + { + "relative": "examples/school-management/src/reconciled/runtime-module.ts", + "beforeSha256": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "generatedSha256": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61", + "sha256": "8b72914c80b75610a081a52a5aee5f66d64a5fca61f0654bb9b00a79fd201f61" + }, + { + "relative": "examples/school-management/src/reconciled/generated-bootstrap.ts", + "beforeSha256": "1513d365488b3f1016973c158034e450b06c6601dec5c109c4fa2bd369aef736", + "generatedSha256": "1513d365488b3f1016973c158034e450b06c6601dec5c109c4fa2bd369aef736", + "sha256": "1513d365488b3f1016973c158034e450b06c6601dec5c109c4fa2bd369aef736" + }, + { + "relative": "examples/school-management/src/reconciled/generated/models/Platform.ts", + "beforeSha256": "db69ea5d998104c1398f54d22fa2720dc55cd93d853fcdfa0d79341c077b6673", + "generatedSha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178", + "sha256": "14ac53e267f00f41f9881702ceef94f84655e3590b4f62ddab2ad696edbe4178" + }, + { + "relative": "examples/school-management/src/reconciled/generated/models/SchoolType.ts", + "beforeSha256": "422d533965dd8bc6e226e1944592e3de44d16b7f46fc842651a19c230e9aaf49", + "generatedSha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411", + "sha256": "1ccf1fac854d58f308f2769f57ec8c378483cdad89208b6c6498cda46592d411" + }, + { + "relative": "examples/school-management/src/reconciled/generated/models/School.ts", + "beforeSha256": "d12b86ed017a2df90e22f117783fdf4b64ac9be0e2f87b4993790884f9eb8f01", + "generatedSha256": "125e5812cf6a9b2ac14614ea98b6e0f514d09c15db605a55c347ff1ac35a8185", + "sha256": "125e5812cf6a9b2ac14614ea98b6e0f514d09c15db605a55c347ff1ac35a8185" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/Q.ts", + "beforeSha256": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "generatedSha256": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f", + "sha256": "e03153a1477298d4b6568bdeab1b98cab21bf98fcafd6a2fb248a1129db0b46f" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "e511483def766362b79d209b3fcffe62441e9718b534db29060707529f3aab54", + "generatedSha256": "d4aeb3fc4d61fcca6628617e61b11eedbe0df48920275a8ad50c7f97e401e890", + "sha256": "d4aeb3fc4d61fcca6628617e61b11eedbe0df48920275a8ad50c7f97e401e890" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/OrderStatusRequest.ts", + "beforeSha256": "3087cbb8ca4172ce9b2924e5d95f503be1c8721242dd1a635c2b70ea19e0c1a1", + "generatedSha256": "735cffc0e97d95bf2be8af3efebd815ed4beb9a7ea49b0762b7234ae9f67139f", + "sha256": "735cffc0e97d95bf2be8af3efebd815ed4beb9a7ea49b0762b7234ae9f67139f" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/CustomerRequest.ts", + "beforeSha256": "422adf5131b8d4cfd65124b8fc3fc59a64da8a1d7e335e6d81be3b0cd737e57e", + "generatedSha256": "e949e3b0f03613224e8c756e1217672e9e1a972527797461539fb3e539b7b0c9", + "sha256": "e949e3b0f03613224e8c756e1217672e9e1a972527797461539fb3e539b7b0c9" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/CustomerOrderRequest.ts", + "beforeSha256": "d283f910d84b0a63795a571254ebb570822ae56e7220dc57bd0b6878d18edd37", + "generatedSha256": "bc9aee5b8b9ee262d6aa52f243b06a8b6527493b9284e3a6a2ac3e6c86ec7c4d", + "sha256": "bc9aee5b8b9ee262d6aa52f243b06a8b6527493b9284e3a6a2ac3e6c86ec7c4d" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/requests/OrderItemRequest.ts", + "beforeSha256": "c11173cc39f0238b841dd6675150d648c5f3dbd48e843931b2941cbf5499416e", + "generatedSha256": "1bace871f045b60e27f8cc184e491a8cbf44a9a90aa8f3af74ea4be53d5df2d6", + "sha256": "1bace871f045b60e27f8cc184e491a8cbf44a9a90aa8f3af74ea4be53d5df2d6" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/E.ts", + "beforeSha256": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "generatedSha256": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983", + "sha256": "9586f405199572d107999ec2e8995cfe01e3283508853f3e9504a11781f58983" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated-search-models.ts", + "beforeSha256": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "generatedSha256": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3", + "sha256": "7ece2e29eeb80306d09623c8685c8a0b8d3b25aad6b38f845d5c9f069bd6f7a3" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/teaql-schemas.ts", + "beforeSha256": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "generatedSha256": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3", + "sha256": "6e6d229ba915f8d0174b6e4a1e8170048be583fd77d1f8601dfc85f2ef88a5a3" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/runtime-module.ts", + "beforeSha256": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "generatedSha256": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b", + "sha256": "1b1672b6370ea8bedcd840f2134afa94885dd0fe3770618f8809dc7632e1891b" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated-bootstrap.ts", + "beforeSha256": "01e5a1a0501f7cb756d74b2f4c13ab8654ab0b6623b0d276f6c120508af6b2d5", + "generatedSha256": "01e5a1a0501f7cb756d74b2f4c13ab8654ab0b6623b0d276f6c120508af6b2d5", + "sha256": "01e5a1a0501f7cb756d74b2f4c13ab8654ab0b6623b0d276f6c120508af6b2d5" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/Platform.ts", + "beforeSha256": "94da2759b338a3be4ebd5310e71db128d741b7bdafd94d94bb68950249f705ef", + "generatedSha256": "be35c375bd7f267e8df179e6aade7d4c158bb86274b2c6823975e9bda4362a70", + "sha256": "be35c375bd7f267e8df179e6aade7d4c158bb86274b2c6823975e9bda4362a70" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/OrderStatus.ts", + "beforeSha256": "6ab043c7044fe392aa9f1f96716066eed51b1419920e783978e28deb2c955f01", + "generatedSha256": "ae5b3bbbe9ecaa46048eb3fb99cd767c347d312afcb604d4f5bc0cb921b4dfe2", + "sha256": "ae5b3bbbe9ecaa46048eb3fb99cd767c347d312afcb604d4f5bc0cb921b4dfe2" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/Customer.ts", + "beforeSha256": "e3cee2717ea883ed1071f42e11e9560ec31079932ff0127b6c26c60083a67a95", + "generatedSha256": "47e2a271fbd84be36affa0e7e5fe77d489f32735e69f137371ffcf0edeb3bcba", + "sha256": "47e2a271fbd84be36affa0e7e5fe77d489f32735e69f137371ffcf0edeb3bcba" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/CustomerOrder.ts", + "beforeSha256": "90a832c2ba6bc2051c7c1e8667a0c9ecf300ff070b8ded7cfd500a290de97a11", + "generatedSha256": "11dd27a3b310cb88a495df5df3241bdc0d7e42834593b7a5b475d7d76755ee3c", + "sha256": "11dd27a3b310cb88a495df5df3241bdc0d7e42834593b7a5b475d7d76755ee3c" + }, + { + "relative": "examples/browser-sqlite/orders-lib/src/generated/models/OrderItem.ts", + "beforeSha256": "ab789105e4ceb01b7cb579dff72de916a50f33fd013cfdcece9141752b0e0766", + "generatedSha256": "45543cf484bf7b57b542bedd42d7f6f1c2650678d80b11da2ddc63925e32e706", + "sha256": "45543cf484bf7b57b542bedd42d7f6f1c2650678d80b11da2ddc63925e32e706" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/Q.ts", + "beforeSha256": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "generatedSha256": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "sha256": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/requests/TenantRequest.ts", + "beforeSha256": "91b24f87248775bdd9eb31e2ca0e8dfcb9013235b1514794c33eb40eaa625510", + "generatedSha256": "3686c7f2c2d18bb7960b88c4f4a636c83d96ba97a6d31620cefee2f218722e3c", + "sha256": "3686c7f2c2d18bb7960b88c4f4a636c83d96ba97a6d31620cefee2f218722e3c" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/requests/PurchaseOrderRequest.ts", + "beforeSha256": "9858803a093318f961a2dc551b95b4c6049e38c241515b004c83b58665649bd9", + "generatedSha256": "5e6c59ead789538fdd469a70255f09144dc12c93c9ad10017629f0b618ab7653", + "sha256": "5e6c59ead789538fdd469a70255f09144dc12c93c9ad10017629f0b618ab7653" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/requests/OrderItemRequest.ts", + "beforeSha256": "4ff1bf5dae0f09a9660af221c6095348932ac69f08de35be061cac04978472fc", + "generatedSha256": "896c43cb390a9b5d9ac76cde78dc296fa55a2b0e8e2aca344daa3ebb33fa5a63", + "sha256": "896c43cb390a9b5d9ac76cde78dc296fa55a2b0e8e2aca344daa3ebb33fa5a63" + }, + { + "relative": "examples/fix-e-alignment/generated/teaql-i18n.json", + "beforeSha256": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "generatedSha256": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "sha256": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/E.ts", + "beforeSha256": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "generatedSha256": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "sha256": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b" + }, + { + "relative": "examples/fix-e-alignment/generated/package.json", + "beforeSha256": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "generatedSha256": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "sha256": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9" + }, + { + "relative": "examples/fix-e-alignment/generated/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/fix-e-alignment/generated/src/teaql-ts.ts", + "beforeSha256": "73787b3490bbc5deb284132a795bf7fb53a46525f6dbee1b5ae5b9ade6da1623", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated-search-models.ts", + "beforeSha256": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "generatedSha256": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "sha256": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6" + }, + { + "relative": "examples/fix-e-alignment/generated/src/teaql-node-sql.ts", + "beforeSha256": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "generatedSha256": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "sha256": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3" + }, + { + "relative": "examples/fix-e-alignment/generated/src/runtime-module.ts", + "beforeSha256": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "generatedSha256": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "sha256": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated-bootstrap.ts", + "beforeSha256": "f16c9576076922c99fab0b88ab36c7c21b1560dce451d99d44b281bbedc5c237", + "generatedSha256": "f16c9576076922c99fab0b88ab36c7c21b1560dce451d99d44b281bbedc5c237", + "sha256": "f16c9576076922c99fab0b88ab36c7c21b1560dce451d99d44b281bbedc5c237" + }, + { + "relative": "examples/fix-e-alignment/generated/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/models/Tenant.ts", + "beforeSha256": "28a88dcc5ba25868c25a4c5272399c68adb0212f05e7b80d361ae8369bb5a6fe", + "generatedSha256": "18ecfca38a353d05fb3a28ca82d9a54e0b466d91c4c5225deafa95d9cdf11434", + "sha256": "18ecfca38a353d05fb3a28ca82d9a54e0b466d91c4c5225deafa95d9cdf11434" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/models/PurchaseOrder.ts", + "beforeSha256": "41b9ac0181d86bed7f4b2f906419121e7864a3c93b9774e54496dd57be09e72f", + "generatedSha256": "ab23220c528f82e51a507ce17aea90e706234b638aa4b89eee326d15bb39d9e0", + "sha256": "ab23220c528f82e51a507ce17aea90e706234b638aa4b89eee326d15bb39d9e0" + }, + { + "relative": "examples/fix-e-alignment/generated/src/generated/models/OrderItem.ts", + "beforeSha256": "118f25c6fe94574e58cf2b449ff6747da77bd5b0d1360337728eeb48e0708d57", + "generatedSha256": "84408c401d116fb8edce9d0ef5bbbc2ed568c46ab0dc8ac517743e9fd80a8ae6", + "sha256": "84408c401d116fb8edce9d0ef5bbbc2ed568c46ab0dc8ac517743e9fd80a8ae6" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "550de9ffdde4deaa2481c6c2cb4b9a92b32db4bbc667127bbbab6f52b833d79e", + "generatedSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "sha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "4aef008eda2d9c4681efe68303fec593edca5c6f22d3f8ed7f0ed1a3437cd4be", + "generatedSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "sha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13" + }, + { + "relative": "examples/scalar-type-probe/generated/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/E.ts", + "beforeSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "generatedSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "sha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f" + }, + { + "relative": "examples/scalar-type-probe/generated/package.json", + "beforeSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/scalar-type-probe/generated/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/scalar-type-probe/generated/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated-search-models.ts", + "beforeSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "generatedSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "sha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956" + }, + { + "relative": "examples/scalar-type-probe/generated/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/scalar-type-probe/generated/src/runtime-module.ts", + "beforeSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "generatedSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "sha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "sha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e" + }, + { + "relative": "examples/scalar-type-probe/generated/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/models/TypePlatform.ts", + "beforeSha256": "d3d169b41dcc8d394b5937c35f965cbd2de5a7edd6d6eb3bfb2c7381327fda3d", + "generatedSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "sha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2" + }, + { + "relative": "examples/scalar-type-probe/generated/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "5f812e1c53d0c1223eca589eae1af519d6db47d84b58a9cff8f7ba97080cefc8", + "generatedSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "sha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/Q.ts", + "beforeSha256": "6978a566fb6ea137eff1b691ea962bbceb229d7f5b9d6346a89a5f5e716b204f", + "generatedSha256": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a", + "sha256": "f7293de435f3d96b971cdfded3940fdc2aa52494201bf2afbe81e34e09314b3a" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/CommercePlatformRequest.ts", + "beforeSha256": "8ffa1254d4a6fe0af08917e386acb187967fa1f9fc202fd127f73e7d137190be", + "generatedSha256": "b52beef112067fdec2f4ad0ea49d6edc12faf982bd9943b25424a5807ca0461c", + "sha256": "b52beef112067fdec2f4ad0ea49d6edc12faf982bd9943b25424a5807ca0461c" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerRequest.ts", + "beforeSha256": "d9ccd4da99beda06e7de3d8206ed999750f223d3214e7b123f921144c3e2b8af", + "generatedSha256": "f5ef064cc780f439173e1b78e643bbc53f92f07cfb63dca60374bbe220207f4e", + "sha256": "f5ef064cc780f439173e1b78e643bbc53f92f07cfb63dca60374bbe220207f4e" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/OrderStatusRequest.ts", + "beforeSha256": "ad390526e5d5cde78d2d3840103cb681e345cb3fbf7af41f49bdd10400af54ff", + "generatedSha256": "1682ba1e66ed78eb7870c8b947f6f6cc61d91629fe0f0e360379763ba9afddd3", + "sha256": "1682ba1e66ed78eb7870c8b947f6f6cc61d91629fe0f0e360379763ba9afddd3" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/CustomerOrderRequest.ts", + "beforeSha256": "ac55cc8f74d068dc642c60933ff6be0d8763612c5d631f0815cdb77f09a1b595", + "generatedSha256": "42d0af0b3f801f8a9086cf9bf945e82ccbf99fd93377a6dfc23eba8b655ac8ee", + "sha256": "42d0af0b3f801f8a9086cf9bf945e82ccbf99fd93377a6dfc23eba8b655ac8ee" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/ProductRequest.ts", + "beforeSha256": "f1e374c3afe6db9808668d9d380eccdd5d3390d3f699a2a3c527d8f6b095d107", + "generatedSha256": "4dbd632a3c0d1f1e0191af73633200c5ce2102531fc8c275b600ae628685275d", + "sha256": "4dbd632a3c0d1f1e0191af73633200c5ce2102531fc8c275b600ae628685275d" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/OrderLineRequest.ts", + "beforeSha256": "15a51491162c7fb093fcb09b50e3ea9a65d61161df13870abe419a78c26eaf63", + "generatedSha256": "c7625ef9ebe20f8ee0a6f0dc1c7be4bfc42a6751ded68735be17478254bcaa62", + "sha256": "c7625ef9ebe20f8ee0a6f0dc1c7be4bfc42a6751ded68735be17478254bcaa62" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/requests/OrderSearchPresetRequest.ts", + "beforeSha256": "a82b5ffbf642745a8d6299b705c76f55f1c5ab91dafd944a26828723155b360a", + "generatedSha256": "02808647c11620de5098c6d6ec01e06b3738d0c0563c26c000fd6b191bdf64c6", + "sha256": "02808647c11620de5098c6d6ec01e06b3738d0c0563c26c000fd6b191bdf64c6" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/teaql-i18n.json", + "beforeSha256": null, + "generatedSha256": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135", + "sha256": "4ae750ac80a6d6ccf296d8fe61d4db0f3cc4b66a285f8926720dfb87d4a42135" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/E.ts", + "beforeSha256": null, + "generatedSha256": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae", + "sha256": "fd6129df1938c80532646ae924257d9826a73040e8fe51fd507f38b1649776ae" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/package.json", + "beforeSha256": "77577f188a7d629cd5a42b9c81339d87fade831b01f056fd9436b667155615bc", + "generatedSha256": "e716061a9ba54b60ac22146437bad3b95835027dccc980014eb760dd7c7e0c1c", + "sha256": "81de7f3d7b09de596d3462ddbdd148e1a7b4b889680186efc52a3b5ae0918b11" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/teaql-ts.ts", + "beforeSha256": "14115fa3c87d15ec34ab20394f443a890df0dfabf85dfccd7c7eda85f13fc9ec", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated-search-models.ts", + "beforeSha256": null, + "generatedSha256": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5", + "sha256": "ba97fbcef69fe1d710534da6d7f590c7363459add0eb4ee7b1e11d38a1c447b5" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/teaql-node-sql.ts", + "beforeSha256": "bc24a1069531b6c1a74b44eb2b04c695ee172f66e0e32f41879b7369e7cf8027", + "generatedSha256": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf", + "sha256": "328f02555cc9c0f8d973e3b268d01b8067355d0fa5c59ea9ac10da1c94f92bbf" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/runtime-module.ts", + "beforeSha256": null, + "generatedSha256": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c", + "sha256": "e3a944ea183ff0078bf63fa5a2dc5e53654e789694fff3919f079c7bf5544b2c" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated-bootstrap.ts", + "beforeSha256": null, + "generatedSha256": "5273e61aca2b4f61980d12b239850c2cbe53034ab4ff2728aec79331202e0218", + "sha256": "5273e61aca2b4f61980d12b239850c2cbe53034ab4ff2728aec79331202e0218" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/teaql-node-sqlite.ts", + "beforeSha256": "d058be0c0f46288eebf14b07aeb02ca71765ade903bb256922df0fcaa9ead6c6", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/CommercePlatform.ts", + "beforeSha256": "9f15feb3e01118873dcb4a25538079f521cb4e00a2bce4e6365539e3d41151a0", + "generatedSha256": "e1b01e6a42c8fdadc1634f45e8f700eed0d3c3fa841fb22cb9b3c7cf22199a81", + "sha256": "e1b01e6a42c8fdadc1634f45e8f700eed0d3c3fa841fb22cb9b3c7cf22199a81" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/Customer.ts", + "beforeSha256": "ff7583f7dc8dd522a752da440fd053d3053092778676de029094bf0efe9196d4", + "generatedSha256": "aafef115b28e5075aa280d9eacfd06feefff4ecf298f35a7c9057ae221738ede", + "sha256": "aafef115b28e5075aa280d9eacfd06feefff4ecf298f35a7c9057ae221738ede" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/OrderStatus.ts", + "beforeSha256": "3953c1bfdfdaa2ba3b2affcd1c427a4a6c33c454f752e7239157749da69bb0cf", + "generatedSha256": "dc8467ddfa4bd759d4a30cd49f8990a5bbcd67d6a36467c4e23623fa23c44a2d", + "sha256": "dc8467ddfa4bd759d4a30cd49f8990a5bbcd67d6a36467c4e23623fa23c44a2d" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/CustomerOrder.ts", + "beforeSha256": "fee5f595fd6c837241ebd244bf36120fcd68be0ff46cbe318b978f59a39cdd18", + "generatedSha256": "47bd5e38d16373e70860e021383921ee4c6d22f9db2de7d46d07d3592b0a7363", + "sha256": "47bd5e38d16373e70860e021383921ee4c6d22f9db2de7d46d07d3592b0a7363" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/Product.ts", + "beforeSha256": "9c4be70ba86a19d651ab983eb42a90e080831baf0a00823f3da3d5c1f7e43301", + "generatedSha256": "cedd9d09a18ccdb8f68943729e300390da46c9790b9601506124cfd968b085ef", + "sha256": "cedd9d09a18ccdb8f68943729e300390da46c9790b9601506124cfd968b085ef" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/OrderLine.ts", + "beforeSha256": "23e5b06bf481c4a2cdc2fdf7a0789a2a7f26f9f3f43085d222bcdc095e7fab37", + "generatedSha256": "1a63ec46b4f02d04efeed5bbe3c7377293c6cea09d336556a84db2c6f67d3e2e", + "sha256": "1a63ec46b4f02d04efeed5bbe3c7377293c6cea09d336556a84db2c6f67d3e2e" + }, + { + "relative": "examples/order-management/typescript-node-lib-core/src/generated/models/OrderSearchPreset.ts", + "beforeSha256": "142ee4d733220c3a005df664ea0f4569dfa399126b74be9e5d051c52398a1823", + "generatedSha256": "e02d8a9db91b94756869a067922f47b638f347c2051900f4f786762c1e3b1266", + "sha256": "e02d8a9db91b94756869a067922f47b638f347c2051900f4f786762c1e3b1266" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/Q.ts", + "beforeSha256": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "generatedSha256": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7", + "sha256": "2d2440b92789bffc20f29bc07c8a47b8f968028b26cd41c71ff3d4b1dc3a2fb7" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/PlatformRequest.ts", + "beforeSha256": "74e7e89c9628e462268551226c3b34c46c0b988ac43b7fed28b2e7ed9da372f5", + "generatedSha256": "d02f8397132992a40731bdeecb4d321bcd4807a48a940d211b7bea8ef38f9d08", + "sha256": "d02f8397132992a40731bdeecb4d321bcd4807a48a940d211b7bea8ef38f9d08" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/TaskStatusRequest.ts", + "beforeSha256": "79c733d9e18279e2a2986e3a1e8bc21e085cd15fde48b83f420eddf44c6c0e8c", + "generatedSha256": "501ed560c7fef2143b6df6dd80084824ae3bfa623c499cf624613465352e19ba", + "sha256": "501ed560c7fef2143b6df6dd80084824ae3bfa623c499cf624613465352e19ba" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/TaskRequest.ts", + "beforeSha256": "3e7956f57f551643c047307f2d9e527133bae8cdad85716e14e72f37c8256c08", + "generatedSha256": "a66bb1ce89a44a1c91219f6f26c002f20d496a6ae58611bf596fd59eb2c46185", + "sha256": "a66bb1ce89a44a1c91219f6f26c002f20d496a6ae58611bf596fd59eb2c46185" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/requests/TaskExecutionLogRequest.ts", + "beforeSha256": "791f8b0ec35c5748cb6d9890c23ddc2cf9177033490c608c7278d9457ae03e2a", + "generatedSha256": "451abd611b6bec0ea8470a1d4337ad48e389892d9475e8f5efd6dcba9517de28", + "sha256": "451abd611b6bec0ea8470a1d4337ad48e389892d9475e8f5efd6dcba9517de28" + }, + { + "relative": "examples/task-board/ts-lib-core/teaql-i18n.json", + "beforeSha256": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "generatedSha256": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d", + "sha256": "79b420e04edf1c1e1b9f4d04ddfc0ec8a6e2a2458e6a337a8c046bacb64c3a8d" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/E.ts", + "beforeSha256": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "generatedSha256": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7", + "sha256": "69183b57505edf1c81b52c9134e1ea684e9c20b14bc3d625e1f0c4c5214852d7" + }, + { + "relative": "examples/task-board/ts-lib-core/package.json", + "beforeSha256": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "generatedSha256": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8", + "sha256": "cec0438794e240d1a2d2a39db0880030dc61c5b565092e00084ac74ad3d6c2a8" + }, + { + "relative": "examples/task-board/ts-lib-core/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/task-board/ts-lib-core/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated-search-models.ts", + "beforeSha256": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "generatedSha256": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c", + "sha256": "bc43fc08c6bea764e4e180f51e90d1fea7a476415b1297c6c9cc431dda369a9c" + }, + { + "relative": "examples/task-board/ts-lib-core/src/teaql-node-sql.ts", + "beforeSha256": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "generatedSha256": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8", + "sha256": "7229a80a16b0ec20289a84602455c05a19cfa728832eadadea379f75550345e8" + }, + { + "relative": "examples/task-board/ts-lib-core/src/runtime-module.ts", + "beforeSha256": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "generatedSha256": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1", + "sha256": "fb475de7f11541e425a5ad6818fd09a1e4d6733dfc857f5da3b2cbdb513250b1" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated-bootstrap.ts", + "beforeSha256": "89796bbdfdcf09c31cffbd64c654853a163b66511776b996594fe5cbf7c5ab01", + "generatedSha256": "89796bbdfdcf09c31cffbd64c654853a163b66511776b996594fe5cbf7c5ab01", + "sha256": "89796bbdfdcf09c31cffbd64c654853a163b66511776b996594fe5cbf7c5ab01" + }, + { + "relative": "examples/task-board/ts-lib-core/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/Platform.ts", + "beforeSha256": "cca8e25990b1f2d43b66f57e66dcea7d1fe7efad98625d9c85b32b140400a879", + "generatedSha256": "2e8dc7c1c3ca171b352b1ed7d318b8b2506f02645f167e30f569ce9be4011707", + "sha256": "2e8dc7c1c3ca171b352b1ed7d318b8b2506f02645f167e30f569ce9be4011707" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/TaskStatus.ts", + "beforeSha256": "78a0c364552769d9f256351c987a7b85a711d9591cd2784472c737ddf102d221", + "generatedSha256": "cf236b6d0b08056c578e9fa6681dc141ab7b155aacaa44e339c9974a504ad456", + "sha256": "cf236b6d0b08056c578e9fa6681dc141ab7b155aacaa44e339c9974a504ad456" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/Task.ts", + "beforeSha256": "acf3dc1e14e8fef8b6ae533215763669445cc5ede669e11f38521111a2e78da4", + "generatedSha256": "a80de823264c6abda17d177b762462b3791f6d2d377adfdb9282a67b5239feaf", + "sha256": "a80de823264c6abda17d177b762462b3791f6d2d377adfdb9282a67b5239feaf" + }, + { + "relative": "examples/task-board/ts-lib-core/src/generated/models/TaskExecutionLog.ts", + "beforeSha256": "822f3b1aaa7c7e9a0ed1f009fa29b5e5a6921b0eb93de1144b96b33c7809da25", + "generatedSha256": "271b9d3a51cbf86cd2190b1f6798bca3414594c4d41b74719c7d3c50ff3873ef", + "sha256": "271b9d3a51cbf86cd2190b1f6798bca3414594c4d41b74719c7d3c50ff3873ef" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "550de9ffdde4deaa2481c6c2cb4b9a92b32db4bbc667127bbbab6f52b833d79e", + "generatedSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "sha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "4aef008eda2d9c4681efe68303fec593edca5c6f22d3f8ed7f0ed1a3437cd4be", + "generatedSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "sha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/E.ts", + "beforeSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "generatedSha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "sha256": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/package.json", + "beforeSha256": "c857608f78461bfe1a63095fd2e0d04ead1669c415de8e7a1f8fb4c216c73558", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated-search-models.ts", + "beforeSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "generatedSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "sha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/runtime-module.ts", + "beforeSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "generatedSha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "sha256": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "sha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/models/TypePlatform.ts", + "beforeSha256": "44684bb7c77661a719ab331c4ac5f0eb95662b614fe53639f80dfc461394030b", + "generatedSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "sha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2" + }, + { + "relative": "examples/expression-profiles/generated/camelCase/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "80d0c17531027f0e5d1ae5dfc1673a92ed5cb1c99adc14185c5f18e5834ec6fc", + "generatedSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "sha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "550de9ffdde4deaa2481c6c2cb4b9a92b32db4bbc667127bbbab6f52b833d79e", + "generatedSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "sha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "4aef008eda2d9c4681efe68303fec593edca5c6f22d3f8ed7f0ed1a3437cd4be", + "generatedSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "sha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/E.ts", + "beforeSha256": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "generatedSha256": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "sha256": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/package.json", + "beforeSha256": "c857608f78461bfe1a63095fd2e0d04ead1669c415de8e7a1f8fb4c216c73558", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated-search-models.ts", + "beforeSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "generatedSha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "sha256": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/runtime-module.ts", + "beforeSha256": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "generatedSha256": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "sha256": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "sha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/models/TypePlatform.ts", + "beforeSha256": "44684bb7c77661a719ab331c4ac5f0eb95662b614fe53639f80dfc461394030b", + "generatedSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "sha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2" + }, + { + "relative": "examples/expression-profiles/generated/snake_case/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "80d0c17531027f0e5d1ae5dfc1673a92ed5cb1c99adc14185c5f18e5834ec6fc", + "generatedSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "sha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/Q.ts", + "beforeSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "generatedSha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "sha256": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/requests/TypePlatformRequest.ts", + "beforeSha256": "550de9ffdde4deaa2481c6c2cb4b9a92b32db4bbc667127bbbab6f52b833d79e", + "generatedSha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759", + "sha256": "1f83ed4a2e5ef7a6ccaa880e8cce1f3d0ce9af8fac3d9e0f11926bc724cac759" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/requests/ScalarTypeProbeRequest.ts", + "beforeSha256": "4aef008eda2d9c4681efe68303fec593edca5c6f22d3f8ed7f0ed1a3437cd4be", + "generatedSha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13", + "sha256": "fcf96cfffda072e0e24a30786d3673e40a9e7146af5db870219203eb6f909c13" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/teaql-i18n.json", + "beforeSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "generatedSha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "sha256": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/E.ts", + "beforeSha256": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "generatedSha256": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "sha256": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/package.json", + "beforeSha256": "c857608f78461bfe1a63095fd2e0d04ead1669c415de8e7a1f8fb4c216c73558", + "generatedSha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "sha256": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/tsconfig.json", + "beforeSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "generatedSha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "sha256": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/teaql-ts.ts", + "beforeSha256": "463ac354f44a3c66cbefde57a0a4ab77f514bd87aa0750ff0299a6a9a221920d", + "generatedSha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d", + "sha256": "5ae07a53e060969004a88e0dc7fe09cc430e3202b7101a46387ff927c3f5de6d" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated-search-models.ts", + "beforeSha256": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "generatedSha256": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "sha256": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/teaql-node-sql.ts", + "beforeSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "generatedSha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "sha256": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/runtime-module.ts", + "beforeSha256": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "generatedSha256": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "sha256": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated-bootstrap.ts", + "beforeSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "generatedSha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e", + "sha256": "92184f41b0a04ce3661a14deab06b2ee99a1bf644641dfe280b89dad416ed63e" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/teaql-node-sqlite.ts", + "beforeSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "generatedSha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "sha256": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/models/TypePlatform.ts", + "beforeSha256": "44684bb7c77661a719ab331c4ac5f0eb95662b614fe53639f80dfc461394030b", + "generatedSha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2", + "sha256": "aa28874a0eebabd198470e0dd310478499c66321250ea745edd4c5827f55b4c2" + }, + { + "relative": "examples/expression-profiles/generated/PascalCase/src/generated/models/ScalarTypeProbe.ts", + "beforeSha256": "80d0c17531027f0e5d1ae5dfc1673a92ed5cb1c99adc14185c5f18e5834ec6fc", + "generatedSha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d", + "sha256": "b3bddd346e3ee38eba1a401bbd820c1893bdb04f83d414da4be013f6fd5ddd3d" + } + ] +} diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json b/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json index a3a4fcf1aef4c648886a81026edfa0484ef49d66..b53ec57450008ff470a1e2cc28beab021b6d21fd 100644 --- a/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/package-lock.json @@ -6,18 +6,21 @@ "": { "name": "teaql-ensure-schema-bootstrap-example", "dependencies": { - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../..", "ts-node": "^10.9.2", "typescript": "5.4.5" }, "devDependencies": { "@types/node": "^22.0.0" + }, + "engines": { + "node": ">=22" } }, "../..": { "name": "@teaql/teaql", - "version": "0.3.1", + "version": "0.5.0", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" @@ -41,7 +44,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -68,7 +71,7 @@ "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", @@ -237,129 +240,25 @@ "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==", "license": "MIT" }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/better-sqlite3": { - "version": "12.11.1", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", - "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", "hasInstallScript": true, "license": "MIT", "dependencies": { - "bindings": "^1.5.0", - "prebuild-install": "^7.1.1" + "node-addon-api": "^8.0.0" }, "engines": { - "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" - } - }, - "node_modules/bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "license": "MIT", - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" + "node": ">=22" } }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, "node_modules/create-require": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==", "license": "MIT" }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, "node_modules/diff": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.4.tgz", @@ -369,321 +268,19 @@ "node": ">=0.3.1" } }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "license": "MIT" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, "node_modules/make-error": { "version": "1.3.6", "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==", "license": "ISC" }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.95.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.95.0.tgz", - "integrity": "sha512-T9iGctuocf0qIWFFOTxPzjT5q0SILqaBYXt272tlBHvTKC5+3JnkMirLxNJNkXHtFyBjU2Jx+NL4Zipr0B/c6Q==", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", - "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", - "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" - } - }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, "engines": { - "node": ">=6" + "node": "^18 || ^20 || >= 21" } }, "node_modules/teaql-ts": { @@ -733,18 +330,6 @@ } } }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, "node_modules/typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", @@ -764,24 +349,12 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "license": "MIT" }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, "node_modules/v8-compile-cache-lib": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==", "license": "MIT" }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, "node_modules/yn": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", diff --git a/source/teaql-ts/examples/ensure-schema-bootstrap/package.json b/source/teaql-ts/examples/ensure-schema-bootstrap/package.json index f3003d870b320a8577ab6f9113814efdd8b683a7..c87e3baf204972536441b27ea1e5fc0faa3e129f 100644 --- a/source/teaql-ts/examples/ensure-schema-bootstrap/package.json +++ b/source/teaql-ts/examples/ensure-schema-bootstrap/package.json @@ -1,12 +1,13 @@ { "name": "teaql-ensure-schema-bootstrap-example", "private": true, + "engines": { "node": ">=22" }, "scripts": { "build": "tsc --noEmit", "start": "ts-node app.ts" }, "dependencies": { - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../..", "ts-node": "^10.9.2", "typescript": "5.4.5" diff --git a/source/teaql-ts/examples/expression-profiles/README.md b/source/teaql-ts/examples/expression-profiles/README.md new file mode 100644 index 0000000000000000000000000000000000000000..07eb3f9c851bb0bc05d54078da5dbb494690fcb7 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/README.md @@ -0,0 +1,31 @@ +# Generated E diagnostics under model JSON naming profiles + +Run from this runtime repository: + +```sh +node examples/expression-profiles/verify-local.cjs +``` + +The same application executes against three evaluated, unmodified generated +libraries: default `camelCase`, `snake_case`, and `PascalCase`. Models differ +only in `json_field_naming`. The local producer identity and file hashes are +recorded in `provenance.json` and `generated/manifest.json`. + +The application uses the context's schema bootstrap, a bounded generated Q +query, and the generated E API to traverse a reverse list which was not loaded. +The default error DTO must use the model's JSON naming, while preserving the +canonical KSML path, the full attempted native chain, one first-failure +`` marker, and preload guidance. It does not override the error profile. +An observed real Q query calibrates the provider counter; E causes no further +provider calls and leaves the selected root name unchanged. + +Each model runs twice on the same SQLite database without a reset. Source, +fixture, command, origin and database evidence is retained; only task-owned +build scratch is removed. To choose an output location, set +`TEAQL_GENERATED_E_PROFILE_EVIDENCE_DIR` to a new absolute directory. +Existing reports and databases are never overwritten. Locked dependencies are installed offline into an owned source copy, never this checkout. + +These are local-source examples, not private/public package qualification, +a new audited-save test, a full example-inventory gate or full P0/P1 acceptance. +Literal punctuation and JSON-pointer escaping are covered by the separate +native expression-path tests; modeled names here are legal multiword fields. diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/model.xml b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..3e50d41714b317230b8c1930ac674b14f579e4ed --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/model.xml @@ -0,0 +1,39 @@ + + + + + + diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/package.json b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc0449fe65f58906b3f4b83d82fd3074e3aaf88 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/package.json @@ -0,0 +1,18 @@ +{ + "name": "scalar-type-conformance-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.3.1", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated-bootstrap.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..c32758df9a96057fe59280ac184fac252759e0b2 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { TypePlatform } from './generated/models/TypePlatform'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.typePlatforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = TypePlatform.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Scalar Type Conformance"); + await domainRoot.auditAs('create generated Domain Root TypePlatform').save(context); + } + context.withActiveRoot({ entity: 'TypePlatform', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated-search-models.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..17b1ab4f7387d0f0965b34113095e9e6a4e2af76 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated-search-models.ts @@ -0,0 +1,189 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "TypePlatform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "Id": "integer" as const, + "name": "string" as const, + "Name": "string" as const, + "version": "integer" as const, + "Version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "Id": "id", + "name": "name", + "Name": "name", + "version": "version", + "Version": "version", + }), + relations: Object.freeze({ + "scalarTypeProbeList": "ScalarTypeProbe", + }), + }), + "ScalarTypeProbe": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "Id": "integer" as const, + "type_platform": "integer" as const, + "typePlatform": "integer" as const, + "TypePlatform": "integer" as const, + "required_string": "string" as const, + "requiredString": "string" as const, + "RequiredString": "string" as const, + "optional_string": "string" as const, + "optionalString": "string" as const, + "OptionalString": "string" as const, + "large_text": "string" as const, + "largeText": "string" as const, + "LargeText": "string" as const, + "required_boolean": "boolean" as const, + "requiredBoolean": "boolean" as const, + "RequiredBoolean": "boolean" as const, + "optional_boolean": "boolean" as const, + "optionalBoolean": "boolean" as const, + "OptionalBoolean": "boolean" as const, + "required_integer": "integer" as const, + "requiredInteger": "integer" as const, + "RequiredInteger": "integer" as const, + "optional_integer": "integer" as const, + "optionalInteger": "integer" as const, + "OptionalInteger": "integer" as const, + "required_long": "integer" as const, + "requiredLong": "integer" as const, + "RequiredLong": "integer" as const, + "optional_long": "integer" as const, + "optionalLong": "integer" as const, + "OptionalLong": "integer" as const, + "required_decimal": "decimal" as const, + "requiredDecimal": "decimal" as const, + "RequiredDecimal": "decimal" as const, + "optional_decimal": "decimal" as const, + "optionalDecimal": "decimal" as const, + "OptionalDecimal": "decimal" as const, + "required_float": "number" as const, + "requiredFloat": "number" as const, + "RequiredFloat": "number" as const, + "optional_float": "number" as const, + "optionalFloat": "number" as const, + "OptionalFloat": "number" as const, + "required_double": "number" as const, + "requiredDouble": "number" as const, + "RequiredDouble": "number" as const, + "optional_double": "number" as const, + "optionalDouble": "number" as const, + "OptionalDouble": "number" as const, + "required_date": "date" as const, + "requiredDate": "date" as const, + "RequiredDate": "date" as const, + "optional_date": "date" as const, + "optionalDate": "date" as const, + "OptionalDate": "date" as const, + "required_time": "unsupported" as const, + "requiredTime": "unsupported" as const, + "RequiredTime": "unsupported" as const, + "optional_time": "unsupported" as const, + "optionalTime": "unsupported" as const, + "OptionalTime": "unsupported" as const, + "required_datetime": "timestamp" as const, + "requiredDatetime": "timestamp" as const, + "RequiredDatetime": "timestamp" as const, + "optional_datetime": "timestamp" as const, + "optionalDatetime": "timestamp" as const, + "OptionalDatetime": "timestamp" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "CreateTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "UpdateTime": "timestamp" as const, + "version": "integer" as const, + "Version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "Id": "id", + "type_platform": "typePlatform", + "typePlatform": "typePlatform", + "TypePlatform": "typePlatform", + "required_string": "requiredString", + "requiredString": "requiredString", + "RequiredString": "requiredString", + "optional_string": "optionalString", + "optionalString": "optionalString", + "OptionalString": "optionalString", + "large_text": "largeText", + "largeText": "largeText", + "LargeText": "largeText", + "required_boolean": "requiredBoolean", + "requiredBoolean": "requiredBoolean", + "RequiredBoolean": "requiredBoolean", + "optional_boolean": "optionalBoolean", + "optionalBoolean": "optionalBoolean", + "OptionalBoolean": "optionalBoolean", + "required_integer": "requiredInteger", + "requiredInteger": "requiredInteger", + "RequiredInteger": "requiredInteger", + "optional_integer": "optionalInteger", + "optionalInteger": "optionalInteger", + "OptionalInteger": "optionalInteger", + "required_long": "requiredLong", + "requiredLong": "requiredLong", + "RequiredLong": "requiredLong", + "optional_long": "optionalLong", + "optionalLong": "optionalLong", + "OptionalLong": "optionalLong", + "required_decimal": "requiredDecimal", + "requiredDecimal": "requiredDecimal", + "RequiredDecimal": "requiredDecimal", + "optional_decimal": "optionalDecimal", + "optionalDecimal": "optionalDecimal", + "OptionalDecimal": "optionalDecimal", + "required_float": "requiredFloat", + "requiredFloat": "requiredFloat", + "RequiredFloat": "requiredFloat", + "optional_float": "optionalFloat", + "optionalFloat": "optionalFloat", + "OptionalFloat": "optionalFloat", + "required_double": "requiredDouble", + "requiredDouble": "requiredDouble", + "RequiredDouble": "requiredDouble", + "optional_double": "optionalDouble", + "optionalDouble": "optionalDouble", + "OptionalDouble": "optionalDouble", + "required_date": "requiredDate", + "requiredDate": "requiredDate", + "RequiredDate": "requiredDate", + "optional_date": "optionalDate", + "optionalDate": "optionalDate", + "OptionalDate": "optionalDate", + "required_time": "requiredTime", + "requiredTime": "requiredTime", + "RequiredTime": "requiredTime", + "optional_time": "optionalTime", + "optionalTime": "optionalTime", + "OptionalTime": "optionalTime", + "required_datetime": "requiredDatetime", + "requiredDatetime": "requiredDatetime", + "RequiredDatetime": "requiredDatetime", + "optional_datetime": "optionalDatetime", + "optionalDatetime": "optionalDatetime", + "OptionalDatetime": "optionalDatetime", + "create_time": "createTime", + "createTime": "createTime", + "CreateTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "UpdateTime": "updateTime", + "version": "version", + "Version": "version", + }), + relations: Object.freeze({ + "type_platform": "TypePlatform", + "typePlatform": "TypePlatform", + "TypePlatform": "TypePlatform", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/E.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..7d4054dee3b04b9e848812d1361ee3f56aa792da --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/E.ts @@ -0,0 +1,564 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { TypePlatform } from './models/TypePlatform'; +import { ScalarTypeProbe } from './models/ScalarTypeProbe'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class TypePlatformExpression { + constructor( + private readonly value: TypePlatform | null | undefined, + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.typePlatform()', 'PascalCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): TypePlatform | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + scalarTypeProbeList(): ScalarTypeProbeListExpression { + const path = this.path.member('scalar_type_probe_list', 'scalarTypeProbeList'); + if (this.notLoaded) { + return new ScalarTypeProbeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return ScalarTypeProbeListExpression.missing(this.root, path); + if (!this.value.isLoaded('scalarTypeProbeList')) { + return new ScalarTypeProbeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'scalar_type_probe_list')); + } + return new ScalarTypeProbeListExpression( + this.value.scalarTypeProbeList(), this.root, path, + ); + } +} + +export class ScalarTypeProbeExpression { + constructor( + private readonly value: ScalarTypeProbe | null | undefined, + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.scalarTypeProbe()', 'PascalCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): ScalarTypeProbe | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + requiredString(): ValueExpression { + const path = this.path.member('required_string', 'requiredString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_string'), + ); + } + return new ValueExpression(this.value.requiredString); + } + + optionalString(): ValueExpression { + const path = this.path.member('optional_string', 'optionalString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_string'), + ); + } + return new ValueExpression(this.value.optionalString); + } + + largeText(): ValueExpression { + const path = this.path.member('large_text', 'largeText'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('largeText')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'large_text'), + ); + } + return new ValueExpression(this.value.largeText); + } + + requiredBoolean(): ValueExpression { + const path = this.path.member('required_boolean', 'requiredBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_boolean'), + ); + } + return new ValueExpression(this.value.requiredBoolean); + } + + optionalBoolean(): ValueExpression { + const path = this.path.member('optional_boolean', 'optionalBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_boolean'), + ); + } + return new ValueExpression(this.value.optionalBoolean); + } + + requiredInteger(): ValueExpression { + const path = this.path.member('required_integer', 'requiredInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_integer'), + ); + } + const error = integer32Error(this.value.requiredInteger, 'ScalarTypeProbe', 'required_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.requiredInteger); + } + + optionalInteger(): ValueExpression { + const path = this.path.member('optional_integer', 'optionalInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_integer'), + ); + } + const error = integer32Error(this.value.optionalInteger, 'ScalarTypeProbe', 'optional_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.optionalInteger); + } + + requiredLong(): ValueExpression { + const path = this.path.member('required_long', 'requiredLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_long'), + ); + } + return new ValueExpression(this.value.requiredLong); + } + + optionalLong(): ValueExpression { + const path = this.path.member('optional_long', 'optionalLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_long'), + ); + } + return new ValueExpression(this.value.optionalLong); + } + + requiredDecimal(): ValueExpression { + const path = this.path.member('required_decimal', 'requiredDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_decimal'), + ); + } + return new ValueExpression(this.value.requiredDecimal); + } + + optionalDecimal(): ValueExpression { + const path = this.path.member('optional_decimal', 'optionalDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_decimal'), + ); + } + return new ValueExpression(this.value.optionalDecimal); + } + + requiredFloat(): ValueExpression { + const path = this.path.member('required_float', 'requiredFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_float'), + ); + } + return new ValueExpression(this.value.requiredFloat); + } + + optionalFloat(): ValueExpression { + const path = this.path.member('optional_float', 'optionalFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_float'), + ); + } + return new ValueExpression(this.value.optionalFloat); + } + + requiredDouble(): ValueExpression { + const path = this.path.member('required_double', 'requiredDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_double'), + ); + } + return new ValueExpression(this.value.requiredDouble); + } + + optionalDouble(): ValueExpression { + const path = this.path.member('optional_double', 'optionalDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_double'), + ); + } + return new ValueExpression(this.value.optionalDouble); + } + + requiredDate(): ValueExpression { + const path = this.path.member('required_date', 'requiredDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_date'), + ); + } + return new ValueExpression(this.value.requiredDate); + } + + optionalDate(): ValueExpression { + const path = this.path.member('optional_date', 'optionalDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_date'), + ); + } + return new ValueExpression(this.value.optionalDate); + } + + requiredTime(): ValueExpression { + const path = this.path.member('required_time', 'requiredTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_time'), + ); + } + return new ValueExpression(this.value.requiredTime); + } + + optionalTime(): ValueExpression { + const path = this.path.member('optional_time', 'optionalTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_time'), + ); + } + return new ValueExpression(this.value.optionalTime); + } + + requiredDatetime(): ValueExpression { + const path = this.path.member('required_datetime', 'requiredDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_datetime'), + ); + } + return new ValueExpression(this.value.requiredDatetime); + } + + optionalDatetime(): ValueExpression { + const path = this.path.member('optional_datetime', 'optionalDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_datetime'), + ); + } + return new ValueExpression(this.value.optionalDatetime); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + typePlatformId(): ValueExpression { + const path = this.path.member('type_platform', 'typePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('typePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'type_platform'), + ); + } + const reference = this.value.typePlatform; + return new ValueExpression( + reference instanceof TypePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + typePlatform(): TypePlatformExpression { + const path = this.path.member('type_platform', 'typePlatform'); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TypePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('typePlatform')) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const relation = this.value.typePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof TypePlatform)) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const target = relation instanceof TypePlatform ? relation : undefined; + return new TypePlatformExpression(target, this.root, path); + } + +} + +export class TypePlatformListExpression { + constructor( + private readonly items: readonly TypePlatform[], + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.entity()', 'PascalCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'PascalCase')): TypePlatformListExpression { + return new TypePlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TypePlatformExpression { + return this.item(0, true); + } + + get(index: number): TypePlatformExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TypePlatformExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TypePlatformExpression(undefined, this.root, itemPath) + : new TypePlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class ScalarTypeProbeListExpression { + constructor( + private readonly items: readonly ScalarTypeProbe[], + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.entity()', 'PascalCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'PascalCase')): ScalarTypeProbeListExpression { + return new ScalarTypeProbeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): ScalarTypeProbeExpression { + return this.item(0, true); + } + + get(index: number): ScalarTypeProbeExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): ScalarTypeProbeExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new ScalarTypeProbeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new ScalarTypeProbeExpression(undefined, this.root, itemPath) + : new ScalarTypeProbeExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static typePlatform( + value: TypePlatform | null | undefined, + ): TypePlatformExpression { + return new TypePlatformExpression( + value, 'TypePlatform', ExpressionPath.root('E.typePlatform()', 'PascalCase'), + ); + } + + static scalarTypeProbe( + value: ScalarTypeProbe | null | undefined, + ): ScalarTypeProbeExpression { + return new ScalarTypeProbeExpression( + value, 'ScalarTypeProbe', ExpressionPath.root('E.scalarTypeProbe()', 'PascalCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/Q.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..5124d7963158b57d5460ab83052c5800791f46aa --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { TypePlatformRequest } from './requests/TypePlatformRequest'; +import { ScalarTypeProbeRequest } from './requests/ScalarTypeProbeRequest'; + +export class Q { + static typePlatforms(): TypePlatformRequest { + return new TypePlatformRequest(false); + } + + static typePlatformsWithMinimalFields(): TypePlatformRequest { + return new TypePlatformRequest(true); + } + static scalarTypeProbes(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(false); + } + + static scalarTypeProbesWithMinimalFields(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/models/ScalarTypeProbe.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/models/ScalarTypeProbe.ts new file mode 100644 index 0000000000000000000000000000000000000000..90f93cf19ac480a4c610bf02ac8696c043c90b2d --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/models/ScalarTypeProbe.ts @@ -0,0 +1,576 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { TypePlatform } from './TypePlatform'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class ScalarTypeProbe { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("ScalarTypeProbe", + ["id", "type_platform", "required_string", "optional_string", "large_text", "required_boolean", "optional_boolean", "required_integer", "optional_integer", "required_long", "optional_long", "required_decimal", "optional_decimal", "required_float", "optional_float", "required_double", "optional_double", "required_date", "optional_date", "required_time", "optional_time", "required_datetime", "optional_datetime", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + typePlatform?: TypePlatform | string; + requiredString?: string; + optionalString?: string | null; + largeText?: string | null; + requiredBoolean?: boolean; + optionalBoolean?: boolean | null; + requiredInteger?: number; + optionalInteger?: number | null; + requiredLong?: Long; + optionalLong?: Long | null; + requiredDecimal?: Decimal; + optionalDecimal?: Decimal | null; + requiredFloat?: number; + optionalFloat?: number | null; + requiredDouble?: number; + optionalDouble?: number | null; + requiredDate?: string; + optionalDate?: string | null; + requiredTime?: LocalTime; + optionalTime?: LocalTime | null; + requiredDatetime?: string; + optionalDatetime?: string | null; + createTime?: string; + updateTime?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(init?.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --ScalarTypeProbe.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).typePlatform && typeof (init as any).typePlatform === "object") { + this.typePlatform = (init as any).typePlatform instanceof TypePlatform + ? (init as any).typePlatform + : TypePlatform.fromRecord((init as any).typePlatform); + this.markLoaded("typePlatform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "ScalarTypeProbe", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): ScalarTypeProbe { + const entity = EntityCreation.hydrated(new ScalarTypeProbe(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(this.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): ScalarTypeProbe { + return ScalarTypeProbe.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): ScalarTypeProbe { + return EntityCreation.bootstrap(context, "ScalarTypeProbe", id, + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "ScalarTypeProbe", + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "type_platform": "TypePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + ScalarTypeProbe.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "ScalarTypeProbe", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "ScalarTypeProbe", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "ScalarTypeProbe", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "ScalarTypeProbe", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "type_platform": this.typePlatform, + "required_string": this.requiredString, + "optional_string": this.optionalString, + "large_text": this.largeText, + "required_boolean": this.requiredBoolean, + "optional_boolean": this.optionalBoolean, + "required_integer": this.requiredInteger, + "optional_integer": this.optionalInteger, + "required_long": this.requiredLong, + "optional_long": this.optionalLong, + "required_decimal": this.requiredDecimal, + "optional_decimal": this.optionalDecimal, + "required_float": this.requiredFloat, + "optional_float": this.optionalFloat, + "required_double": this.requiredDouble, + "optional_double": this.optionalDouble, + "required_date": this.requiredDate, + "optional_date": this.optionalDate, + "required_time": this.requiredTime, + "optional_time": this.optionalTime, + "required_datetime": this.requiredDatetime, + "optional_datetime": this.optionalDatetime, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateRequiredString(value: string): this { + this.requiredString = value; + this.markLoaded("requiredString"); + (this as any)._root.set(this.teaqlEntityKey(), "required_string", value); + return this; + } + + updateOptionalString(value: string | null): this { + this.optionalString = value; + this.markLoaded("optionalString"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_string", value); + return this; + } + + updateLargeText(value: string | null): this { + this.largeText = value; + this.markLoaded("largeText"); + (this as any)._root.set(this.teaqlEntityKey(), "large_text", value); + return this; + } + + updateRequiredBoolean(value: boolean): this { + this.requiredBoolean = value; + this.markLoaded("requiredBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "required_boolean", value); + return this; + } + + updateOptionalBoolean(value: boolean | null): this { + this.optionalBoolean = value; + this.markLoaded("optionalBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_boolean", value); + return this; + } + + updateRequiredInteger(value: number): this { + this.requiredInteger = value; + this.markLoaded("requiredInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "required_integer", value); + return this; + } + + updateOptionalInteger(value: number | null): this { + this.optionalInteger = value; + this.markLoaded("optionalInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_integer", value); + return this; + } + + updateRequiredLong(value: Long): this { + if (value != null) value = long(value); + this.requiredLong = value; + this.markLoaded("requiredLong"); + (this as any)._root.set(this.teaqlEntityKey(), "required_long", value); + return this; + } + + updateOptionalLong(value: Long | null): this { + if (value != null) value = long(value); + this.optionalLong = value; + this.markLoaded("optionalLong"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_long", value); + return this; + } + + updateRequiredDecimal(value: Decimal): this { + if (value != null) value = decimal(value); + this.requiredDecimal = value; + this.markLoaded("requiredDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "required_decimal", value); + return this; + } + + updateOptionalDecimal(value: Decimal | null): this { + if (value != null) value = decimal(value); + this.optionalDecimal = value; + this.markLoaded("optionalDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_decimal", value); + return this; + } + + updateRequiredFloat(value: number): this { + this.requiredFloat = value; + this.markLoaded("requiredFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "required_float", value); + return this; + } + + updateOptionalFloat(value: number | null): this { + this.optionalFloat = value; + this.markLoaded("optionalFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_float", value); + return this; + } + + updateRequiredDouble(value: number): this { + this.requiredDouble = value; + this.markLoaded("requiredDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "required_double", value); + return this; + } + + updateOptionalDouble(value: number | null): this { + this.optionalDouble = value; + this.markLoaded("optionalDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_double", value); + return this; + } + + updateRequiredDate(value: string): this { + this.requiredDate = value; + this.markLoaded("requiredDate"); + (this as any)._root.set(this.teaqlEntityKey(), "required_date", value); + return this; + } + + updateOptionalDate(value: string | null): this { + this.optionalDate = value; + this.markLoaded("optionalDate"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_date", value); + return this; + } + + updateRequiredTime(value: LocalTime): this { + if (value != null) value = localTime(value); + this.requiredTime = value; + this.markLoaded("requiredTime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_time", value); + return this; + } + + updateOptionalTime(value: LocalTime | null): this { + if (value != null) value = localTime(value); + this.optionalTime = value; + this.markLoaded("optionalTime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_time", value); + return this; + } + + updateRequiredDatetime(value: string): this { + this.requiredDatetime = value; + this.markLoaded("requiredDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_datetime", value); + return this; + } + + updateOptionalDatetime(value: string | null): this { + this.optionalDatetime = value; + this.markLoaded("optionalDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_datetime", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateTypePlatform(value: any): this { + this.typePlatform = value?.id ?? value; + this.markLoaded("typePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "type_platform", this.typePlatform); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/models/TypePlatform.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/models/TypePlatform.ts new file mode 100644 index 0000000000000000000000000000000000000000..00fc9ee5d876db31834d06abe61c11f063127e61 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/models/TypePlatform.ts @@ -0,0 +1,403 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { ScalarTypeProbe } from './ScalarTypeProbe'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class TypePlatform { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("TypePlatform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --TypePlatform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_scalarTypeProbeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["scalarTypeProbeList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).scalarTypeProbeList)) { + const selected = (init as any).scalarTypeProbeList; + (this as any)._scalarTypeProbeList = new SmartList(selected.map( + (child: unknown) => child instanceof ScalarTypeProbe + ? child + : ScalarTypeProbe.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("scalarTypeProbeList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "TypePlatform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._scalarTypeProbeList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): TypePlatform { + const entity = EntityCreation.hydrated(new TypePlatform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("scalarTypeProbeList")) result["scalarTypeProbeList"] = (this as any)._scalarTypeProbeList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): TypePlatform { + return TypePlatform.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): TypePlatform { + return EntityCreation.bootstrap(context, "TypePlatform", id, + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "TypePlatform", + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._scalarTypeProbeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._scalarTypeProbeList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "scalar_type_probe_list": graph.sourceMembers((this as any)._scalarTypeProbeList) + })); + for (const child of (this as any)._scalarTypeProbeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + TypePlatform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "TypePlatform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "TypePlatform", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "TypePlatform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "TypePlatform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + scalarTypeProbeList(): SmartList { + return (this as any)._scalarTypeProbeList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/requests/ScalarTypeProbeRequest.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/requests/ScalarTypeProbeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aab674d36faae5691bcfb6d8a395878245cbaa4 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/requests/ScalarTypeProbeRequest.ts @@ -0,0 +1,3073 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { ScalarTypeProbe } from '../models/ScalarTypeProbe'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class ScalarTypeProbeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("ScalarTypeProbe"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "ScalarTypeProbe" { + return "ScalarTypeProbe"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableScalarTypeProbeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableScalarTypeProbeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "typePlatform", "requiredString", "optionalString", "largeText", "requiredBoolean", "optionalBoolean", "requiredInteger", "optionalInteger", "requiredLong", "optionalLong", "requiredDecimal", "optionalDecimal", "requiredFloat", "optionalFloat", "requiredDouble", "optionalDouble", "requiredDate", "optionalDate", "requiredTime", "optionalTime", "requiredDatetime", "optionalDatetime", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectRequiredString(): this { + this.query.select(["requiredString"]); + return this; + } + + selectOptionalString(): this { + this.query.select(["optionalString"]); + return this; + } + + selectLargeText(): this { + this.query.select(["largeText"]); + return this; + } + + selectRequiredBoolean(): this { + this.query.select(["requiredBoolean"]); + return this; + } + + selectOptionalBoolean(): this { + this.query.select(["optionalBoolean"]); + return this; + } + + selectRequiredInteger(): this { + this.query.select(["requiredInteger"]); + return this; + } + + selectOptionalInteger(): this { + this.query.select(["optionalInteger"]); + return this; + } + + selectRequiredLong(): this { + this.query.select(["requiredLong"]); + return this; + } + + selectOptionalLong(): this { + this.query.select(["optionalLong"]); + return this; + } + + selectRequiredDecimal(): this { + this.query.select(["requiredDecimal"]); + return this; + } + + selectOptionalDecimal(): this { + this.query.select(["optionalDecimal"]); + return this; + } + + selectRequiredFloat(): this { + this.query.select(["requiredFloat"]); + return this; + } + + selectOptionalFloat(): this { + this.query.select(["optionalFloat"]); + return this; + } + + selectRequiredDouble(): this { + this.query.select(["requiredDouble"]); + return this; + } + + selectOptionalDouble(): this { + this.query.select(["optionalDouble"]); + return this; + } + + selectRequiredDate(): this { + this.query.select(["requiredDate"]); + return this; + } + + selectOptionalDate(): this { + this.query.select(["optionalDate"]); + return this; + } + + selectRequiredTime(): this { + this.query.select(["requiredTime"]); + return this; + } + + selectOptionalTime(): this { + this.query.select(["optionalTime"]); + return this; + } + + selectRequiredDatetime(): this { + this.query.select(["requiredDatetime"]); + return this; + } + + selectOptionalDatetime(): this { + this.query.select(["optionalDatetime"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectTypePlatformWith(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["typePlatform"]); + this.query.relationQuery( + "typePlatform", request.toQuery(), "typePlatform", "id", false, + { kind: "relation-select", method: "selectTypePlatformWith", relation: "typePlatform" }); + return this; + } + + withTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByTypePlatform(val: any): this { + this.filters.push({ "typePlatform": { "$eq": val } }); + return this; + } + + filterByTypePlatformIn(...vals: any[]): this { + this.filters.push({ "typePlatform": { "$in": vals } }); + return this; + } + + withTypePlatformIsKnown(): this { + this.filters.push({ "typePlatform": { "$isNull": false } }); + return this; + } + + withTypePlatformIsUnknown(): this { + this.filters.push({ "typePlatform": { "$isNull": true } }); + return this; + } + + withRequiredStringContaining(val: string): this { + this.filters.push({ "requiredString": { "$contains": val } }); + return this; + } + + withRequiredStringIs(val: string): this { + this.filters.push({ "requiredString": { "$eq": val } }); + return this; + } + + withRequiredStringIsNot(val: string): this { + this.filters.push({ "requiredString": { "$ne": val } }); + return this; + } + + withRequiredStringIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$in": vals } }); + return this; + } + + withRequiredStringNotIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$notIn": vals } }); + return this; + } + + withRequiredStringGreaterThan(val: string): this { + this.filters.push({ "requiredString": { "$gt": val } }); + return this; + } + + withRequiredStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$gte": val } }); + return this; + } + + withRequiredStringLessThan(val: string): this { + this.filters.push({ "requiredString": { "$lt": val } }); + return this; + } + + withRequiredStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$lte": val } }); + return this; + } + + withRequiredStringBetween(lower: string, upper: string): this { + this.filters.push({ "requiredString": { "$between": [lower, upper] } }); + return this; + } + + withRequiredStringIsKnown(): this { + this.filters.push({ "requiredString": { "$isNull": false } }); + return this; + } + + withRequiredStringIsUnknown(): this { + this.filters.push({ "requiredString": { "$isNull": true } }); + return this; + } + withRequiredStringNotContaining(val: string): this { + this.filters.push({ "requiredString": { "$notContains": val } }); + return this; + } + + withRequiredStringStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$startsWith": val } }); + return this; + } + + withRequiredStringNotStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$notStartsWith": val } }); + return this; + } + + withRequiredStringEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$endsWith": val } }); + return this; + } + + withRequiredStringNotEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$notEndsWith": val } }); + return this; + } + + withRequiredStringSoundingLike(val: string): this { + this.filters.push({ "requiredString": { "$soundLike": val } }); + return this; + } + + withOptionalStringContaining(val: string): this { + this.filters.push({ "optionalString": { "$contains": val } }); + return this; + } + + withOptionalStringIs(val: string): this { + this.filters.push({ "optionalString": { "$eq": val } }); + return this; + } + + withOptionalStringIsNot(val: string): this { + this.filters.push({ "optionalString": { "$ne": val } }); + return this; + } + + withOptionalStringIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$in": vals } }); + return this; + } + + withOptionalStringNotIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$notIn": vals } }); + return this; + } + + withOptionalStringGreaterThan(val: string): this { + this.filters.push({ "optionalString": { "$gt": val } }); + return this; + } + + withOptionalStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$gte": val } }); + return this; + } + + withOptionalStringLessThan(val: string): this { + this.filters.push({ "optionalString": { "$lt": val } }); + return this; + } + + withOptionalStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$lte": val } }); + return this; + } + + withOptionalStringBetween(lower: string, upper: string): this { + this.filters.push({ "optionalString": { "$between": [lower, upper] } }); + return this; + } + + withOptionalStringIsKnown(): this { + this.filters.push({ "optionalString": { "$isNull": false } }); + return this; + } + + withOptionalStringIsUnknown(): this { + this.filters.push({ "optionalString": { "$isNull": true } }); + return this; + } + withOptionalStringNotContaining(val: string): this { + this.filters.push({ "optionalString": { "$notContains": val } }); + return this; + } + + withOptionalStringStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$startsWith": val } }); + return this; + } + + withOptionalStringNotStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$notStartsWith": val } }); + return this; + } + + withOptionalStringEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$endsWith": val } }); + return this; + } + + withOptionalStringNotEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$notEndsWith": val } }); + return this; + } + + withOptionalStringSoundingLike(val: string): this { + this.filters.push({ "optionalString": { "$soundLike": val } }); + return this; + } + + withLargeTextContaining(val: string): this { + this.filters.push({ "largeText": { "$contains": val } }); + return this; + } + + withLargeTextIs(val: string): this { + this.filters.push({ "largeText": { "$eq": val } }); + return this; + } + + withLargeTextIsNot(val: string): this { + this.filters.push({ "largeText": { "$ne": val } }); + return this; + } + + withLargeTextIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$in": vals } }); + return this; + } + + withLargeTextNotIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$notIn": vals } }); + return this; + } + + withLargeTextGreaterThan(val: string): this { + this.filters.push({ "largeText": { "$gt": val } }); + return this; + } + + withLargeTextGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$gte": val } }); + return this; + } + + withLargeTextLessThan(val: string): this { + this.filters.push({ "largeText": { "$lt": val } }); + return this; + } + + withLargeTextLessThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$lte": val } }); + return this; + } + + withLargeTextBetween(lower: string, upper: string): this { + this.filters.push({ "largeText": { "$between": [lower, upper] } }); + return this; + } + + withLargeTextIsKnown(): this { + this.filters.push({ "largeText": { "$isNull": false } }); + return this; + } + + withLargeTextIsUnknown(): this { + this.filters.push({ "largeText": { "$isNull": true } }); + return this; + } + withLargeTextNotContaining(val: string): this { + this.filters.push({ "largeText": { "$notContains": val } }); + return this; + } + + withLargeTextStartingWith(val: string): this { + this.filters.push({ "largeText": { "$startsWith": val } }); + return this; + } + + withLargeTextNotStartingWith(val: string): this { + this.filters.push({ "largeText": { "$notStartsWith": val } }); + return this; + } + + withLargeTextEndingWith(val: string): this { + this.filters.push({ "largeText": { "$endsWith": val } }); + return this; + } + + withLargeTextNotEndingWith(val: string): this { + this.filters.push({ "largeText": { "$notEndsWith": val } }); + return this; + } + + withLargeTextSoundingLike(val: string): this { + this.filters.push({ "largeText": { "$soundLike": val } }); + return this; + } + + whichAreRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": true } }); + return this; + } + + whichAreNotRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": false } }); + return this; + } + withRequiredBooleanIsNot(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$ne": val } }); + return this; + } + + withRequiredBooleanIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$in": vals } }); + return this; + } + + withRequiredBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$notIn": vals } }); + return this; + } + + withRequiredBooleanGreaterThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gt": val } }); + return this; + } + + withRequiredBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gte": val } }); + return this; + } + + withRequiredBooleanLessThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lt": val } }); + return this; + } + + withRequiredBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lte": val } }); + return this; + } + + withRequiredBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "requiredBoolean": { "$between": [lower, upper] } }); + return this; + } + + withRequiredBooleanIsKnown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": false } }); + return this; + } + + withRequiredBooleanIsUnknown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": true } }); + return this; + } + + whichAreOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": true } }); + return this; + } + + whichAreNotOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": false } }); + return this; + } + withOptionalBooleanIsNot(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$ne": val } }); + return this; + } + + withOptionalBooleanIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$in": vals } }); + return this; + } + + withOptionalBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$notIn": vals } }); + return this; + } + + withOptionalBooleanGreaterThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gt": val } }); + return this; + } + + withOptionalBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gte": val } }); + return this; + } + + withOptionalBooleanLessThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lt": val } }); + return this; + } + + withOptionalBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lte": val } }); + return this; + } + + withOptionalBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "optionalBoolean": { "$between": [lower, upper] } }); + return this; + } + + withOptionalBooleanIsKnown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": false } }); + return this; + } + + withOptionalBooleanIsUnknown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": true } }); + return this; + } + + withRequiredIntegerIs(val: number): this { + this.filters.push({ "requiredInteger": { "$eq": val } }); + return this; + } + + withRequiredIntegerIsNot(val: number): this { + this.filters.push({ "requiredInteger": { "$ne": val } }); + return this; + } + + withRequiredIntegerIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$in": vals } }); + return this; + } + + withRequiredIntegerNotIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$notIn": vals } }); + return this; + } + + withRequiredIntegerGreaterThan(val: number): this { + this.filters.push({ "requiredInteger": { "$gt": val } }); + return this; + } + + withRequiredIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$gte": val } }); + return this; + } + + withRequiredIntegerLessThan(val: number): this { + this.filters.push({ "requiredInteger": { "$lt": val } }); + return this; + } + + withRequiredIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$lte": val } }); + return this; + } + + withRequiredIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "requiredInteger": { "$between": [lower, upper] } }); + return this; + } + + withRequiredIntegerIsKnown(): this { + this.filters.push({ "requiredInteger": { "$isNull": false } }); + return this; + } + + withRequiredIntegerIsUnknown(): this { + this.filters.push({ "requiredInteger": { "$isNull": true } }); + return this; + } + + withOptionalIntegerIs(val: number): this { + this.filters.push({ "optionalInteger": { "$eq": val } }); + return this; + } + + withOptionalIntegerIsNot(val: number): this { + this.filters.push({ "optionalInteger": { "$ne": val } }); + return this; + } + + withOptionalIntegerIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$in": vals } }); + return this; + } + + withOptionalIntegerNotIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$notIn": vals } }); + return this; + } + + withOptionalIntegerGreaterThan(val: number): this { + this.filters.push({ "optionalInteger": { "$gt": val } }); + return this; + } + + withOptionalIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$gte": val } }); + return this; + } + + withOptionalIntegerLessThan(val: number): this { + this.filters.push({ "optionalInteger": { "$lt": val } }); + return this; + } + + withOptionalIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$lte": val } }); + return this; + } + + withOptionalIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "optionalInteger": { "$between": [lower, upper] } }); + return this; + } + + withOptionalIntegerIsKnown(): this { + this.filters.push({ "optionalInteger": { "$isNull": false } }); + return this; + } + + withOptionalIntegerIsUnknown(): this { + this.filters.push({ "optionalInteger": { "$isNull": true } }); + return this; + } + + withRequiredLongIs(val: Long): this { + this.filters.push({ "requiredLong": { "$eq": val } }); + return this; + } + + withRequiredLongIsNot(val: Long): this { + this.filters.push({ "requiredLong": { "$ne": val } }); + return this; + } + + withRequiredLongIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$in": vals } }); + return this; + } + + withRequiredLongNotIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$notIn": vals } }); + return this; + } + + withRequiredLongGreaterThan(val: Long): this { + this.filters.push({ "requiredLong": { "$gt": val } }); + return this; + } + + withRequiredLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$gte": val } }); + return this; + } + + withRequiredLongLessThan(val: Long): this { + this.filters.push({ "requiredLong": { "$lt": val } }); + return this; + } + + withRequiredLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$lte": val } }); + return this; + } + + withRequiredLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "requiredLong": { "$between": [lower, upper] } }); + return this; + } + + withRequiredLongIsKnown(): this { + this.filters.push({ "requiredLong": { "$isNull": false } }); + return this; + } + + withRequiredLongIsUnknown(): this { + this.filters.push({ "requiredLong": { "$isNull": true } }); + return this; + } + + withOptionalLongIs(val: Long): this { + this.filters.push({ "optionalLong": { "$eq": val } }); + return this; + } + + withOptionalLongIsNot(val: Long): this { + this.filters.push({ "optionalLong": { "$ne": val } }); + return this; + } + + withOptionalLongIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$in": vals } }); + return this; + } + + withOptionalLongNotIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$notIn": vals } }); + return this; + } + + withOptionalLongGreaterThan(val: Long): this { + this.filters.push({ "optionalLong": { "$gt": val } }); + return this; + } + + withOptionalLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$gte": val } }); + return this; + } + + withOptionalLongLessThan(val: Long): this { + this.filters.push({ "optionalLong": { "$lt": val } }); + return this; + } + + withOptionalLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$lte": val } }); + return this; + } + + withOptionalLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "optionalLong": { "$between": [lower, upper] } }); + return this; + } + + withOptionalLongIsKnown(): this { + this.filters.push({ "optionalLong": { "$isNull": false } }); + return this; + } + + withOptionalLongIsUnknown(): this { + this.filters.push({ "optionalLong": { "$isNull": true } }); + return this; + } + + withRequiredDecimalIs(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$eq": val } }); + return this; + } + + withRequiredDecimalIsNot(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$ne": val } }); + return this; + } + + withRequiredDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$in": vals } }); + return this; + } + + withRequiredDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$notIn": vals } }); + return this; + } + + withRequiredDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gt": val } }); + return this; + } + + withRequiredDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gte": val } }); + return this; + } + + withRequiredDecimalLessThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lt": val } }); + return this; + } + + withRequiredDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lte": val } }); + return this; + } + + withRequiredDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "requiredDecimal": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDecimalIsKnown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": false } }); + return this; + } + + withRequiredDecimalIsUnknown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": true } }); + return this; + } + + withOptionalDecimalIs(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$eq": val } }); + return this; + } + + withOptionalDecimalIsNot(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$ne": val } }); + return this; + } + + withOptionalDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$in": vals } }); + return this; + } + + withOptionalDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$notIn": vals } }); + return this; + } + + withOptionalDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gt": val } }); + return this; + } + + withOptionalDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gte": val } }); + return this; + } + + withOptionalDecimalLessThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lt": val } }); + return this; + } + + withOptionalDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lte": val } }); + return this; + } + + withOptionalDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "optionalDecimal": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDecimalIsKnown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": false } }); + return this; + } + + withOptionalDecimalIsUnknown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": true } }); + return this; + } + + withRequiredFloatIs(val: number): this { + this.filters.push({ "requiredFloat": { "$eq": val } }); + return this; + } + + withRequiredFloatIsNot(val: number): this { + this.filters.push({ "requiredFloat": { "$ne": val } }); + return this; + } + + withRequiredFloatIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$in": vals } }); + return this; + } + + withRequiredFloatNotIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$notIn": vals } }); + return this; + } + + withRequiredFloatGreaterThan(val: number): this { + this.filters.push({ "requiredFloat": { "$gt": val } }); + return this; + } + + withRequiredFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$gte": val } }); + return this; + } + + withRequiredFloatLessThan(val: number): this { + this.filters.push({ "requiredFloat": { "$lt": val } }); + return this; + } + + withRequiredFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$lte": val } }); + return this; + } + + withRequiredFloatBetween(lower: number, upper: number): this { + this.filters.push({ "requiredFloat": { "$between": [lower, upper] } }); + return this; + } + + withRequiredFloatIsKnown(): this { + this.filters.push({ "requiredFloat": { "$isNull": false } }); + return this; + } + + withRequiredFloatIsUnknown(): this { + this.filters.push({ "requiredFloat": { "$isNull": true } }); + return this; + } + + withOptionalFloatIs(val: number): this { + this.filters.push({ "optionalFloat": { "$eq": val } }); + return this; + } + + withOptionalFloatIsNot(val: number): this { + this.filters.push({ "optionalFloat": { "$ne": val } }); + return this; + } + + withOptionalFloatIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$in": vals } }); + return this; + } + + withOptionalFloatNotIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$notIn": vals } }); + return this; + } + + withOptionalFloatGreaterThan(val: number): this { + this.filters.push({ "optionalFloat": { "$gt": val } }); + return this; + } + + withOptionalFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$gte": val } }); + return this; + } + + withOptionalFloatLessThan(val: number): this { + this.filters.push({ "optionalFloat": { "$lt": val } }); + return this; + } + + withOptionalFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$lte": val } }); + return this; + } + + withOptionalFloatBetween(lower: number, upper: number): this { + this.filters.push({ "optionalFloat": { "$between": [lower, upper] } }); + return this; + } + + withOptionalFloatIsKnown(): this { + this.filters.push({ "optionalFloat": { "$isNull": false } }); + return this; + } + + withOptionalFloatIsUnknown(): this { + this.filters.push({ "optionalFloat": { "$isNull": true } }); + return this; + } + + withRequiredDoubleIs(val: number): this { + this.filters.push({ "requiredDouble": { "$eq": val } }); + return this; + } + + withRequiredDoubleIsNot(val: number): this { + this.filters.push({ "requiredDouble": { "$ne": val } }); + return this; + } + + withRequiredDoubleIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$in": vals } }); + return this; + } + + withRequiredDoubleNotIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$notIn": vals } }); + return this; + } + + withRequiredDoubleGreaterThan(val: number): this { + this.filters.push({ "requiredDouble": { "$gt": val } }); + return this; + } + + withRequiredDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$gte": val } }); + return this; + } + + withRequiredDoubleLessThan(val: number): this { + this.filters.push({ "requiredDouble": { "$lt": val } }); + return this; + } + + withRequiredDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$lte": val } }); + return this; + } + + withRequiredDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "requiredDouble": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDoubleIsKnown(): this { + this.filters.push({ "requiredDouble": { "$isNull": false } }); + return this; + } + + withRequiredDoubleIsUnknown(): this { + this.filters.push({ "requiredDouble": { "$isNull": true } }); + return this; + } + + withOptionalDoubleIs(val: number): this { + this.filters.push({ "optionalDouble": { "$eq": val } }); + return this; + } + + withOptionalDoubleIsNot(val: number): this { + this.filters.push({ "optionalDouble": { "$ne": val } }); + return this; + } + + withOptionalDoubleIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$in": vals } }); + return this; + } + + withOptionalDoubleNotIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$notIn": vals } }); + return this; + } + + withOptionalDoubleGreaterThan(val: number): this { + this.filters.push({ "optionalDouble": { "$gt": val } }); + return this; + } + + withOptionalDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$gte": val } }); + return this; + } + + withOptionalDoubleLessThan(val: number): this { + this.filters.push({ "optionalDouble": { "$lt": val } }); + return this; + } + + withOptionalDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$lte": val } }); + return this; + } + + withOptionalDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "optionalDouble": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDoubleIsKnown(): this { + this.filters.push({ "optionalDouble": { "$isNull": false } }); + return this; + } + + withOptionalDoubleIsUnknown(): this { + this.filters.push({ "optionalDouble": { "$isNull": true } }); + return this; + } + + withRequiredDateIs(val: string): this { + this.filters.push({ "requiredDate": { "$eq": val } }); + return this; + } + + withRequiredDateIsNot(val: string): this { + this.filters.push({ "requiredDate": { "$ne": val } }); + return this; + } + + withRequiredDateIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$in": vals } }); + return this; + } + + withRequiredDateNotIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$notIn": vals } }); + return this; + } + + withRequiredDateGreaterThan(val: string): this { + this.filters.push({ "requiredDate": { "$gt": val } }); + return this; + } + + withRequiredDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$gte": val } }); + return this; + } + + withRequiredDateLessThan(val: string): this { + this.filters.push({ "requiredDate": { "$lt": val } }); + return this; + } + + withRequiredDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$lte": val } }); + return this; + } + + withRequiredDateBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDate": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDateIsKnown(): this { + this.filters.push({ "requiredDate": { "$isNull": false } }); + return this; + } + + withRequiredDateIsUnknown(): this { + this.filters.push({ "requiredDate": { "$isNull": true } }); + return this; + } + + withOptionalDateIs(val: string): this { + this.filters.push({ "optionalDate": { "$eq": val } }); + return this; + } + + withOptionalDateIsNot(val: string): this { + this.filters.push({ "optionalDate": { "$ne": val } }); + return this; + } + + withOptionalDateIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$in": vals } }); + return this; + } + + withOptionalDateNotIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$notIn": vals } }); + return this; + } + + withOptionalDateGreaterThan(val: string): this { + this.filters.push({ "optionalDate": { "$gt": val } }); + return this; + } + + withOptionalDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$gte": val } }); + return this; + } + + withOptionalDateLessThan(val: string): this { + this.filters.push({ "optionalDate": { "$lt": val } }); + return this; + } + + withOptionalDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$lte": val } }); + return this; + } + + withOptionalDateBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDate": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDateIsKnown(): this { + this.filters.push({ "optionalDate": { "$isNull": false } }); + return this; + } + + withOptionalDateIsUnknown(): this { + this.filters.push({ "optionalDate": { "$isNull": true } }); + return this; + } + + withRequiredTimeIs(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$eq": val } }); + return this; + } + + withRequiredTimeIsNot(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$ne": val } }); + return this; + } + + withRequiredTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$in": vals } }); + return this; + } + + withRequiredTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$notIn": vals } }); + return this; + } + + withRequiredTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gt": val } }); + return this; + } + + withRequiredTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gte": val } }); + return this; + } + + withRequiredTimeLessThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lt": val } }); + return this; + } + + withRequiredTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lte": val } }); + return this; + } + + withRequiredTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "requiredTime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredTimeIsKnown(): this { + this.filters.push({ "requiredTime": { "$isNull": false } }); + return this; + } + + withRequiredTimeIsUnknown(): this { + this.filters.push({ "requiredTime": { "$isNull": true } }); + return this; + } + + withOptionalTimeIs(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$eq": val } }); + return this; + } + + withOptionalTimeIsNot(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$ne": val } }); + return this; + } + + withOptionalTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$in": vals } }); + return this; + } + + withOptionalTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$notIn": vals } }); + return this; + } + + withOptionalTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gt": val } }); + return this; + } + + withOptionalTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gte": val } }); + return this; + } + + withOptionalTimeLessThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lt": val } }); + return this; + } + + withOptionalTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lte": val } }); + return this; + } + + withOptionalTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "optionalTime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalTimeIsKnown(): this { + this.filters.push({ "optionalTime": { "$isNull": false } }); + return this; + } + + withOptionalTimeIsUnknown(): this { + this.filters.push({ "optionalTime": { "$isNull": true } }); + return this; + } + + withRequiredDatetimeIs(val: string): this { + this.filters.push({ "requiredDatetime": { "$eq": val } }); + return this; + } + + withRequiredDatetimeIsNot(val: string): this { + this.filters.push({ "requiredDatetime": { "$ne": val } }); + return this; + } + + withRequiredDatetimeIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$in": vals } }); + return this; + } + + withRequiredDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$notIn": vals } }); + return this; + } + + withRequiredDatetimeGreaterThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$gt": val } }); + return this; + } + + withRequiredDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$gte": val } }); + return this; + } + + withRequiredDatetimeLessThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$lt": val } }); + return this; + } + + withRequiredDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$lte": val } }); + return this; + } + + withRequiredDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDatetime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDatetimeIsKnown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": false } }); + return this; + } + + withRequiredDatetimeIsUnknown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": true } }); + return this; + } + + withOptionalDatetimeIs(val: string): this { + this.filters.push({ "optionalDatetime": { "$eq": val } }); + return this; + } + + withOptionalDatetimeIsNot(val: string): this { + this.filters.push({ "optionalDatetime": { "$ne": val } }); + return this; + } + + withOptionalDatetimeIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$in": vals } }); + return this; + } + + withOptionalDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$notIn": vals } }); + return this; + } + + withOptionalDatetimeGreaterThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$gt": val } }); + return this; + } + + withOptionalDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$gte": val } }); + return this; + } + + withOptionalDatetimeLessThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$lt": val } }); + return this; + } + + withOptionalDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$lte": val } }); + return this; + } + + withOptionalDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDatetime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDatetimeIsKnown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": false } }); + return this; + } + + withOptionalDatetimeIsUnknown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByRequiredStringAscending(): this { + this.query.orderBy("requiredString", "asc"); + return this; + } + + orderByRequiredStringDescending(): this { + this.query.orderBy("requiredString", "desc"); + return this; + } + + orderByOptionalStringAscending(): this { + this.query.orderBy("optionalString", "asc"); + return this; + } + + orderByOptionalStringDescending(): this { + this.query.orderBy("optionalString", "desc"); + return this; + } + + orderByLargeTextAscending(): this { + this.query.orderBy("largeText", "asc"); + return this; + } + + orderByLargeTextDescending(): this { + this.query.orderBy("largeText", "desc"); + return this; + } + + orderByRequiredBooleanAscending(): this { + this.query.orderBy("requiredBoolean", "asc"); + return this; + } + + orderByRequiredBooleanDescending(): this { + this.query.orderBy("requiredBoolean", "desc"); + return this; + } + + orderByOptionalBooleanAscending(): this { + this.query.orderBy("optionalBoolean", "asc"); + return this; + } + + orderByOptionalBooleanDescending(): this { + this.query.orderBy("optionalBoolean", "desc"); + return this; + } + + orderByRequiredIntegerAscending(): this { + this.query.orderBy("requiredInteger", "asc"); + return this; + } + + orderByRequiredIntegerDescending(): this { + this.query.orderBy("requiredInteger", "desc"); + return this; + } + + orderByOptionalIntegerAscending(): this { + this.query.orderBy("optionalInteger", "asc"); + return this; + } + + orderByOptionalIntegerDescending(): this { + this.query.orderBy("optionalInteger", "desc"); + return this; + } + + orderByRequiredLongAscending(): this { + this.query.orderBy("requiredLong", "asc"); + return this; + } + + orderByRequiredLongDescending(): this { + this.query.orderBy("requiredLong", "desc"); + return this; + } + + orderByOptionalLongAscending(): this { + this.query.orderBy("optionalLong", "asc"); + return this; + } + + orderByOptionalLongDescending(): this { + this.query.orderBy("optionalLong", "desc"); + return this; + } + + orderByRequiredDecimalAscending(): this { + this.query.orderBy("requiredDecimal", "asc"); + return this; + } + + orderByRequiredDecimalDescending(): this { + this.query.orderBy("requiredDecimal", "desc"); + return this; + } + + orderByOptionalDecimalAscending(): this { + this.query.orderBy("optionalDecimal", "asc"); + return this; + } + + orderByOptionalDecimalDescending(): this { + this.query.orderBy("optionalDecimal", "desc"); + return this; + } + + orderByRequiredFloatAscending(): this { + this.query.orderBy("requiredFloat", "asc"); + return this; + } + + orderByRequiredFloatDescending(): this { + this.query.orderBy("requiredFloat", "desc"); + return this; + } + + orderByOptionalFloatAscending(): this { + this.query.orderBy("optionalFloat", "asc"); + return this; + } + + orderByOptionalFloatDescending(): this { + this.query.orderBy("optionalFloat", "desc"); + return this; + } + + orderByRequiredDoubleAscending(): this { + this.query.orderBy("requiredDouble", "asc"); + return this; + } + + orderByRequiredDoubleDescending(): this { + this.query.orderBy("requiredDouble", "desc"); + return this; + } + + orderByOptionalDoubleAscending(): this { + this.query.orderBy("optionalDouble", "asc"); + return this; + } + + orderByOptionalDoubleDescending(): this { + this.query.orderBy("optionalDouble", "desc"); + return this; + } + + orderByRequiredDateAscending(): this { + this.query.orderBy("requiredDate", "asc"); + return this; + } + + orderByRequiredDateDescending(): this { + this.query.orderBy("requiredDate", "desc"); + return this; + } + + orderByOptionalDateAscending(): this { + this.query.orderBy("optionalDate", "asc"); + return this; + } + + orderByOptionalDateDescending(): this { + this.query.orderBy("optionalDate", "desc"); + return this; + } + + orderByRequiredTimeAscending(): this { + this.query.orderBy("requiredTime", "asc"); + return this; + } + + orderByRequiredTimeDescending(): this { + this.query.orderBy("requiredTime", "desc"); + return this; + } + + orderByOptionalTimeAscending(): this { + this.query.orderBy("optionalTime", "asc"); + return this; + } + + orderByOptionalTimeDescending(): this { + this.query.orderBy("optionalTime", "desc"); + return this; + } + + orderByRequiredDatetimeAscending(): this { + this.query.orderBy("requiredDatetime", "asc"); + return this; + } + + orderByRequiredDatetimeDescending(): this { + this.query.orderBy("requiredDatetime", "desc"); + return this; + } + + orderByOptionalDatetimeAscending(): this { + this.query.orderBy("optionalDatetime", "asc"); + return this; + } + + orderByOptionalDatetimeDescending(): this { + this.query.orderBy("optionalDatetime", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minRequiredInteger(): this { + return this.minRequiredIntegerAs("minOfRequiredInteger"); + } + + minRequiredIntegerAs(retName: string): this { + this.query.aggregate("min", "requiredInteger", retName); + return this; + } + maxRequiredInteger(): this { + return this.maxRequiredIntegerAs("maxOfRequiredInteger"); + } + + maxRequiredIntegerAs(retName: string): this { + this.query.aggregate("max", "requiredInteger", retName); + return this; + } + sumRequiredInteger(): this { + return this.sumRequiredIntegerAs("sumOfRequiredInteger"); + } + + sumRequiredIntegerAs(retName: string): this { + this.query.aggregate("sum", "requiredInteger", retName); + return this; + } + avgRequiredInteger(): this { + return this.avgRequiredIntegerAs("avgOfRequiredInteger"); + } + + avgRequiredIntegerAs(retName: string): this { + this.query.aggregate("avg", "requiredInteger", retName); + return this; + } + standardDeviationRequiredInteger(): this { + return this.standardDeviationRequiredIntegerAs("standardDeviationOfRequiredInteger"); + } + + standardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev", "requiredInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredInteger(): this { + return this.squareRootOfPopulationStandardDeviationRequiredIntegerAs("squareRootOfPopulationStandardDeviationOfRequiredInteger"); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredInteger", retName); + return this; + } + sampleVarianceRequiredInteger(): this { + return this.sampleVarianceRequiredIntegerAs("sampleVarianceOfRequiredInteger"); + } + + sampleVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "requiredInteger", retName); + return this; + } + samplePopulationVarianceRequiredInteger(): this { + return this.samplePopulationVarianceRequiredIntegerAs("samplePopulationVarianceOfRequiredInteger"); + } + + samplePopulationVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "requiredInteger", retName); + return this; + } + minOptionalInteger(): this { + return this.minOptionalIntegerAs("minOfOptionalInteger"); + } + + minOptionalIntegerAs(retName: string): this { + this.query.aggregate("min", "optionalInteger", retName); + return this; + } + maxOptionalInteger(): this { + return this.maxOptionalIntegerAs("maxOfOptionalInteger"); + } + + maxOptionalIntegerAs(retName: string): this { + this.query.aggregate("max", "optionalInteger", retName); + return this; + } + sumOptionalInteger(): this { + return this.sumOptionalIntegerAs("sumOfOptionalInteger"); + } + + sumOptionalIntegerAs(retName: string): this { + this.query.aggregate("sum", "optionalInteger", retName); + return this; + } + avgOptionalInteger(): this { + return this.avgOptionalIntegerAs("avgOfOptionalInteger"); + } + + avgOptionalIntegerAs(retName: string): this { + this.query.aggregate("avg", "optionalInteger", retName); + return this; + } + standardDeviationOptionalInteger(): this { + return this.standardDeviationOptionalIntegerAs("standardDeviationOfOptionalInteger"); + } + + standardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev", "optionalInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalInteger(): this { + return this.squareRootOfPopulationStandardDeviationOptionalIntegerAs("squareRootOfPopulationStandardDeviationOfOptionalInteger"); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalInteger", retName); + return this; + } + sampleVarianceOptionalInteger(): this { + return this.sampleVarianceOptionalIntegerAs("sampleVarianceOfOptionalInteger"); + } + + sampleVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "optionalInteger", retName); + return this; + } + samplePopulationVarianceOptionalInteger(): this { + return this.samplePopulationVarianceOptionalIntegerAs("samplePopulationVarianceOfOptionalInteger"); + } + + samplePopulationVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "optionalInteger", retName); + return this; + } + minRequiredLong(): this { + return this.minRequiredLongAs("minOfRequiredLong"); + } + + minRequiredLongAs(retName: string): this { + this.query.aggregate("min", "requiredLong", retName); + return this; + } + maxRequiredLong(): this { + return this.maxRequiredLongAs("maxOfRequiredLong"); + } + + maxRequiredLongAs(retName: string): this { + this.query.aggregate("max", "requiredLong", retName); + return this; + } + sumRequiredLong(): this { + return this.sumRequiredLongAs("sumOfRequiredLong"); + } + + sumRequiredLongAs(retName: string): this { + this.query.aggregate("sum", "requiredLong", retName); + return this; + } + avgRequiredLong(): this { + return this.avgRequiredLongAs("avgOfRequiredLong"); + } + + avgRequiredLongAs(retName: string): this { + this.query.aggregate("avg", "requiredLong", retName); + return this; + } + standardDeviationRequiredLong(): this { + return this.standardDeviationRequiredLongAs("standardDeviationOfRequiredLong"); + } + + standardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev", "requiredLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLong(): this { + return this.squareRootOfPopulationStandardDeviationRequiredLongAs("squareRootOfPopulationStandardDeviationOfRequiredLong"); + } + + squareRootOfPopulationStandardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredLong", retName); + return this; + } + sampleVarianceRequiredLong(): this { + return this.sampleVarianceRequiredLongAs("sampleVarianceOfRequiredLong"); + } + + sampleVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_samp", "requiredLong", retName); + return this; + } + samplePopulationVarianceRequiredLong(): this { + return this.samplePopulationVarianceRequiredLongAs("samplePopulationVarianceOfRequiredLong"); + } + + samplePopulationVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_pop", "requiredLong", retName); + return this; + } + minOptionalLong(): this { + return this.minOptionalLongAs("minOfOptionalLong"); + } + + minOptionalLongAs(retName: string): this { + this.query.aggregate("min", "optionalLong", retName); + return this; + } + maxOptionalLong(): this { + return this.maxOptionalLongAs("maxOfOptionalLong"); + } + + maxOptionalLongAs(retName: string): this { + this.query.aggregate("max", "optionalLong", retName); + return this; + } + sumOptionalLong(): this { + return this.sumOptionalLongAs("sumOfOptionalLong"); + } + + sumOptionalLongAs(retName: string): this { + this.query.aggregate("sum", "optionalLong", retName); + return this; + } + avgOptionalLong(): this { + return this.avgOptionalLongAs("avgOfOptionalLong"); + } + + avgOptionalLongAs(retName: string): this { + this.query.aggregate("avg", "optionalLong", retName); + return this; + } + standardDeviationOptionalLong(): this { + return this.standardDeviationOptionalLongAs("standardDeviationOfOptionalLong"); + } + + standardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev", "optionalLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLong(): this { + return this.squareRootOfPopulationStandardDeviationOptionalLongAs("squareRootOfPopulationStandardDeviationOfOptionalLong"); + } + + squareRootOfPopulationStandardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalLong", retName); + return this; + } + sampleVarianceOptionalLong(): this { + return this.sampleVarianceOptionalLongAs("sampleVarianceOfOptionalLong"); + } + + sampleVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_samp", "optionalLong", retName); + return this; + } + samplePopulationVarianceOptionalLong(): this { + return this.samplePopulationVarianceOptionalLongAs("samplePopulationVarianceOfOptionalLong"); + } + + samplePopulationVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_pop", "optionalLong", retName); + return this; + } + minRequiredDecimal(): this { + return this.minRequiredDecimalAs("minOfRequiredDecimal"); + } + + minRequiredDecimalAs(retName: string): this { + this.query.aggregate("min", "requiredDecimal", retName); + return this; + } + maxRequiredDecimal(): this { + return this.maxRequiredDecimalAs("maxOfRequiredDecimal"); + } + + maxRequiredDecimalAs(retName: string): this { + this.query.aggregate("max", "requiredDecimal", retName); + return this; + } + sumRequiredDecimal(): this { + return this.sumRequiredDecimalAs("sumOfRequiredDecimal"); + } + + sumRequiredDecimalAs(retName: string): this { + this.query.aggregate("sum", "requiredDecimal", retName); + return this; + } + avgRequiredDecimal(): this { + return this.avgRequiredDecimalAs("avgOfRequiredDecimal"); + } + + avgRequiredDecimalAs(retName: string): this { + this.query.aggregate("avg", "requiredDecimal", retName); + return this; + } + standardDeviationRequiredDecimal(): this { + return this.standardDeviationRequiredDecimalAs("standardDeviationOfRequiredDecimal"); + } + + standardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev", "requiredDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimal(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDecimalAs("squareRootOfPopulationStandardDeviationOfRequiredDecimal"); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDecimal", retName); + return this; + } + sampleVarianceRequiredDecimal(): this { + return this.sampleVarianceRequiredDecimalAs("sampleVarianceOfRequiredDecimal"); + } + + sampleVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDecimal", retName); + return this; + } + samplePopulationVarianceRequiredDecimal(): this { + return this.samplePopulationVarianceRequiredDecimalAs("samplePopulationVarianceOfRequiredDecimal"); + } + + samplePopulationVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDecimal", retName); + return this; + } + minOptionalDecimal(): this { + return this.minOptionalDecimalAs("minOfOptionalDecimal"); + } + + minOptionalDecimalAs(retName: string): this { + this.query.aggregate("min", "optionalDecimal", retName); + return this; + } + maxOptionalDecimal(): this { + return this.maxOptionalDecimalAs("maxOfOptionalDecimal"); + } + + maxOptionalDecimalAs(retName: string): this { + this.query.aggregate("max", "optionalDecimal", retName); + return this; + } + sumOptionalDecimal(): this { + return this.sumOptionalDecimalAs("sumOfOptionalDecimal"); + } + + sumOptionalDecimalAs(retName: string): this { + this.query.aggregate("sum", "optionalDecimal", retName); + return this; + } + avgOptionalDecimal(): this { + return this.avgOptionalDecimalAs("avgOfOptionalDecimal"); + } + + avgOptionalDecimalAs(retName: string): this { + this.query.aggregate("avg", "optionalDecimal", retName); + return this; + } + standardDeviationOptionalDecimal(): this { + return this.standardDeviationOptionalDecimalAs("standardDeviationOfOptionalDecimal"); + } + + standardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev", "optionalDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimal(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDecimalAs("squareRootOfPopulationStandardDeviationOfOptionalDecimal"); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDecimal", retName); + return this; + } + sampleVarianceOptionalDecimal(): this { + return this.sampleVarianceOptionalDecimalAs("sampleVarianceOfOptionalDecimal"); + } + + sampleVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDecimal", retName); + return this; + } + samplePopulationVarianceOptionalDecimal(): this { + return this.samplePopulationVarianceOptionalDecimalAs("samplePopulationVarianceOfOptionalDecimal"); + } + + samplePopulationVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDecimal", retName); + return this; + } + minRequiredFloat(): this { + return this.minRequiredFloatAs("minOfRequiredFloat"); + } + + minRequiredFloatAs(retName: string): this { + this.query.aggregate("min", "requiredFloat", retName); + return this; + } + maxRequiredFloat(): this { + return this.maxRequiredFloatAs("maxOfRequiredFloat"); + } + + maxRequiredFloatAs(retName: string): this { + this.query.aggregate("max", "requiredFloat", retName); + return this; + } + sumRequiredFloat(): this { + return this.sumRequiredFloatAs("sumOfRequiredFloat"); + } + + sumRequiredFloatAs(retName: string): this { + this.query.aggregate("sum", "requiredFloat", retName); + return this; + } + avgRequiredFloat(): this { + return this.avgRequiredFloatAs("avgOfRequiredFloat"); + } + + avgRequiredFloatAs(retName: string): this { + this.query.aggregate("avg", "requiredFloat", retName); + return this; + } + standardDeviationRequiredFloat(): this { + return this.standardDeviationRequiredFloatAs("standardDeviationOfRequiredFloat"); + } + + standardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev", "requiredFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloat(): this { + return this.squareRootOfPopulationStandardDeviationRequiredFloatAs("squareRootOfPopulationStandardDeviationOfRequiredFloat"); + } + + squareRootOfPopulationStandardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredFloat", retName); + return this; + } + sampleVarianceRequiredFloat(): this { + return this.sampleVarianceRequiredFloatAs("sampleVarianceOfRequiredFloat"); + } + + sampleVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_samp", "requiredFloat", retName); + return this; + } + samplePopulationVarianceRequiredFloat(): this { + return this.samplePopulationVarianceRequiredFloatAs("samplePopulationVarianceOfRequiredFloat"); + } + + samplePopulationVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_pop", "requiredFloat", retName); + return this; + } + minOptionalFloat(): this { + return this.minOptionalFloatAs("minOfOptionalFloat"); + } + + minOptionalFloatAs(retName: string): this { + this.query.aggregate("min", "optionalFloat", retName); + return this; + } + maxOptionalFloat(): this { + return this.maxOptionalFloatAs("maxOfOptionalFloat"); + } + + maxOptionalFloatAs(retName: string): this { + this.query.aggregate("max", "optionalFloat", retName); + return this; + } + sumOptionalFloat(): this { + return this.sumOptionalFloatAs("sumOfOptionalFloat"); + } + + sumOptionalFloatAs(retName: string): this { + this.query.aggregate("sum", "optionalFloat", retName); + return this; + } + avgOptionalFloat(): this { + return this.avgOptionalFloatAs("avgOfOptionalFloat"); + } + + avgOptionalFloatAs(retName: string): this { + this.query.aggregate("avg", "optionalFloat", retName); + return this; + } + standardDeviationOptionalFloat(): this { + return this.standardDeviationOptionalFloatAs("standardDeviationOfOptionalFloat"); + } + + standardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev", "optionalFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloat(): this { + return this.squareRootOfPopulationStandardDeviationOptionalFloatAs("squareRootOfPopulationStandardDeviationOfOptionalFloat"); + } + + squareRootOfPopulationStandardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalFloat", retName); + return this; + } + sampleVarianceOptionalFloat(): this { + return this.sampleVarianceOptionalFloatAs("sampleVarianceOfOptionalFloat"); + } + + sampleVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_samp", "optionalFloat", retName); + return this; + } + samplePopulationVarianceOptionalFloat(): this { + return this.samplePopulationVarianceOptionalFloatAs("samplePopulationVarianceOfOptionalFloat"); + } + + samplePopulationVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_pop", "optionalFloat", retName); + return this; + } + minRequiredDouble(): this { + return this.minRequiredDoubleAs("minOfRequiredDouble"); + } + + minRequiredDoubleAs(retName: string): this { + this.query.aggregate("min", "requiredDouble", retName); + return this; + } + maxRequiredDouble(): this { + return this.maxRequiredDoubleAs("maxOfRequiredDouble"); + } + + maxRequiredDoubleAs(retName: string): this { + this.query.aggregate("max", "requiredDouble", retName); + return this; + } + sumRequiredDouble(): this { + return this.sumRequiredDoubleAs("sumOfRequiredDouble"); + } + + sumRequiredDoubleAs(retName: string): this { + this.query.aggregate("sum", "requiredDouble", retName); + return this; + } + avgRequiredDouble(): this { + return this.avgRequiredDoubleAs("avgOfRequiredDouble"); + } + + avgRequiredDoubleAs(retName: string): this { + this.query.aggregate("avg", "requiredDouble", retName); + return this; + } + standardDeviationRequiredDouble(): this { + return this.standardDeviationRequiredDoubleAs("standardDeviationOfRequiredDouble"); + } + + standardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev", "requiredDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDouble(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDoubleAs("squareRootOfPopulationStandardDeviationOfRequiredDouble"); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDouble", retName); + return this; + } + sampleVarianceRequiredDouble(): this { + return this.sampleVarianceRequiredDoubleAs("sampleVarianceOfRequiredDouble"); + } + + sampleVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDouble", retName); + return this; + } + samplePopulationVarianceRequiredDouble(): this { + return this.samplePopulationVarianceRequiredDoubleAs("samplePopulationVarianceOfRequiredDouble"); + } + + samplePopulationVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDouble", retName); + return this; + } + minOptionalDouble(): this { + return this.minOptionalDoubleAs("minOfOptionalDouble"); + } + + minOptionalDoubleAs(retName: string): this { + this.query.aggregate("min", "optionalDouble", retName); + return this; + } + maxOptionalDouble(): this { + return this.maxOptionalDoubleAs("maxOfOptionalDouble"); + } + + maxOptionalDoubleAs(retName: string): this { + this.query.aggregate("max", "optionalDouble", retName); + return this; + } + sumOptionalDouble(): this { + return this.sumOptionalDoubleAs("sumOfOptionalDouble"); + } + + sumOptionalDoubleAs(retName: string): this { + this.query.aggregate("sum", "optionalDouble", retName); + return this; + } + avgOptionalDouble(): this { + return this.avgOptionalDoubleAs("avgOfOptionalDouble"); + } + + avgOptionalDoubleAs(retName: string): this { + this.query.aggregate("avg", "optionalDouble", retName); + return this; + } + standardDeviationOptionalDouble(): this { + return this.standardDeviationOptionalDoubleAs("standardDeviationOfOptionalDouble"); + } + + standardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev", "optionalDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDouble(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDoubleAs("squareRootOfPopulationStandardDeviationOfOptionalDouble"); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDouble", retName); + return this; + } + sampleVarianceOptionalDouble(): this { + return this.sampleVarianceOptionalDoubleAs("sampleVarianceOfOptionalDouble"); + } + + sampleVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDouble", retName); + return this; + } + samplePopulationVarianceOptionalDouble(): this { + return this.samplePopulationVarianceOptionalDoubleAs("samplePopulationVarianceOfOptionalDouble"); + } + + samplePopulationVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDouble", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByTypePlatform(): this { + this.query.groupBy("typePlatform"); + return this; + } + + groupByTypePlatformAs(retName: string): this { + this.query.groupBy("typePlatform", retName); + return this; + } + groupByRequiredString(): this { + this.query.groupBy("requiredString"); + return this; + } + + groupByRequiredStringAs(retName: string): this { + this.query.groupBy("requiredString", retName); + return this; + } + groupByOptionalString(): this { + this.query.groupBy("optionalString"); + return this; + } + + groupByOptionalStringAs(retName: string): this { + this.query.groupBy("optionalString", retName); + return this; + } + groupByLargeText(): this { + this.query.groupBy("largeText"); + return this; + } + + groupByLargeTextAs(retName: string): this { + this.query.groupBy("largeText", retName); + return this; + } + groupByRequiredBoolean(): this { + this.query.groupBy("requiredBoolean"); + return this; + } + + groupByRequiredBooleanAs(retName: string): this { + this.query.groupBy("requiredBoolean", retName); + return this; + } + groupByOptionalBoolean(): this { + this.query.groupBy("optionalBoolean"); + return this; + } + + groupByOptionalBooleanAs(retName: string): this { + this.query.groupBy("optionalBoolean", retName); + return this; + } + groupByRequiredInteger(): this { + this.query.groupBy("requiredInteger"); + return this; + } + + groupByRequiredIntegerAs(retName: string): this { + this.query.groupBy("requiredInteger", retName); + return this; + } + groupByOptionalInteger(): this { + this.query.groupBy("optionalInteger"); + return this; + } + + groupByOptionalIntegerAs(retName: string): this { + this.query.groupBy("optionalInteger", retName); + return this; + } + groupByRequiredLong(): this { + this.query.groupBy("requiredLong"); + return this; + } + + groupByRequiredLongAs(retName: string): this { + this.query.groupBy("requiredLong", retName); + return this; + } + groupByOptionalLong(): this { + this.query.groupBy("optionalLong"); + return this; + } + + groupByOptionalLongAs(retName: string): this { + this.query.groupBy("optionalLong", retName); + return this; + } + groupByRequiredDecimal(): this { + this.query.groupBy("requiredDecimal"); + return this; + } + + groupByRequiredDecimalAs(retName: string): this { + this.query.groupBy("requiredDecimal", retName); + return this; + } + groupByOptionalDecimal(): this { + this.query.groupBy("optionalDecimal"); + return this; + } + + groupByOptionalDecimalAs(retName: string): this { + this.query.groupBy("optionalDecimal", retName); + return this; + } + groupByRequiredFloat(): this { + this.query.groupBy("requiredFloat"); + return this; + } + + groupByRequiredFloatAs(retName: string): this { + this.query.groupBy("requiredFloat", retName); + return this; + } + groupByOptionalFloat(): this { + this.query.groupBy("optionalFloat"); + return this; + } + + groupByOptionalFloatAs(retName: string): this { + this.query.groupBy("optionalFloat", retName); + return this; + } + groupByRequiredDouble(): this { + this.query.groupBy("requiredDouble"); + return this; + } + + groupByRequiredDoubleAs(retName: string): this { + this.query.groupBy("requiredDouble", retName); + return this; + } + groupByOptionalDouble(): this { + this.query.groupBy("optionalDouble"); + return this; + } + + groupByOptionalDoubleAs(retName: string): this { + this.query.groupBy("optionalDouble", retName); + return this; + } + groupByRequiredDate(): this { + this.query.groupBy("requiredDate"); + return this; + } + + groupByRequiredDateAs(retName: string): this { + this.query.groupBy("requiredDate", retName); + return this; + } + groupByOptionalDate(): this { + this.query.groupBy("optionalDate"); + return this; + } + + groupByOptionalDateAs(retName: string): this { + this.query.groupBy("optionalDate", retName); + return this; + } + groupByRequiredTime(): this { + this.query.groupBy("requiredTime"); + return this; + } + + groupByRequiredTimeAs(retName: string): this { + this.query.groupBy("requiredTime", retName); + return this; + } + groupByOptionalTime(): this { + this.query.groupBy("optionalTime"); + return this; + } + + groupByOptionalTimeAs(retName: string): this { + this.query.groupBy("optionalTime", retName); + return this; + } + groupByRequiredDatetime(): this { + this.query.groupBy("requiredDatetime"); + return this; + } + + groupByRequiredDatetimeAs(retName: string): this { + this.query.groupBy("requiredDatetime", retName); + return this; + } + groupByOptionalDatetime(): this { + this.query.groupBy("optionalDatetime"); + return this; + } + + groupByOptionalDatetimeAs(retName: string): this { + this.query.groupBy("optionalDatetime", retName); + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime", retName); + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + facetByTypePlatformAs( + facetName: string, + request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "typePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByTypePlatformAs", relation: "typePlatform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof ScalarTypeProbe + ? entity + : ScalarTypeProbe.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableScalarTypeProbeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return ScalarTypeProbe.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/requests/TypePlatformRequest.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/requests/TypePlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d0caed3d9719c20a917e89fdcad7bad64597fb0 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/generated/requests/TypePlatformRequest.ts @@ -0,0 +1,1736 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { TypePlatform } from '../models/TypePlatform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class TypePlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("TypePlatform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "TypePlatform" { + return "TypePlatform"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTypePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableTypePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectScalarTypeProbeListWith(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "scalarTypeProbeList", request.toQuery(), "id", "typePlatform", true, + { kind: "relation-select", method: "selectScalarTypeProbeListWith", relation: "scalarTypeProbeList" }); + return this; + } + + haveScalarTypeProbes(): this { + return this.withScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + haveNoScalarTypeProbes(): this { + return this.withoutScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + withScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + withoutScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + countScalarTypeProbes(): this { + return this.countScalarTypeProbesAs("countScalarTypeProbes"); + } + + countScalarTypeProbesAs(alias: string): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + this.countScalarTypeProbesWith(alias, { entityName: "ScalarTypeProbe", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }; + return this; + } + + countScalarTypeProbesWith(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "relation-count", method: "countScalarTypeProbesWith", relation: "scalarTypeProbeList", alias }); + return this; + } + + minRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredIntegerOfScalarTypeProbesAs( + "minOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredIntegerOfScalarTypeProbesAs( + "maxOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredIntegerOfScalarTypeProbesAs( + "sumOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredIntegerOfScalarTypeProbesAs( + "avgOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredIntegerOfScalarTypeProbesAs( + "standardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredIntegerOfScalarTypeProbesAs( + "sampleVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalIntegerOfScalarTypeProbesAs( + "minOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalIntegerOfScalarTypeProbesAs( + "maxOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalIntegerOfScalarTypeProbesAs( + "sumOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalIntegerOfScalarTypeProbesAs( + "avgOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalIntegerOfScalarTypeProbesAs( + "standardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalIntegerOfScalarTypeProbesAs( + "sampleVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredLongOfScalarTypeProbesAs( + "minOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredLongOfScalarTypeProbesAs( + "maxOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredLongOfScalarTypeProbesAs( + "sumOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredLongOfScalarTypeProbesAs( + "avgOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredLongOfScalarTypeProbesAs( + "standardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredLongOfScalarTypeProbesAs( + "sampleVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalLongOfScalarTypeProbesAs( + "minOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalLongOfScalarTypeProbesAs( + "maxOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalLongOfScalarTypeProbesAs( + "sumOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalLongOfScalarTypeProbesAs( + "avgOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalLongOfScalarTypeProbesAs( + "standardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalLongOfScalarTypeProbesAs( + "sampleVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDecimalOfScalarTypeProbesAs( + "minOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDecimalOfScalarTypeProbesAs( + "maxOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDecimalOfScalarTypeProbesAs( + "sumOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDecimalOfScalarTypeProbesAs( + "avgOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDecimalOfScalarTypeProbesAs( + "standardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDecimalOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDecimalOfScalarTypeProbesAs( + "minOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDecimalOfScalarTypeProbesAs( + "maxOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDecimalOfScalarTypeProbesAs( + "sumOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDecimalOfScalarTypeProbesAs( + "avgOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDecimalOfScalarTypeProbesAs( + "standardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDecimalOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredFloatOfScalarTypeProbesAs( + "minOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredFloatOfScalarTypeProbesAs( + "maxOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredFloatOfScalarTypeProbesAs( + "sumOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredFloatOfScalarTypeProbesAs( + "avgOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredFloatOfScalarTypeProbesAs( + "standardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredFloatOfScalarTypeProbesAs( + "sampleVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalFloatOfScalarTypeProbesAs( + "minOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalFloatOfScalarTypeProbesAs( + "maxOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalFloatOfScalarTypeProbesAs( + "sumOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalFloatOfScalarTypeProbesAs( + "avgOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalFloatOfScalarTypeProbesAs( + "standardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalFloatOfScalarTypeProbesAs( + "sampleVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDoubleOfScalarTypeProbesAs( + "minOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDoubleOfScalarTypeProbesAs( + "maxOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDoubleOfScalarTypeProbesAs( + "sumOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDoubleOfScalarTypeProbesAs( + "avgOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDoubleOfScalarTypeProbesAs( + "standardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDoubleOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDoubleOfScalarTypeProbesAs( + "minOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDoubleOfScalarTypeProbesAs( + "maxOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDoubleOfScalarTypeProbesAs( + "sumOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDoubleOfScalarTypeProbesAs( + "avgOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDoubleOfScalarTypeProbesAs( + "standardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDoubleOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof TypePlatform + ? entity + : TypePlatform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTypePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return TypePlatform.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/runtime-module.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..8360c7c150ff602d04277cd8a41c04ac09d664ec --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/runtime-module.ts @@ -0,0 +1,128 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "PascalCase" as const, + entities: Object.freeze({ + "TypePlatform": Object.freeze({ + entityType: "TypePlatform", + profile: "PascalCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "Id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "Name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "Version", aliases: Object.freeze([] as string[]) }) + }), + }), + "ScalarTypeProbe": Object.freeze({ + entityType: "ScalarTypeProbe", + profile: "PascalCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "Id", aliases: Object.freeze([] as string[]) }), + "type_platform": Object.freeze({ canonicalName: "type_platform", wireName: "TypePlatform", aliases: Object.freeze([] as string[]) }), + "required_string": Object.freeze({ canonicalName: "required_string", wireName: "RequiredString", aliases: Object.freeze([] as string[]) }), + "optional_string": Object.freeze({ canonicalName: "optional_string", wireName: "OptionalString", aliases: Object.freeze([] as string[]) }), + "large_text": Object.freeze({ canonicalName: "large_text", wireName: "LargeText", aliases: Object.freeze([] as string[]) }), + "required_boolean": Object.freeze({ canonicalName: "required_boolean", wireName: "RequiredBoolean", aliases: Object.freeze([] as string[]) }), + "optional_boolean": Object.freeze({ canonicalName: "optional_boolean", wireName: "OptionalBoolean", aliases: Object.freeze([] as string[]) }), + "required_integer": Object.freeze({ canonicalName: "required_integer", wireName: "RequiredInteger", aliases: Object.freeze([] as string[]) }), + "optional_integer": Object.freeze({ canonicalName: "optional_integer", wireName: "OptionalInteger", aliases: Object.freeze([] as string[]) }), + "required_long": Object.freeze({ canonicalName: "required_long", wireName: "RequiredLong", aliases: Object.freeze([] as string[]) }), + "optional_long": Object.freeze({ canonicalName: "optional_long", wireName: "OptionalLong", aliases: Object.freeze([] as string[]) }), + "required_decimal": Object.freeze({ canonicalName: "required_decimal", wireName: "RequiredDecimal", aliases: Object.freeze([] as string[]) }), + "optional_decimal": Object.freeze({ canonicalName: "optional_decimal", wireName: "OptionalDecimal", aliases: Object.freeze([] as string[]) }), + "required_float": Object.freeze({ canonicalName: "required_float", wireName: "RequiredFloat", aliases: Object.freeze([] as string[]) }), + "optional_float": Object.freeze({ canonicalName: "optional_float", wireName: "OptionalFloat", aliases: Object.freeze([] as string[]) }), + "required_double": Object.freeze({ canonicalName: "required_double", wireName: "RequiredDouble", aliases: Object.freeze([] as string[]) }), + "optional_double": Object.freeze({ canonicalName: "optional_double", wireName: "OptionalDouble", aliases: Object.freeze([] as string[]) }), + "required_date": Object.freeze({ canonicalName: "required_date", wireName: "RequiredDate", aliases: Object.freeze([] as string[]) }), + "optional_date": Object.freeze({ canonicalName: "optional_date", wireName: "OptionalDate", aliases: Object.freeze([] as string[]) }), + "required_time": Object.freeze({ canonicalName: "required_time", wireName: "RequiredTime", aliases: Object.freeze([] as string[]) }), + "optional_time": Object.freeze({ canonicalName: "optional_time", wireName: "OptionalTime", aliases: Object.freeze([] as string[]) }), + "required_datetime": Object.freeze({ canonicalName: "required_datetime", wireName: "RequiredDatetime", aliases: Object.freeze([] as string[]) }), + "optional_datetime": Object.freeze({ canonicalName: "optional_datetime", wireName: "OptionalDatetime", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "CreateTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "UpdateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "Version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "TypePlatform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "ScalarTypeProbe": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["type_platform"] === undefined) || mutation.payload["type_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("type_platform") }); + + if ((mutation.action === "Create" && mutation.payload["required_string"] === undefined) || mutation.payload["required_string"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_string") }); + if (mutation.payload["required_string"] != null && [...String(mutation.payload["required_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("required_string"), inputValue: mutation.payload["required_string"], systemValue: 100 }); + + if (mutation.payload["optional_string"] != null && [...String(mutation.payload["optional_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("optional_string"), inputValue: mutation.payload["optional_string"], systemValue: 100 }); + + + if ((mutation.action === "Create" && mutation.payload["required_boolean"] === undefined) || mutation.payload["required_boolean"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_boolean") }); + + + if ((mutation.action === "Create" && mutation.payload["required_integer"] === undefined) || mutation.payload["required_integer"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_integer") }); + + + if ((mutation.action === "Create" && mutation.payload["required_long"] === undefined) || mutation.payload["required_long"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_long") }); + + + if ((mutation.action === "Create" && mutation.payload["required_decimal"] === undefined) || mutation.payload["required_decimal"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_decimal") }); + + + if ((mutation.action === "Create" && mutation.payload["required_float"] === undefined) || mutation.payload["required_float"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_float") }); + + + if ((mutation.action === "Create" && mutation.payload["required_double"] === undefined) || mutation.payload["required_double"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_double") }); + + + if ((mutation.action === "Create" && mutation.payload["required_date"] === undefined) || mutation.payload["required_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_date") }); + + + if ((mutation.action === "Create" && mutation.payload["required_time"] === undefined) || mutation.payload["required_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_time") }); + + + if ((mutation.action === "Create" && mutation.payload["required_datetime"] === undefined) || mutation.payload["required_datetime"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_datetime") }); + + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "TypePlatform", id: "1", values: { "name": "Scalar Type Conformance" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-node-sql.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f5d108d228a1dbec1140e735022c1d72d704eb6 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-node-sql.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"TypePlatform": { + table: "type_platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"scalarTypeProbeList": { targetEntity: "ScalarTypeProbe", localKey: "id", foreignKey: "typePlatform", many: true }} +}, +"ScalarTypeProbe": { + table: "scalar_type_probe_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "typePlatform": { columnName: "type_platform", modelName: "type_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "requiredString": { columnName: "required_string", modelName: "required_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "optionalString": { columnName: "optional_string", modelName: "optional_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "largeText": { columnName: "large_text", modelName: "large_text", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "requiredBoolean": { columnName: "required_boolean", modelName: "required_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "optionalBoolean": { columnName: "optional_boolean", modelName: "optional_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: true }, "requiredInteger": { columnName: "required_integer", modelName: "required_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "optionalInteger": { columnName: "optional_integer", modelName: "optional_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: true, integer32: true }, "requiredLong": { columnName: "required_long", modelName: "required_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: false }, "optionalLong": { columnName: "optional_long", modelName: "optional_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: true }, "requiredDecimal": { columnName: "required_decimal", modelName: "required_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "optionalDecimal": { columnName: "optional_decimal", modelName: "optional_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: true }, "requiredFloat": { columnName: "required_float", modelName: "required_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalFloat": { columnName: "optional_float", modelName: "optional_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDouble": { columnName: "required_double", modelName: "required_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalDouble": { columnName: "optional_double", modelName: "optional_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDate": { columnName: "required_date", modelName: "required_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "optionalDate": { columnName: "optional_date", modelName: "optional_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: true }, "requiredTime": { columnName: "required_time", modelName: "required_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: false }, "optionalTime": { columnName: "optional_time", modelName: "optional_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: true }, "requiredDatetime": { columnName: "required_datetime", modelName: "required_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "optionalDatetime": { columnName: "optional_datetime", modelName: "optional_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: true }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"typePlatform": { targetEntity: "TypePlatform", localKey: "typePlatform", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-ts.ts b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..9983b00b27c90dc429fca76441f2bf077f825921 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/src/teaql-ts.ts @@ -0,0 +1,518 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/teaql-i18n.json b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..9bccc83b0cb5f837bc4c9ee6a49415974e1a4d50 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/teaql-i18n.json @@ -0,0 +1,127 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.scalarTypeProbe.largeText": "Large Text", + "property.scalarTypeProbe.requiredString": "Required String", + "property.scalarTypeProbe.id": "Id", + "property.scalarTypeProbe.optionalDecimal": "Optional Decimal", + "property.scalarTypeProbe.requiredDate": "Required Date", + "property.scalarTypeProbe.optionalString": "Optional String", + "property.scalarTypeProbe.requiredLong": "Required Long", + "property.typePlatform.version": "Version", + "entity.scalarTypeProbe": "Scalar Type Probe", + "property.scalarTypeProbe.optionalTime": "Optional Time", + "property.scalarTypeProbe.typePlatform": "Type Platform", + "property.scalarTypeProbe.optionalLong": "Optional Long", + "property.scalarTypeProbe.requiredDatetime": "Required Datetime", + "property.scalarTypeProbe.requiredTime": "Required Time", + "property.scalarTypeProbe.optionalBoolean": "Optional Boolean", + "property.scalarTypeProbe.optionalInteger": "Optional Integer", + "property.scalarTypeProbe.requiredDouble": "Required Double", + "entity.typePlatform": "Type Platform", + "property.scalarTypeProbe.requiredInteger": "Required Integer", + "property.scalarTypeProbe.optionalDouble": "Optional Double", + "property.scalarTypeProbe.optionalDatetime": "Optional Datetime", + "property.scalarTypeProbe.createTime": "Create Time", + "property.scalarTypeProbe.requiredFloat": "Required Float", + "property.typePlatform.id": "Id", + "property.scalarTypeProbe.requiredDecimal": "Required Decimal", + "property.scalarTypeProbe.optionalFloat": "Optional Float", + "property.scalarTypeProbe.version": "Version", + "property.scalarTypeProbe.requiredBoolean": "Required Boolean", + "property.scalarTypeProbe.updateTime": "Update Time", + "property.typePlatform.name": "Name", + "property.scalarTypeProbe.optionalDate": "Optional Date" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/PascalCase/tsconfig.json b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/PascalCase/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/base-model.xml b/source/teaql-ts/examples/expression-profiles/generated/base-model.xml new file mode 100644 index 0000000000000000000000000000000000000000..6fd6f2bc503caa1608c4dec93acc85a8d3a345ea --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/base-model.xml @@ -0,0 +1,39 @@ + + + + + + diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/model.xml b/source/teaql-ts/examples/expression-profiles/generated/camelCase/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..6fd6f2bc503caa1608c4dec93acc85a8d3a345ea --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/model.xml @@ -0,0 +1,39 @@ + + + + + + diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/package.json b/source/teaql-ts/examples/expression-profiles/generated/camelCase/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc0449fe65f58906b3f4b83d82fd3074e3aaf88 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/package.json @@ -0,0 +1,18 @@ +{ + "name": "scalar-type-conformance-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.3.1", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated-bootstrap.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..c32758df9a96057fe59280ac184fac252759e0b2 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { TypePlatform } from './generated/models/TypePlatform'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.typePlatforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = TypePlatform.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Scalar Type Conformance"); + await domainRoot.auditAs('create generated Domain Root TypePlatform').save(context); + } + context.withActiveRoot({ entity: 'TypePlatform', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated-search-models.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..40a79e6c3579b1785644cba497ee964459a779bc --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated-search-models.ts @@ -0,0 +1,130 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "TypePlatform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "scalarTypeProbeList": "ScalarTypeProbe", + }), + }), + "ScalarTypeProbe": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "type_platform": "integer" as const, + "typePlatform": "integer" as const, + "required_string": "string" as const, + "requiredString": "string" as const, + "optional_string": "string" as const, + "optionalString": "string" as const, + "large_text": "string" as const, + "largeText": "string" as const, + "required_boolean": "boolean" as const, + "requiredBoolean": "boolean" as const, + "optional_boolean": "boolean" as const, + "optionalBoolean": "boolean" as const, + "required_integer": "integer" as const, + "requiredInteger": "integer" as const, + "optional_integer": "integer" as const, + "optionalInteger": "integer" as const, + "required_long": "integer" as const, + "requiredLong": "integer" as const, + "optional_long": "integer" as const, + "optionalLong": "integer" as const, + "required_decimal": "decimal" as const, + "requiredDecimal": "decimal" as const, + "optional_decimal": "decimal" as const, + "optionalDecimal": "decimal" as const, + "required_float": "number" as const, + "requiredFloat": "number" as const, + "optional_float": "number" as const, + "optionalFloat": "number" as const, + "required_double": "number" as const, + "requiredDouble": "number" as const, + "optional_double": "number" as const, + "optionalDouble": "number" as const, + "required_date": "date" as const, + "requiredDate": "date" as const, + "optional_date": "date" as const, + "optionalDate": "date" as const, + "required_time": "unsupported" as const, + "requiredTime": "unsupported" as const, + "optional_time": "unsupported" as const, + "optionalTime": "unsupported" as const, + "required_datetime": "timestamp" as const, + "requiredDatetime": "timestamp" as const, + "optional_datetime": "timestamp" as const, + "optionalDatetime": "timestamp" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "type_platform": "typePlatform", + "typePlatform": "typePlatform", + "required_string": "requiredString", + "requiredString": "requiredString", + "optional_string": "optionalString", + "optionalString": "optionalString", + "large_text": "largeText", + "largeText": "largeText", + "required_boolean": "requiredBoolean", + "requiredBoolean": "requiredBoolean", + "optional_boolean": "optionalBoolean", + "optionalBoolean": "optionalBoolean", + "required_integer": "requiredInteger", + "requiredInteger": "requiredInteger", + "optional_integer": "optionalInteger", + "optionalInteger": "optionalInteger", + "required_long": "requiredLong", + "requiredLong": "requiredLong", + "optional_long": "optionalLong", + "optionalLong": "optionalLong", + "required_decimal": "requiredDecimal", + "requiredDecimal": "requiredDecimal", + "optional_decimal": "optionalDecimal", + "optionalDecimal": "optionalDecimal", + "required_float": "requiredFloat", + "requiredFloat": "requiredFloat", + "optional_float": "optionalFloat", + "optionalFloat": "optionalFloat", + "required_double": "requiredDouble", + "requiredDouble": "requiredDouble", + "optional_double": "optionalDouble", + "optionalDouble": "optionalDouble", + "required_date": "requiredDate", + "requiredDate": "requiredDate", + "optional_date": "optionalDate", + "optionalDate": "optionalDate", + "required_time": "requiredTime", + "requiredTime": "requiredTime", + "optional_time": "optionalTime", + "optionalTime": "optionalTime", + "required_datetime": "requiredDatetime", + "requiredDatetime": "requiredDatetime", + "optional_datetime": "optionalDatetime", + "optionalDatetime": "optionalDatetime", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "type_platform": "TypePlatform", + "typePlatform": "TypePlatform", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/E.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..dc53535c21ddb69a38876cf65ab146fc893db4d0 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/E.ts @@ -0,0 +1,564 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { TypePlatform } from './models/TypePlatform'; +import { ScalarTypeProbe } from './models/ScalarTypeProbe'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class TypePlatformExpression { + constructor( + private readonly value: TypePlatform | null | undefined, + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.typePlatform()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): TypePlatform | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + scalarTypeProbeList(): ScalarTypeProbeListExpression { + const path = this.path.member('scalar_type_probe_list', 'scalarTypeProbeList'); + if (this.notLoaded) { + return new ScalarTypeProbeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return ScalarTypeProbeListExpression.missing(this.root, path); + if (!this.value.isLoaded('scalarTypeProbeList')) { + return new ScalarTypeProbeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'scalar_type_probe_list')); + } + return new ScalarTypeProbeListExpression( + this.value.scalarTypeProbeList(), this.root, path, + ); + } +} + +export class ScalarTypeProbeExpression { + constructor( + private readonly value: ScalarTypeProbe | null | undefined, + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.scalarTypeProbe()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): ScalarTypeProbe | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + requiredString(): ValueExpression { + const path = this.path.member('required_string', 'requiredString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_string'), + ); + } + return new ValueExpression(this.value.requiredString); + } + + optionalString(): ValueExpression { + const path = this.path.member('optional_string', 'optionalString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_string'), + ); + } + return new ValueExpression(this.value.optionalString); + } + + largeText(): ValueExpression { + const path = this.path.member('large_text', 'largeText'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('largeText')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'large_text'), + ); + } + return new ValueExpression(this.value.largeText); + } + + requiredBoolean(): ValueExpression { + const path = this.path.member('required_boolean', 'requiredBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_boolean'), + ); + } + return new ValueExpression(this.value.requiredBoolean); + } + + optionalBoolean(): ValueExpression { + const path = this.path.member('optional_boolean', 'optionalBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_boolean'), + ); + } + return new ValueExpression(this.value.optionalBoolean); + } + + requiredInteger(): ValueExpression { + const path = this.path.member('required_integer', 'requiredInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_integer'), + ); + } + const error = integer32Error(this.value.requiredInteger, 'ScalarTypeProbe', 'required_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.requiredInteger); + } + + optionalInteger(): ValueExpression { + const path = this.path.member('optional_integer', 'optionalInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_integer'), + ); + } + const error = integer32Error(this.value.optionalInteger, 'ScalarTypeProbe', 'optional_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.optionalInteger); + } + + requiredLong(): ValueExpression { + const path = this.path.member('required_long', 'requiredLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_long'), + ); + } + return new ValueExpression(this.value.requiredLong); + } + + optionalLong(): ValueExpression { + const path = this.path.member('optional_long', 'optionalLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_long'), + ); + } + return new ValueExpression(this.value.optionalLong); + } + + requiredDecimal(): ValueExpression { + const path = this.path.member('required_decimal', 'requiredDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_decimal'), + ); + } + return new ValueExpression(this.value.requiredDecimal); + } + + optionalDecimal(): ValueExpression { + const path = this.path.member('optional_decimal', 'optionalDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_decimal'), + ); + } + return new ValueExpression(this.value.optionalDecimal); + } + + requiredFloat(): ValueExpression { + const path = this.path.member('required_float', 'requiredFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_float'), + ); + } + return new ValueExpression(this.value.requiredFloat); + } + + optionalFloat(): ValueExpression { + const path = this.path.member('optional_float', 'optionalFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_float'), + ); + } + return new ValueExpression(this.value.optionalFloat); + } + + requiredDouble(): ValueExpression { + const path = this.path.member('required_double', 'requiredDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_double'), + ); + } + return new ValueExpression(this.value.requiredDouble); + } + + optionalDouble(): ValueExpression { + const path = this.path.member('optional_double', 'optionalDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_double'), + ); + } + return new ValueExpression(this.value.optionalDouble); + } + + requiredDate(): ValueExpression { + const path = this.path.member('required_date', 'requiredDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_date'), + ); + } + return new ValueExpression(this.value.requiredDate); + } + + optionalDate(): ValueExpression { + const path = this.path.member('optional_date', 'optionalDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_date'), + ); + } + return new ValueExpression(this.value.optionalDate); + } + + requiredTime(): ValueExpression { + const path = this.path.member('required_time', 'requiredTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_time'), + ); + } + return new ValueExpression(this.value.requiredTime); + } + + optionalTime(): ValueExpression { + const path = this.path.member('optional_time', 'optionalTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_time'), + ); + } + return new ValueExpression(this.value.optionalTime); + } + + requiredDatetime(): ValueExpression { + const path = this.path.member('required_datetime', 'requiredDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_datetime'), + ); + } + return new ValueExpression(this.value.requiredDatetime); + } + + optionalDatetime(): ValueExpression { + const path = this.path.member('optional_datetime', 'optionalDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_datetime'), + ); + } + return new ValueExpression(this.value.optionalDatetime); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + typePlatformId(): ValueExpression { + const path = this.path.member('type_platform', 'typePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('typePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'type_platform'), + ); + } + const reference = this.value.typePlatform; + return new ValueExpression( + reference instanceof TypePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + typePlatform(): TypePlatformExpression { + const path = this.path.member('type_platform', 'typePlatform'); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TypePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('typePlatform')) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const relation = this.value.typePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof TypePlatform)) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const target = relation instanceof TypePlatform ? relation : undefined; + return new TypePlatformExpression(target, this.root, path); + } + +} + +export class TypePlatformListExpression { + constructor( + private readonly items: readonly TypePlatform[], + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): TypePlatformListExpression { + return new TypePlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TypePlatformExpression { + return this.item(0, true); + } + + get(index: number): TypePlatformExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TypePlatformExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TypePlatformExpression(undefined, this.root, itemPath) + : new TypePlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class ScalarTypeProbeListExpression { + constructor( + private readonly items: readonly ScalarTypeProbe[], + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): ScalarTypeProbeListExpression { + return new ScalarTypeProbeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): ScalarTypeProbeExpression { + return this.item(0, true); + } + + get(index: number): ScalarTypeProbeExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): ScalarTypeProbeExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new ScalarTypeProbeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new ScalarTypeProbeExpression(undefined, this.root, itemPath) + : new ScalarTypeProbeExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static typePlatform( + value: TypePlatform | null | undefined, + ): TypePlatformExpression { + return new TypePlatformExpression( + value, 'TypePlatform', ExpressionPath.root('E.typePlatform()', 'camelCase'), + ); + } + + static scalarTypeProbe( + value: ScalarTypeProbe | null | undefined, + ): ScalarTypeProbeExpression { + return new ScalarTypeProbeExpression( + value, 'ScalarTypeProbe', ExpressionPath.root('E.scalarTypeProbe()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/Q.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..5124d7963158b57d5460ab83052c5800791f46aa --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { TypePlatformRequest } from './requests/TypePlatformRequest'; +import { ScalarTypeProbeRequest } from './requests/ScalarTypeProbeRequest'; + +export class Q { + static typePlatforms(): TypePlatformRequest { + return new TypePlatformRequest(false); + } + + static typePlatformsWithMinimalFields(): TypePlatformRequest { + return new TypePlatformRequest(true); + } + static scalarTypeProbes(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(false); + } + + static scalarTypeProbesWithMinimalFields(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/models/ScalarTypeProbe.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/models/ScalarTypeProbe.ts new file mode 100644 index 0000000000000000000000000000000000000000..90f93cf19ac480a4c610bf02ac8696c043c90b2d --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/models/ScalarTypeProbe.ts @@ -0,0 +1,576 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { TypePlatform } from './TypePlatform'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class ScalarTypeProbe { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("ScalarTypeProbe", + ["id", "type_platform", "required_string", "optional_string", "large_text", "required_boolean", "optional_boolean", "required_integer", "optional_integer", "required_long", "optional_long", "required_decimal", "optional_decimal", "required_float", "optional_float", "required_double", "optional_double", "required_date", "optional_date", "required_time", "optional_time", "required_datetime", "optional_datetime", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + typePlatform?: TypePlatform | string; + requiredString?: string; + optionalString?: string | null; + largeText?: string | null; + requiredBoolean?: boolean; + optionalBoolean?: boolean | null; + requiredInteger?: number; + optionalInteger?: number | null; + requiredLong?: Long; + optionalLong?: Long | null; + requiredDecimal?: Decimal; + optionalDecimal?: Decimal | null; + requiredFloat?: number; + optionalFloat?: number | null; + requiredDouble?: number; + optionalDouble?: number | null; + requiredDate?: string; + optionalDate?: string | null; + requiredTime?: LocalTime; + optionalTime?: LocalTime | null; + requiredDatetime?: string; + optionalDatetime?: string | null; + createTime?: string; + updateTime?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(init?.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --ScalarTypeProbe.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).typePlatform && typeof (init as any).typePlatform === "object") { + this.typePlatform = (init as any).typePlatform instanceof TypePlatform + ? (init as any).typePlatform + : TypePlatform.fromRecord((init as any).typePlatform); + this.markLoaded("typePlatform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "ScalarTypeProbe", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): ScalarTypeProbe { + const entity = EntityCreation.hydrated(new ScalarTypeProbe(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(this.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): ScalarTypeProbe { + return ScalarTypeProbe.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): ScalarTypeProbe { + return EntityCreation.bootstrap(context, "ScalarTypeProbe", id, + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "ScalarTypeProbe", + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "type_platform": "TypePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + ScalarTypeProbe.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "ScalarTypeProbe", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "ScalarTypeProbe", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "ScalarTypeProbe", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "ScalarTypeProbe", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "type_platform": this.typePlatform, + "required_string": this.requiredString, + "optional_string": this.optionalString, + "large_text": this.largeText, + "required_boolean": this.requiredBoolean, + "optional_boolean": this.optionalBoolean, + "required_integer": this.requiredInteger, + "optional_integer": this.optionalInteger, + "required_long": this.requiredLong, + "optional_long": this.optionalLong, + "required_decimal": this.requiredDecimal, + "optional_decimal": this.optionalDecimal, + "required_float": this.requiredFloat, + "optional_float": this.optionalFloat, + "required_double": this.requiredDouble, + "optional_double": this.optionalDouble, + "required_date": this.requiredDate, + "optional_date": this.optionalDate, + "required_time": this.requiredTime, + "optional_time": this.optionalTime, + "required_datetime": this.requiredDatetime, + "optional_datetime": this.optionalDatetime, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateRequiredString(value: string): this { + this.requiredString = value; + this.markLoaded("requiredString"); + (this as any)._root.set(this.teaqlEntityKey(), "required_string", value); + return this; + } + + updateOptionalString(value: string | null): this { + this.optionalString = value; + this.markLoaded("optionalString"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_string", value); + return this; + } + + updateLargeText(value: string | null): this { + this.largeText = value; + this.markLoaded("largeText"); + (this as any)._root.set(this.teaqlEntityKey(), "large_text", value); + return this; + } + + updateRequiredBoolean(value: boolean): this { + this.requiredBoolean = value; + this.markLoaded("requiredBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "required_boolean", value); + return this; + } + + updateOptionalBoolean(value: boolean | null): this { + this.optionalBoolean = value; + this.markLoaded("optionalBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_boolean", value); + return this; + } + + updateRequiredInteger(value: number): this { + this.requiredInteger = value; + this.markLoaded("requiredInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "required_integer", value); + return this; + } + + updateOptionalInteger(value: number | null): this { + this.optionalInteger = value; + this.markLoaded("optionalInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_integer", value); + return this; + } + + updateRequiredLong(value: Long): this { + if (value != null) value = long(value); + this.requiredLong = value; + this.markLoaded("requiredLong"); + (this as any)._root.set(this.teaqlEntityKey(), "required_long", value); + return this; + } + + updateOptionalLong(value: Long | null): this { + if (value != null) value = long(value); + this.optionalLong = value; + this.markLoaded("optionalLong"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_long", value); + return this; + } + + updateRequiredDecimal(value: Decimal): this { + if (value != null) value = decimal(value); + this.requiredDecimal = value; + this.markLoaded("requiredDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "required_decimal", value); + return this; + } + + updateOptionalDecimal(value: Decimal | null): this { + if (value != null) value = decimal(value); + this.optionalDecimal = value; + this.markLoaded("optionalDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_decimal", value); + return this; + } + + updateRequiredFloat(value: number): this { + this.requiredFloat = value; + this.markLoaded("requiredFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "required_float", value); + return this; + } + + updateOptionalFloat(value: number | null): this { + this.optionalFloat = value; + this.markLoaded("optionalFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_float", value); + return this; + } + + updateRequiredDouble(value: number): this { + this.requiredDouble = value; + this.markLoaded("requiredDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "required_double", value); + return this; + } + + updateOptionalDouble(value: number | null): this { + this.optionalDouble = value; + this.markLoaded("optionalDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_double", value); + return this; + } + + updateRequiredDate(value: string): this { + this.requiredDate = value; + this.markLoaded("requiredDate"); + (this as any)._root.set(this.teaqlEntityKey(), "required_date", value); + return this; + } + + updateOptionalDate(value: string | null): this { + this.optionalDate = value; + this.markLoaded("optionalDate"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_date", value); + return this; + } + + updateRequiredTime(value: LocalTime): this { + if (value != null) value = localTime(value); + this.requiredTime = value; + this.markLoaded("requiredTime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_time", value); + return this; + } + + updateOptionalTime(value: LocalTime | null): this { + if (value != null) value = localTime(value); + this.optionalTime = value; + this.markLoaded("optionalTime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_time", value); + return this; + } + + updateRequiredDatetime(value: string): this { + this.requiredDatetime = value; + this.markLoaded("requiredDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_datetime", value); + return this; + } + + updateOptionalDatetime(value: string | null): this { + this.optionalDatetime = value; + this.markLoaded("optionalDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_datetime", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateTypePlatform(value: any): this { + this.typePlatform = value?.id ?? value; + this.markLoaded("typePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "type_platform", this.typePlatform); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/models/TypePlatform.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/models/TypePlatform.ts new file mode 100644 index 0000000000000000000000000000000000000000..00fc9ee5d876db31834d06abe61c11f063127e61 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/models/TypePlatform.ts @@ -0,0 +1,403 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { ScalarTypeProbe } from './ScalarTypeProbe'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class TypePlatform { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("TypePlatform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --TypePlatform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_scalarTypeProbeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["scalarTypeProbeList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).scalarTypeProbeList)) { + const selected = (init as any).scalarTypeProbeList; + (this as any)._scalarTypeProbeList = new SmartList(selected.map( + (child: unknown) => child instanceof ScalarTypeProbe + ? child + : ScalarTypeProbe.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("scalarTypeProbeList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "TypePlatform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._scalarTypeProbeList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): TypePlatform { + const entity = EntityCreation.hydrated(new TypePlatform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("scalarTypeProbeList")) result["scalarTypeProbeList"] = (this as any)._scalarTypeProbeList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): TypePlatform { + return TypePlatform.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): TypePlatform { + return EntityCreation.bootstrap(context, "TypePlatform", id, + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "TypePlatform", + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._scalarTypeProbeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._scalarTypeProbeList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "scalar_type_probe_list": graph.sourceMembers((this as any)._scalarTypeProbeList) + })); + for (const child of (this as any)._scalarTypeProbeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + TypePlatform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "TypePlatform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "TypePlatform", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "TypePlatform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "TypePlatform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + scalarTypeProbeList(): SmartList { + return (this as any)._scalarTypeProbeList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/requests/ScalarTypeProbeRequest.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/requests/ScalarTypeProbeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aab674d36faae5691bcfb6d8a395878245cbaa4 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/requests/ScalarTypeProbeRequest.ts @@ -0,0 +1,3073 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { ScalarTypeProbe } from '../models/ScalarTypeProbe'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class ScalarTypeProbeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("ScalarTypeProbe"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "ScalarTypeProbe" { + return "ScalarTypeProbe"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableScalarTypeProbeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableScalarTypeProbeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "typePlatform", "requiredString", "optionalString", "largeText", "requiredBoolean", "optionalBoolean", "requiredInteger", "optionalInteger", "requiredLong", "optionalLong", "requiredDecimal", "optionalDecimal", "requiredFloat", "optionalFloat", "requiredDouble", "optionalDouble", "requiredDate", "optionalDate", "requiredTime", "optionalTime", "requiredDatetime", "optionalDatetime", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectRequiredString(): this { + this.query.select(["requiredString"]); + return this; + } + + selectOptionalString(): this { + this.query.select(["optionalString"]); + return this; + } + + selectLargeText(): this { + this.query.select(["largeText"]); + return this; + } + + selectRequiredBoolean(): this { + this.query.select(["requiredBoolean"]); + return this; + } + + selectOptionalBoolean(): this { + this.query.select(["optionalBoolean"]); + return this; + } + + selectRequiredInteger(): this { + this.query.select(["requiredInteger"]); + return this; + } + + selectOptionalInteger(): this { + this.query.select(["optionalInteger"]); + return this; + } + + selectRequiredLong(): this { + this.query.select(["requiredLong"]); + return this; + } + + selectOptionalLong(): this { + this.query.select(["optionalLong"]); + return this; + } + + selectRequiredDecimal(): this { + this.query.select(["requiredDecimal"]); + return this; + } + + selectOptionalDecimal(): this { + this.query.select(["optionalDecimal"]); + return this; + } + + selectRequiredFloat(): this { + this.query.select(["requiredFloat"]); + return this; + } + + selectOptionalFloat(): this { + this.query.select(["optionalFloat"]); + return this; + } + + selectRequiredDouble(): this { + this.query.select(["requiredDouble"]); + return this; + } + + selectOptionalDouble(): this { + this.query.select(["optionalDouble"]); + return this; + } + + selectRequiredDate(): this { + this.query.select(["requiredDate"]); + return this; + } + + selectOptionalDate(): this { + this.query.select(["optionalDate"]); + return this; + } + + selectRequiredTime(): this { + this.query.select(["requiredTime"]); + return this; + } + + selectOptionalTime(): this { + this.query.select(["optionalTime"]); + return this; + } + + selectRequiredDatetime(): this { + this.query.select(["requiredDatetime"]); + return this; + } + + selectOptionalDatetime(): this { + this.query.select(["optionalDatetime"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectTypePlatformWith(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["typePlatform"]); + this.query.relationQuery( + "typePlatform", request.toQuery(), "typePlatform", "id", false, + { kind: "relation-select", method: "selectTypePlatformWith", relation: "typePlatform" }); + return this; + } + + withTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByTypePlatform(val: any): this { + this.filters.push({ "typePlatform": { "$eq": val } }); + return this; + } + + filterByTypePlatformIn(...vals: any[]): this { + this.filters.push({ "typePlatform": { "$in": vals } }); + return this; + } + + withTypePlatformIsKnown(): this { + this.filters.push({ "typePlatform": { "$isNull": false } }); + return this; + } + + withTypePlatformIsUnknown(): this { + this.filters.push({ "typePlatform": { "$isNull": true } }); + return this; + } + + withRequiredStringContaining(val: string): this { + this.filters.push({ "requiredString": { "$contains": val } }); + return this; + } + + withRequiredStringIs(val: string): this { + this.filters.push({ "requiredString": { "$eq": val } }); + return this; + } + + withRequiredStringIsNot(val: string): this { + this.filters.push({ "requiredString": { "$ne": val } }); + return this; + } + + withRequiredStringIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$in": vals } }); + return this; + } + + withRequiredStringNotIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$notIn": vals } }); + return this; + } + + withRequiredStringGreaterThan(val: string): this { + this.filters.push({ "requiredString": { "$gt": val } }); + return this; + } + + withRequiredStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$gte": val } }); + return this; + } + + withRequiredStringLessThan(val: string): this { + this.filters.push({ "requiredString": { "$lt": val } }); + return this; + } + + withRequiredStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$lte": val } }); + return this; + } + + withRequiredStringBetween(lower: string, upper: string): this { + this.filters.push({ "requiredString": { "$between": [lower, upper] } }); + return this; + } + + withRequiredStringIsKnown(): this { + this.filters.push({ "requiredString": { "$isNull": false } }); + return this; + } + + withRequiredStringIsUnknown(): this { + this.filters.push({ "requiredString": { "$isNull": true } }); + return this; + } + withRequiredStringNotContaining(val: string): this { + this.filters.push({ "requiredString": { "$notContains": val } }); + return this; + } + + withRequiredStringStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$startsWith": val } }); + return this; + } + + withRequiredStringNotStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$notStartsWith": val } }); + return this; + } + + withRequiredStringEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$endsWith": val } }); + return this; + } + + withRequiredStringNotEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$notEndsWith": val } }); + return this; + } + + withRequiredStringSoundingLike(val: string): this { + this.filters.push({ "requiredString": { "$soundLike": val } }); + return this; + } + + withOptionalStringContaining(val: string): this { + this.filters.push({ "optionalString": { "$contains": val } }); + return this; + } + + withOptionalStringIs(val: string): this { + this.filters.push({ "optionalString": { "$eq": val } }); + return this; + } + + withOptionalStringIsNot(val: string): this { + this.filters.push({ "optionalString": { "$ne": val } }); + return this; + } + + withOptionalStringIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$in": vals } }); + return this; + } + + withOptionalStringNotIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$notIn": vals } }); + return this; + } + + withOptionalStringGreaterThan(val: string): this { + this.filters.push({ "optionalString": { "$gt": val } }); + return this; + } + + withOptionalStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$gte": val } }); + return this; + } + + withOptionalStringLessThan(val: string): this { + this.filters.push({ "optionalString": { "$lt": val } }); + return this; + } + + withOptionalStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$lte": val } }); + return this; + } + + withOptionalStringBetween(lower: string, upper: string): this { + this.filters.push({ "optionalString": { "$between": [lower, upper] } }); + return this; + } + + withOptionalStringIsKnown(): this { + this.filters.push({ "optionalString": { "$isNull": false } }); + return this; + } + + withOptionalStringIsUnknown(): this { + this.filters.push({ "optionalString": { "$isNull": true } }); + return this; + } + withOptionalStringNotContaining(val: string): this { + this.filters.push({ "optionalString": { "$notContains": val } }); + return this; + } + + withOptionalStringStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$startsWith": val } }); + return this; + } + + withOptionalStringNotStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$notStartsWith": val } }); + return this; + } + + withOptionalStringEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$endsWith": val } }); + return this; + } + + withOptionalStringNotEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$notEndsWith": val } }); + return this; + } + + withOptionalStringSoundingLike(val: string): this { + this.filters.push({ "optionalString": { "$soundLike": val } }); + return this; + } + + withLargeTextContaining(val: string): this { + this.filters.push({ "largeText": { "$contains": val } }); + return this; + } + + withLargeTextIs(val: string): this { + this.filters.push({ "largeText": { "$eq": val } }); + return this; + } + + withLargeTextIsNot(val: string): this { + this.filters.push({ "largeText": { "$ne": val } }); + return this; + } + + withLargeTextIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$in": vals } }); + return this; + } + + withLargeTextNotIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$notIn": vals } }); + return this; + } + + withLargeTextGreaterThan(val: string): this { + this.filters.push({ "largeText": { "$gt": val } }); + return this; + } + + withLargeTextGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$gte": val } }); + return this; + } + + withLargeTextLessThan(val: string): this { + this.filters.push({ "largeText": { "$lt": val } }); + return this; + } + + withLargeTextLessThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$lte": val } }); + return this; + } + + withLargeTextBetween(lower: string, upper: string): this { + this.filters.push({ "largeText": { "$between": [lower, upper] } }); + return this; + } + + withLargeTextIsKnown(): this { + this.filters.push({ "largeText": { "$isNull": false } }); + return this; + } + + withLargeTextIsUnknown(): this { + this.filters.push({ "largeText": { "$isNull": true } }); + return this; + } + withLargeTextNotContaining(val: string): this { + this.filters.push({ "largeText": { "$notContains": val } }); + return this; + } + + withLargeTextStartingWith(val: string): this { + this.filters.push({ "largeText": { "$startsWith": val } }); + return this; + } + + withLargeTextNotStartingWith(val: string): this { + this.filters.push({ "largeText": { "$notStartsWith": val } }); + return this; + } + + withLargeTextEndingWith(val: string): this { + this.filters.push({ "largeText": { "$endsWith": val } }); + return this; + } + + withLargeTextNotEndingWith(val: string): this { + this.filters.push({ "largeText": { "$notEndsWith": val } }); + return this; + } + + withLargeTextSoundingLike(val: string): this { + this.filters.push({ "largeText": { "$soundLike": val } }); + return this; + } + + whichAreRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": true } }); + return this; + } + + whichAreNotRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": false } }); + return this; + } + withRequiredBooleanIsNot(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$ne": val } }); + return this; + } + + withRequiredBooleanIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$in": vals } }); + return this; + } + + withRequiredBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$notIn": vals } }); + return this; + } + + withRequiredBooleanGreaterThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gt": val } }); + return this; + } + + withRequiredBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gte": val } }); + return this; + } + + withRequiredBooleanLessThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lt": val } }); + return this; + } + + withRequiredBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lte": val } }); + return this; + } + + withRequiredBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "requiredBoolean": { "$between": [lower, upper] } }); + return this; + } + + withRequiredBooleanIsKnown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": false } }); + return this; + } + + withRequiredBooleanIsUnknown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": true } }); + return this; + } + + whichAreOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": true } }); + return this; + } + + whichAreNotOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": false } }); + return this; + } + withOptionalBooleanIsNot(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$ne": val } }); + return this; + } + + withOptionalBooleanIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$in": vals } }); + return this; + } + + withOptionalBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$notIn": vals } }); + return this; + } + + withOptionalBooleanGreaterThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gt": val } }); + return this; + } + + withOptionalBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gte": val } }); + return this; + } + + withOptionalBooleanLessThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lt": val } }); + return this; + } + + withOptionalBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lte": val } }); + return this; + } + + withOptionalBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "optionalBoolean": { "$between": [lower, upper] } }); + return this; + } + + withOptionalBooleanIsKnown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": false } }); + return this; + } + + withOptionalBooleanIsUnknown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": true } }); + return this; + } + + withRequiredIntegerIs(val: number): this { + this.filters.push({ "requiredInteger": { "$eq": val } }); + return this; + } + + withRequiredIntegerIsNot(val: number): this { + this.filters.push({ "requiredInteger": { "$ne": val } }); + return this; + } + + withRequiredIntegerIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$in": vals } }); + return this; + } + + withRequiredIntegerNotIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$notIn": vals } }); + return this; + } + + withRequiredIntegerGreaterThan(val: number): this { + this.filters.push({ "requiredInteger": { "$gt": val } }); + return this; + } + + withRequiredIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$gte": val } }); + return this; + } + + withRequiredIntegerLessThan(val: number): this { + this.filters.push({ "requiredInteger": { "$lt": val } }); + return this; + } + + withRequiredIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$lte": val } }); + return this; + } + + withRequiredIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "requiredInteger": { "$between": [lower, upper] } }); + return this; + } + + withRequiredIntegerIsKnown(): this { + this.filters.push({ "requiredInteger": { "$isNull": false } }); + return this; + } + + withRequiredIntegerIsUnknown(): this { + this.filters.push({ "requiredInteger": { "$isNull": true } }); + return this; + } + + withOptionalIntegerIs(val: number): this { + this.filters.push({ "optionalInteger": { "$eq": val } }); + return this; + } + + withOptionalIntegerIsNot(val: number): this { + this.filters.push({ "optionalInteger": { "$ne": val } }); + return this; + } + + withOptionalIntegerIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$in": vals } }); + return this; + } + + withOptionalIntegerNotIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$notIn": vals } }); + return this; + } + + withOptionalIntegerGreaterThan(val: number): this { + this.filters.push({ "optionalInteger": { "$gt": val } }); + return this; + } + + withOptionalIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$gte": val } }); + return this; + } + + withOptionalIntegerLessThan(val: number): this { + this.filters.push({ "optionalInteger": { "$lt": val } }); + return this; + } + + withOptionalIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$lte": val } }); + return this; + } + + withOptionalIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "optionalInteger": { "$between": [lower, upper] } }); + return this; + } + + withOptionalIntegerIsKnown(): this { + this.filters.push({ "optionalInteger": { "$isNull": false } }); + return this; + } + + withOptionalIntegerIsUnknown(): this { + this.filters.push({ "optionalInteger": { "$isNull": true } }); + return this; + } + + withRequiredLongIs(val: Long): this { + this.filters.push({ "requiredLong": { "$eq": val } }); + return this; + } + + withRequiredLongIsNot(val: Long): this { + this.filters.push({ "requiredLong": { "$ne": val } }); + return this; + } + + withRequiredLongIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$in": vals } }); + return this; + } + + withRequiredLongNotIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$notIn": vals } }); + return this; + } + + withRequiredLongGreaterThan(val: Long): this { + this.filters.push({ "requiredLong": { "$gt": val } }); + return this; + } + + withRequiredLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$gte": val } }); + return this; + } + + withRequiredLongLessThan(val: Long): this { + this.filters.push({ "requiredLong": { "$lt": val } }); + return this; + } + + withRequiredLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$lte": val } }); + return this; + } + + withRequiredLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "requiredLong": { "$between": [lower, upper] } }); + return this; + } + + withRequiredLongIsKnown(): this { + this.filters.push({ "requiredLong": { "$isNull": false } }); + return this; + } + + withRequiredLongIsUnknown(): this { + this.filters.push({ "requiredLong": { "$isNull": true } }); + return this; + } + + withOptionalLongIs(val: Long): this { + this.filters.push({ "optionalLong": { "$eq": val } }); + return this; + } + + withOptionalLongIsNot(val: Long): this { + this.filters.push({ "optionalLong": { "$ne": val } }); + return this; + } + + withOptionalLongIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$in": vals } }); + return this; + } + + withOptionalLongNotIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$notIn": vals } }); + return this; + } + + withOptionalLongGreaterThan(val: Long): this { + this.filters.push({ "optionalLong": { "$gt": val } }); + return this; + } + + withOptionalLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$gte": val } }); + return this; + } + + withOptionalLongLessThan(val: Long): this { + this.filters.push({ "optionalLong": { "$lt": val } }); + return this; + } + + withOptionalLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$lte": val } }); + return this; + } + + withOptionalLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "optionalLong": { "$between": [lower, upper] } }); + return this; + } + + withOptionalLongIsKnown(): this { + this.filters.push({ "optionalLong": { "$isNull": false } }); + return this; + } + + withOptionalLongIsUnknown(): this { + this.filters.push({ "optionalLong": { "$isNull": true } }); + return this; + } + + withRequiredDecimalIs(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$eq": val } }); + return this; + } + + withRequiredDecimalIsNot(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$ne": val } }); + return this; + } + + withRequiredDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$in": vals } }); + return this; + } + + withRequiredDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$notIn": vals } }); + return this; + } + + withRequiredDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gt": val } }); + return this; + } + + withRequiredDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gte": val } }); + return this; + } + + withRequiredDecimalLessThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lt": val } }); + return this; + } + + withRequiredDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lte": val } }); + return this; + } + + withRequiredDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "requiredDecimal": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDecimalIsKnown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": false } }); + return this; + } + + withRequiredDecimalIsUnknown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": true } }); + return this; + } + + withOptionalDecimalIs(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$eq": val } }); + return this; + } + + withOptionalDecimalIsNot(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$ne": val } }); + return this; + } + + withOptionalDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$in": vals } }); + return this; + } + + withOptionalDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$notIn": vals } }); + return this; + } + + withOptionalDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gt": val } }); + return this; + } + + withOptionalDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gte": val } }); + return this; + } + + withOptionalDecimalLessThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lt": val } }); + return this; + } + + withOptionalDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lte": val } }); + return this; + } + + withOptionalDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "optionalDecimal": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDecimalIsKnown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": false } }); + return this; + } + + withOptionalDecimalIsUnknown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": true } }); + return this; + } + + withRequiredFloatIs(val: number): this { + this.filters.push({ "requiredFloat": { "$eq": val } }); + return this; + } + + withRequiredFloatIsNot(val: number): this { + this.filters.push({ "requiredFloat": { "$ne": val } }); + return this; + } + + withRequiredFloatIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$in": vals } }); + return this; + } + + withRequiredFloatNotIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$notIn": vals } }); + return this; + } + + withRequiredFloatGreaterThan(val: number): this { + this.filters.push({ "requiredFloat": { "$gt": val } }); + return this; + } + + withRequiredFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$gte": val } }); + return this; + } + + withRequiredFloatLessThan(val: number): this { + this.filters.push({ "requiredFloat": { "$lt": val } }); + return this; + } + + withRequiredFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$lte": val } }); + return this; + } + + withRequiredFloatBetween(lower: number, upper: number): this { + this.filters.push({ "requiredFloat": { "$between": [lower, upper] } }); + return this; + } + + withRequiredFloatIsKnown(): this { + this.filters.push({ "requiredFloat": { "$isNull": false } }); + return this; + } + + withRequiredFloatIsUnknown(): this { + this.filters.push({ "requiredFloat": { "$isNull": true } }); + return this; + } + + withOptionalFloatIs(val: number): this { + this.filters.push({ "optionalFloat": { "$eq": val } }); + return this; + } + + withOptionalFloatIsNot(val: number): this { + this.filters.push({ "optionalFloat": { "$ne": val } }); + return this; + } + + withOptionalFloatIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$in": vals } }); + return this; + } + + withOptionalFloatNotIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$notIn": vals } }); + return this; + } + + withOptionalFloatGreaterThan(val: number): this { + this.filters.push({ "optionalFloat": { "$gt": val } }); + return this; + } + + withOptionalFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$gte": val } }); + return this; + } + + withOptionalFloatLessThan(val: number): this { + this.filters.push({ "optionalFloat": { "$lt": val } }); + return this; + } + + withOptionalFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$lte": val } }); + return this; + } + + withOptionalFloatBetween(lower: number, upper: number): this { + this.filters.push({ "optionalFloat": { "$between": [lower, upper] } }); + return this; + } + + withOptionalFloatIsKnown(): this { + this.filters.push({ "optionalFloat": { "$isNull": false } }); + return this; + } + + withOptionalFloatIsUnknown(): this { + this.filters.push({ "optionalFloat": { "$isNull": true } }); + return this; + } + + withRequiredDoubleIs(val: number): this { + this.filters.push({ "requiredDouble": { "$eq": val } }); + return this; + } + + withRequiredDoubleIsNot(val: number): this { + this.filters.push({ "requiredDouble": { "$ne": val } }); + return this; + } + + withRequiredDoubleIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$in": vals } }); + return this; + } + + withRequiredDoubleNotIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$notIn": vals } }); + return this; + } + + withRequiredDoubleGreaterThan(val: number): this { + this.filters.push({ "requiredDouble": { "$gt": val } }); + return this; + } + + withRequiredDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$gte": val } }); + return this; + } + + withRequiredDoubleLessThan(val: number): this { + this.filters.push({ "requiredDouble": { "$lt": val } }); + return this; + } + + withRequiredDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$lte": val } }); + return this; + } + + withRequiredDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "requiredDouble": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDoubleIsKnown(): this { + this.filters.push({ "requiredDouble": { "$isNull": false } }); + return this; + } + + withRequiredDoubleIsUnknown(): this { + this.filters.push({ "requiredDouble": { "$isNull": true } }); + return this; + } + + withOptionalDoubleIs(val: number): this { + this.filters.push({ "optionalDouble": { "$eq": val } }); + return this; + } + + withOptionalDoubleIsNot(val: number): this { + this.filters.push({ "optionalDouble": { "$ne": val } }); + return this; + } + + withOptionalDoubleIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$in": vals } }); + return this; + } + + withOptionalDoubleNotIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$notIn": vals } }); + return this; + } + + withOptionalDoubleGreaterThan(val: number): this { + this.filters.push({ "optionalDouble": { "$gt": val } }); + return this; + } + + withOptionalDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$gte": val } }); + return this; + } + + withOptionalDoubleLessThan(val: number): this { + this.filters.push({ "optionalDouble": { "$lt": val } }); + return this; + } + + withOptionalDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$lte": val } }); + return this; + } + + withOptionalDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "optionalDouble": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDoubleIsKnown(): this { + this.filters.push({ "optionalDouble": { "$isNull": false } }); + return this; + } + + withOptionalDoubleIsUnknown(): this { + this.filters.push({ "optionalDouble": { "$isNull": true } }); + return this; + } + + withRequiredDateIs(val: string): this { + this.filters.push({ "requiredDate": { "$eq": val } }); + return this; + } + + withRequiredDateIsNot(val: string): this { + this.filters.push({ "requiredDate": { "$ne": val } }); + return this; + } + + withRequiredDateIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$in": vals } }); + return this; + } + + withRequiredDateNotIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$notIn": vals } }); + return this; + } + + withRequiredDateGreaterThan(val: string): this { + this.filters.push({ "requiredDate": { "$gt": val } }); + return this; + } + + withRequiredDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$gte": val } }); + return this; + } + + withRequiredDateLessThan(val: string): this { + this.filters.push({ "requiredDate": { "$lt": val } }); + return this; + } + + withRequiredDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$lte": val } }); + return this; + } + + withRequiredDateBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDate": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDateIsKnown(): this { + this.filters.push({ "requiredDate": { "$isNull": false } }); + return this; + } + + withRequiredDateIsUnknown(): this { + this.filters.push({ "requiredDate": { "$isNull": true } }); + return this; + } + + withOptionalDateIs(val: string): this { + this.filters.push({ "optionalDate": { "$eq": val } }); + return this; + } + + withOptionalDateIsNot(val: string): this { + this.filters.push({ "optionalDate": { "$ne": val } }); + return this; + } + + withOptionalDateIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$in": vals } }); + return this; + } + + withOptionalDateNotIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$notIn": vals } }); + return this; + } + + withOptionalDateGreaterThan(val: string): this { + this.filters.push({ "optionalDate": { "$gt": val } }); + return this; + } + + withOptionalDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$gte": val } }); + return this; + } + + withOptionalDateLessThan(val: string): this { + this.filters.push({ "optionalDate": { "$lt": val } }); + return this; + } + + withOptionalDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$lte": val } }); + return this; + } + + withOptionalDateBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDate": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDateIsKnown(): this { + this.filters.push({ "optionalDate": { "$isNull": false } }); + return this; + } + + withOptionalDateIsUnknown(): this { + this.filters.push({ "optionalDate": { "$isNull": true } }); + return this; + } + + withRequiredTimeIs(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$eq": val } }); + return this; + } + + withRequiredTimeIsNot(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$ne": val } }); + return this; + } + + withRequiredTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$in": vals } }); + return this; + } + + withRequiredTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$notIn": vals } }); + return this; + } + + withRequiredTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gt": val } }); + return this; + } + + withRequiredTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gte": val } }); + return this; + } + + withRequiredTimeLessThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lt": val } }); + return this; + } + + withRequiredTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lte": val } }); + return this; + } + + withRequiredTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "requiredTime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredTimeIsKnown(): this { + this.filters.push({ "requiredTime": { "$isNull": false } }); + return this; + } + + withRequiredTimeIsUnknown(): this { + this.filters.push({ "requiredTime": { "$isNull": true } }); + return this; + } + + withOptionalTimeIs(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$eq": val } }); + return this; + } + + withOptionalTimeIsNot(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$ne": val } }); + return this; + } + + withOptionalTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$in": vals } }); + return this; + } + + withOptionalTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$notIn": vals } }); + return this; + } + + withOptionalTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gt": val } }); + return this; + } + + withOptionalTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gte": val } }); + return this; + } + + withOptionalTimeLessThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lt": val } }); + return this; + } + + withOptionalTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lte": val } }); + return this; + } + + withOptionalTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "optionalTime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalTimeIsKnown(): this { + this.filters.push({ "optionalTime": { "$isNull": false } }); + return this; + } + + withOptionalTimeIsUnknown(): this { + this.filters.push({ "optionalTime": { "$isNull": true } }); + return this; + } + + withRequiredDatetimeIs(val: string): this { + this.filters.push({ "requiredDatetime": { "$eq": val } }); + return this; + } + + withRequiredDatetimeIsNot(val: string): this { + this.filters.push({ "requiredDatetime": { "$ne": val } }); + return this; + } + + withRequiredDatetimeIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$in": vals } }); + return this; + } + + withRequiredDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$notIn": vals } }); + return this; + } + + withRequiredDatetimeGreaterThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$gt": val } }); + return this; + } + + withRequiredDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$gte": val } }); + return this; + } + + withRequiredDatetimeLessThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$lt": val } }); + return this; + } + + withRequiredDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$lte": val } }); + return this; + } + + withRequiredDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDatetime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDatetimeIsKnown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": false } }); + return this; + } + + withRequiredDatetimeIsUnknown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": true } }); + return this; + } + + withOptionalDatetimeIs(val: string): this { + this.filters.push({ "optionalDatetime": { "$eq": val } }); + return this; + } + + withOptionalDatetimeIsNot(val: string): this { + this.filters.push({ "optionalDatetime": { "$ne": val } }); + return this; + } + + withOptionalDatetimeIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$in": vals } }); + return this; + } + + withOptionalDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$notIn": vals } }); + return this; + } + + withOptionalDatetimeGreaterThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$gt": val } }); + return this; + } + + withOptionalDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$gte": val } }); + return this; + } + + withOptionalDatetimeLessThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$lt": val } }); + return this; + } + + withOptionalDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$lte": val } }); + return this; + } + + withOptionalDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDatetime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDatetimeIsKnown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": false } }); + return this; + } + + withOptionalDatetimeIsUnknown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByRequiredStringAscending(): this { + this.query.orderBy("requiredString", "asc"); + return this; + } + + orderByRequiredStringDescending(): this { + this.query.orderBy("requiredString", "desc"); + return this; + } + + orderByOptionalStringAscending(): this { + this.query.orderBy("optionalString", "asc"); + return this; + } + + orderByOptionalStringDescending(): this { + this.query.orderBy("optionalString", "desc"); + return this; + } + + orderByLargeTextAscending(): this { + this.query.orderBy("largeText", "asc"); + return this; + } + + orderByLargeTextDescending(): this { + this.query.orderBy("largeText", "desc"); + return this; + } + + orderByRequiredBooleanAscending(): this { + this.query.orderBy("requiredBoolean", "asc"); + return this; + } + + orderByRequiredBooleanDescending(): this { + this.query.orderBy("requiredBoolean", "desc"); + return this; + } + + orderByOptionalBooleanAscending(): this { + this.query.orderBy("optionalBoolean", "asc"); + return this; + } + + orderByOptionalBooleanDescending(): this { + this.query.orderBy("optionalBoolean", "desc"); + return this; + } + + orderByRequiredIntegerAscending(): this { + this.query.orderBy("requiredInteger", "asc"); + return this; + } + + orderByRequiredIntegerDescending(): this { + this.query.orderBy("requiredInteger", "desc"); + return this; + } + + orderByOptionalIntegerAscending(): this { + this.query.orderBy("optionalInteger", "asc"); + return this; + } + + orderByOptionalIntegerDescending(): this { + this.query.orderBy("optionalInteger", "desc"); + return this; + } + + orderByRequiredLongAscending(): this { + this.query.orderBy("requiredLong", "asc"); + return this; + } + + orderByRequiredLongDescending(): this { + this.query.orderBy("requiredLong", "desc"); + return this; + } + + orderByOptionalLongAscending(): this { + this.query.orderBy("optionalLong", "asc"); + return this; + } + + orderByOptionalLongDescending(): this { + this.query.orderBy("optionalLong", "desc"); + return this; + } + + orderByRequiredDecimalAscending(): this { + this.query.orderBy("requiredDecimal", "asc"); + return this; + } + + orderByRequiredDecimalDescending(): this { + this.query.orderBy("requiredDecimal", "desc"); + return this; + } + + orderByOptionalDecimalAscending(): this { + this.query.orderBy("optionalDecimal", "asc"); + return this; + } + + orderByOptionalDecimalDescending(): this { + this.query.orderBy("optionalDecimal", "desc"); + return this; + } + + orderByRequiredFloatAscending(): this { + this.query.orderBy("requiredFloat", "asc"); + return this; + } + + orderByRequiredFloatDescending(): this { + this.query.orderBy("requiredFloat", "desc"); + return this; + } + + orderByOptionalFloatAscending(): this { + this.query.orderBy("optionalFloat", "asc"); + return this; + } + + orderByOptionalFloatDescending(): this { + this.query.orderBy("optionalFloat", "desc"); + return this; + } + + orderByRequiredDoubleAscending(): this { + this.query.orderBy("requiredDouble", "asc"); + return this; + } + + orderByRequiredDoubleDescending(): this { + this.query.orderBy("requiredDouble", "desc"); + return this; + } + + orderByOptionalDoubleAscending(): this { + this.query.orderBy("optionalDouble", "asc"); + return this; + } + + orderByOptionalDoubleDescending(): this { + this.query.orderBy("optionalDouble", "desc"); + return this; + } + + orderByRequiredDateAscending(): this { + this.query.orderBy("requiredDate", "asc"); + return this; + } + + orderByRequiredDateDescending(): this { + this.query.orderBy("requiredDate", "desc"); + return this; + } + + orderByOptionalDateAscending(): this { + this.query.orderBy("optionalDate", "asc"); + return this; + } + + orderByOptionalDateDescending(): this { + this.query.orderBy("optionalDate", "desc"); + return this; + } + + orderByRequiredTimeAscending(): this { + this.query.orderBy("requiredTime", "asc"); + return this; + } + + orderByRequiredTimeDescending(): this { + this.query.orderBy("requiredTime", "desc"); + return this; + } + + orderByOptionalTimeAscending(): this { + this.query.orderBy("optionalTime", "asc"); + return this; + } + + orderByOptionalTimeDescending(): this { + this.query.orderBy("optionalTime", "desc"); + return this; + } + + orderByRequiredDatetimeAscending(): this { + this.query.orderBy("requiredDatetime", "asc"); + return this; + } + + orderByRequiredDatetimeDescending(): this { + this.query.orderBy("requiredDatetime", "desc"); + return this; + } + + orderByOptionalDatetimeAscending(): this { + this.query.orderBy("optionalDatetime", "asc"); + return this; + } + + orderByOptionalDatetimeDescending(): this { + this.query.orderBy("optionalDatetime", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minRequiredInteger(): this { + return this.minRequiredIntegerAs("minOfRequiredInteger"); + } + + minRequiredIntegerAs(retName: string): this { + this.query.aggregate("min", "requiredInteger", retName); + return this; + } + maxRequiredInteger(): this { + return this.maxRequiredIntegerAs("maxOfRequiredInteger"); + } + + maxRequiredIntegerAs(retName: string): this { + this.query.aggregate("max", "requiredInteger", retName); + return this; + } + sumRequiredInteger(): this { + return this.sumRequiredIntegerAs("sumOfRequiredInteger"); + } + + sumRequiredIntegerAs(retName: string): this { + this.query.aggregate("sum", "requiredInteger", retName); + return this; + } + avgRequiredInteger(): this { + return this.avgRequiredIntegerAs("avgOfRequiredInteger"); + } + + avgRequiredIntegerAs(retName: string): this { + this.query.aggregate("avg", "requiredInteger", retName); + return this; + } + standardDeviationRequiredInteger(): this { + return this.standardDeviationRequiredIntegerAs("standardDeviationOfRequiredInteger"); + } + + standardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev", "requiredInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredInteger(): this { + return this.squareRootOfPopulationStandardDeviationRequiredIntegerAs("squareRootOfPopulationStandardDeviationOfRequiredInteger"); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredInteger", retName); + return this; + } + sampleVarianceRequiredInteger(): this { + return this.sampleVarianceRequiredIntegerAs("sampleVarianceOfRequiredInteger"); + } + + sampleVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "requiredInteger", retName); + return this; + } + samplePopulationVarianceRequiredInteger(): this { + return this.samplePopulationVarianceRequiredIntegerAs("samplePopulationVarianceOfRequiredInteger"); + } + + samplePopulationVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "requiredInteger", retName); + return this; + } + minOptionalInteger(): this { + return this.minOptionalIntegerAs("minOfOptionalInteger"); + } + + minOptionalIntegerAs(retName: string): this { + this.query.aggregate("min", "optionalInteger", retName); + return this; + } + maxOptionalInteger(): this { + return this.maxOptionalIntegerAs("maxOfOptionalInteger"); + } + + maxOptionalIntegerAs(retName: string): this { + this.query.aggregate("max", "optionalInteger", retName); + return this; + } + sumOptionalInteger(): this { + return this.sumOptionalIntegerAs("sumOfOptionalInteger"); + } + + sumOptionalIntegerAs(retName: string): this { + this.query.aggregate("sum", "optionalInteger", retName); + return this; + } + avgOptionalInteger(): this { + return this.avgOptionalIntegerAs("avgOfOptionalInteger"); + } + + avgOptionalIntegerAs(retName: string): this { + this.query.aggregate("avg", "optionalInteger", retName); + return this; + } + standardDeviationOptionalInteger(): this { + return this.standardDeviationOptionalIntegerAs("standardDeviationOfOptionalInteger"); + } + + standardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev", "optionalInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalInteger(): this { + return this.squareRootOfPopulationStandardDeviationOptionalIntegerAs("squareRootOfPopulationStandardDeviationOfOptionalInteger"); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalInteger", retName); + return this; + } + sampleVarianceOptionalInteger(): this { + return this.sampleVarianceOptionalIntegerAs("sampleVarianceOfOptionalInteger"); + } + + sampleVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "optionalInteger", retName); + return this; + } + samplePopulationVarianceOptionalInteger(): this { + return this.samplePopulationVarianceOptionalIntegerAs("samplePopulationVarianceOfOptionalInteger"); + } + + samplePopulationVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "optionalInteger", retName); + return this; + } + minRequiredLong(): this { + return this.minRequiredLongAs("minOfRequiredLong"); + } + + minRequiredLongAs(retName: string): this { + this.query.aggregate("min", "requiredLong", retName); + return this; + } + maxRequiredLong(): this { + return this.maxRequiredLongAs("maxOfRequiredLong"); + } + + maxRequiredLongAs(retName: string): this { + this.query.aggregate("max", "requiredLong", retName); + return this; + } + sumRequiredLong(): this { + return this.sumRequiredLongAs("sumOfRequiredLong"); + } + + sumRequiredLongAs(retName: string): this { + this.query.aggregate("sum", "requiredLong", retName); + return this; + } + avgRequiredLong(): this { + return this.avgRequiredLongAs("avgOfRequiredLong"); + } + + avgRequiredLongAs(retName: string): this { + this.query.aggregate("avg", "requiredLong", retName); + return this; + } + standardDeviationRequiredLong(): this { + return this.standardDeviationRequiredLongAs("standardDeviationOfRequiredLong"); + } + + standardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev", "requiredLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLong(): this { + return this.squareRootOfPopulationStandardDeviationRequiredLongAs("squareRootOfPopulationStandardDeviationOfRequiredLong"); + } + + squareRootOfPopulationStandardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredLong", retName); + return this; + } + sampleVarianceRequiredLong(): this { + return this.sampleVarianceRequiredLongAs("sampleVarianceOfRequiredLong"); + } + + sampleVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_samp", "requiredLong", retName); + return this; + } + samplePopulationVarianceRequiredLong(): this { + return this.samplePopulationVarianceRequiredLongAs("samplePopulationVarianceOfRequiredLong"); + } + + samplePopulationVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_pop", "requiredLong", retName); + return this; + } + minOptionalLong(): this { + return this.minOptionalLongAs("minOfOptionalLong"); + } + + minOptionalLongAs(retName: string): this { + this.query.aggregate("min", "optionalLong", retName); + return this; + } + maxOptionalLong(): this { + return this.maxOptionalLongAs("maxOfOptionalLong"); + } + + maxOptionalLongAs(retName: string): this { + this.query.aggregate("max", "optionalLong", retName); + return this; + } + sumOptionalLong(): this { + return this.sumOptionalLongAs("sumOfOptionalLong"); + } + + sumOptionalLongAs(retName: string): this { + this.query.aggregate("sum", "optionalLong", retName); + return this; + } + avgOptionalLong(): this { + return this.avgOptionalLongAs("avgOfOptionalLong"); + } + + avgOptionalLongAs(retName: string): this { + this.query.aggregate("avg", "optionalLong", retName); + return this; + } + standardDeviationOptionalLong(): this { + return this.standardDeviationOptionalLongAs("standardDeviationOfOptionalLong"); + } + + standardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev", "optionalLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLong(): this { + return this.squareRootOfPopulationStandardDeviationOptionalLongAs("squareRootOfPopulationStandardDeviationOfOptionalLong"); + } + + squareRootOfPopulationStandardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalLong", retName); + return this; + } + sampleVarianceOptionalLong(): this { + return this.sampleVarianceOptionalLongAs("sampleVarianceOfOptionalLong"); + } + + sampleVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_samp", "optionalLong", retName); + return this; + } + samplePopulationVarianceOptionalLong(): this { + return this.samplePopulationVarianceOptionalLongAs("samplePopulationVarianceOfOptionalLong"); + } + + samplePopulationVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_pop", "optionalLong", retName); + return this; + } + minRequiredDecimal(): this { + return this.minRequiredDecimalAs("minOfRequiredDecimal"); + } + + minRequiredDecimalAs(retName: string): this { + this.query.aggregate("min", "requiredDecimal", retName); + return this; + } + maxRequiredDecimal(): this { + return this.maxRequiredDecimalAs("maxOfRequiredDecimal"); + } + + maxRequiredDecimalAs(retName: string): this { + this.query.aggregate("max", "requiredDecimal", retName); + return this; + } + sumRequiredDecimal(): this { + return this.sumRequiredDecimalAs("sumOfRequiredDecimal"); + } + + sumRequiredDecimalAs(retName: string): this { + this.query.aggregate("sum", "requiredDecimal", retName); + return this; + } + avgRequiredDecimal(): this { + return this.avgRequiredDecimalAs("avgOfRequiredDecimal"); + } + + avgRequiredDecimalAs(retName: string): this { + this.query.aggregate("avg", "requiredDecimal", retName); + return this; + } + standardDeviationRequiredDecimal(): this { + return this.standardDeviationRequiredDecimalAs("standardDeviationOfRequiredDecimal"); + } + + standardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev", "requiredDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimal(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDecimalAs("squareRootOfPopulationStandardDeviationOfRequiredDecimal"); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDecimal", retName); + return this; + } + sampleVarianceRequiredDecimal(): this { + return this.sampleVarianceRequiredDecimalAs("sampleVarianceOfRequiredDecimal"); + } + + sampleVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDecimal", retName); + return this; + } + samplePopulationVarianceRequiredDecimal(): this { + return this.samplePopulationVarianceRequiredDecimalAs("samplePopulationVarianceOfRequiredDecimal"); + } + + samplePopulationVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDecimal", retName); + return this; + } + minOptionalDecimal(): this { + return this.minOptionalDecimalAs("minOfOptionalDecimal"); + } + + minOptionalDecimalAs(retName: string): this { + this.query.aggregate("min", "optionalDecimal", retName); + return this; + } + maxOptionalDecimal(): this { + return this.maxOptionalDecimalAs("maxOfOptionalDecimal"); + } + + maxOptionalDecimalAs(retName: string): this { + this.query.aggregate("max", "optionalDecimal", retName); + return this; + } + sumOptionalDecimal(): this { + return this.sumOptionalDecimalAs("sumOfOptionalDecimal"); + } + + sumOptionalDecimalAs(retName: string): this { + this.query.aggregate("sum", "optionalDecimal", retName); + return this; + } + avgOptionalDecimal(): this { + return this.avgOptionalDecimalAs("avgOfOptionalDecimal"); + } + + avgOptionalDecimalAs(retName: string): this { + this.query.aggregate("avg", "optionalDecimal", retName); + return this; + } + standardDeviationOptionalDecimal(): this { + return this.standardDeviationOptionalDecimalAs("standardDeviationOfOptionalDecimal"); + } + + standardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev", "optionalDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimal(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDecimalAs("squareRootOfPopulationStandardDeviationOfOptionalDecimal"); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDecimal", retName); + return this; + } + sampleVarianceOptionalDecimal(): this { + return this.sampleVarianceOptionalDecimalAs("sampleVarianceOfOptionalDecimal"); + } + + sampleVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDecimal", retName); + return this; + } + samplePopulationVarianceOptionalDecimal(): this { + return this.samplePopulationVarianceOptionalDecimalAs("samplePopulationVarianceOfOptionalDecimal"); + } + + samplePopulationVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDecimal", retName); + return this; + } + minRequiredFloat(): this { + return this.minRequiredFloatAs("minOfRequiredFloat"); + } + + minRequiredFloatAs(retName: string): this { + this.query.aggregate("min", "requiredFloat", retName); + return this; + } + maxRequiredFloat(): this { + return this.maxRequiredFloatAs("maxOfRequiredFloat"); + } + + maxRequiredFloatAs(retName: string): this { + this.query.aggregate("max", "requiredFloat", retName); + return this; + } + sumRequiredFloat(): this { + return this.sumRequiredFloatAs("sumOfRequiredFloat"); + } + + sumRequiredFloatAs(retName: string): this { + this.query.aggregate("sum", "requiredFloat", retName); + return this; + } + avgRequiredFloat(): this { + return this.avgRequiredFloatAs("avgOfRequiredFloat"); + } + + avgRequiredFloatAs(retName: string): this { + this.query.aggregate("avg", "requiredFloat", retName); + return this; + } + standardDeviationRequiredFloat(): this { + return this.standardDeviationRequiredFloatAs("standardDeviationOfRequiredFloat"); + } + + standardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev", "requiredFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloat(): this { + return this.squareRootOfPopulationStandardDeviationRequiredFloatAs("squareRootOfPopulationStandardDeviationOfRequiredFloat"); + } + + squareRootOfPopulationStandardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredFloat", retName); + return this; + } + sampleVarianceRequiredFloat(): this { + return this.sampleVarianceRequiredFloatAs("sampleVarianceOfRequiredFloat"); + } + + sampleVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_samp", "requiredFloat", retName); + return this; + } + samplePopulationVarianceRequiredFloat(): this { + return this.samplePopulationVarianceRequiredFloatAs("samplePopulationVarianceOfRequiredFloat"); + } + + samplePopulationVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_pop", "requiredFloat", retName); + return this; + } + minOptionalFloat(): this { + return this.minOptionalFloatAs("minOfOptionalFloat"); + } + + minOptionalFloatAs(retName: string): this { + this.query.aggregate("min", "optionalFloat", retName); + return this; + } + maxOptionalFloat(): this { + return this.maxOptionalFloatAs("maxOfOptionalFloat"); + } + + maxOptionalFloatAs(retName: string): this { + this.query.aggregate("max", "optionalFloat", retName); + return this; + } + sumOptionalFloat(): this { + return this.sumOptionalFloatAs("sumOfOptionalFloat"); + } + + sumOptionalFloatAs(retName: string): this { + this.query.aggregate("sum", "optionalFloat", retName); + return this; + } + avgOptionalFloat(): this { + return this.avgOptionalFloatAs("avgOfOptionalFloat"); + } + + avgOptionalFloatAs(retName: string): this { + this.query.aggregate("avg", "optionalFloat", retName); + return this; + } + standardDeviationOptionalFloat(): this { + return this.standardDeviationOptionalFloatAs("standardDeviationOfOptionalFloat"); + } + + standardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev", "optionalFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloat(): this { + return this.squareRootOfPopulationStandardDeviationOptionalFloatAs("squareRootOfPopulationStandardDeviationOfOptionalFloat"); + } + + squareRootOfPopulationStandardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalFloat", retName); + return this; + } + sampleVarianceOptionalFloat(): this { + return this.sampleVarianceOptionalFloatAs("sampleVarianceOfOptionalFloat"); + } + + sampleVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_samp", "optionalFloat", retName); + return this; + } + samplePopulationVarianceOptionalFloat(): this { + return this.samplePopulationVarianceOptionalFloatAs("samplePopulationVarianceOfOptionalFloat"); + } + + samplePopulationVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_pop", "optionalFloat", retName); + return this; + } + minRequiredDouble(): this { + return this.minRequiredDoubleAs("minOfRequiredDouble"); + } + + minRequiredDoubleAs(retName: string): this { + this.query.aggregate("min", "requiredDouble", retName); + return this; + } + maxRequiredDouble(): this { + return this.maxRequiredDoubleAs("maxOfRequiredDouble"); + } + + maxRequiredDoubleAs(retName: string): this { + this.query.aggregate("max", "requiredDouble", retName); + return this; + } + sumRequiredDouble(): this { + return this.sumRequiredDoubleAs("sumOfRequiredDouble"); + } + + sumRequiredDoubleAs(retName: string): this { + this.query.aggregate("sum", "requiredDouble", retName); + return this; + } + avgRequiredDouble(): this { + return this.avgRequiredDoubleAs("avgOfRequiredDouble"); + } + + avgRequiredDoubleAs(retName: string): this { + this.query.aggregate("avg", "requiredDouble", retName); + return this; + } + standardDeviationRequiredDouble(): this { + return this.standardDeviationRequiredDoubleAs("standardDeviationOfRequiredDouble"); + } + + standardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev", "requiredDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDouble(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDoubleAs("squareRootOfPopulationStandardDeviationOfRequiredDouble"); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDouble", retName); + return this; + } + sampleVarianceRequiredDouble(): this { + return this.sampleVarianceRequiredDoubleAs("sampleVarianceOfRequiredDouble"); + } + + sampleVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDouble", retName); + return this; + } + samplePopulationVarianceRequiredDouble(): this { + return this.samplePopulationVarianceRequiredDoubleAs("samplePopulationVarianceOfRequiredDouble"); + } + + samplePopulationVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDouble", retName); + return this; + } + minOptionalDouble(): this { + return this.minOptionalDoubleAs("minOfOptionalDouble"); + } + + minOptionalDoubleAs(retName: string): this { + this.query.aggregate("min", "optionalDouble", retName); + return this; + } + maxOptionalDouble(): this { + return this.maxOptionalDoubleAs("maxOfOptionalDouble"); + } + + maxOptionalDoubleAs(retName: string): this { + this.query.aggregate("max", "optionalDouble", retName); + return this; + } + sumOptionalDouble(): this { + return this.sumOptionalDoubleAs("sumOfOptionalDouble"); + } + + sumOptionalDoubleAs(retName: string): this { + this.query.aggregate("sum", "optionalDouble", retName); + return this; + } + avgOptionalDouble(): this { + return this.avgOptionalDoubleAs("avgOfOptionalDouble"); + } + + avgOptionalDoubleAs(retName: string): this { + this.query.aggregate("avg", "optionalDouble", retName); + return this; + } + standardDeviationOptionalDouble(): this { + return this.standardDeviationOptionalDoubleAs("standardDeviationOfOptionalDouble"); + } + + standardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev", "optionalDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDouble(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDoubleAs("squareRootOfPopulationStandardDeviationOfOptionalDouble"); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDouble", retName); + return this; + } + sampleVarianceOptionalDouble(): this { + return this.sampleVarianceOptionalDoubleAs("sampleVarianceOfOptionalDouble"); + } + + sampleVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDouble", retName); + return this; + } + samplePopulationVarianceOptionalDouble(): this { + return this.samplePopulationVarianceOptionalDoubleAs("samplePopulationVarianceOfOptionalDouble"); + } + + samplePopulationVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDouble", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByTypePlatform(): this { + this.query.groupBy("typePlatform"); + return this; + } + + groupByTypePlatformAs(retName: string): this { + this.query.groupBy("typePlatform", retName); + return this; + } + groupByRequiredString(): this { + this.query.groupBy("requiredString"); + return this; + } + + groupByRequiredStringAs(retName: string): this { + this.query.groupBy("requiredString", retName); + return this; + } + groupByOptionalString(): this { + this.query.groupBy("optionalString"); + return this; + } + + groupByOptionalStringAs(retName: string): this { + this.query.groupBy("optionalString", retName); + return this; + } + groupByLargeText(): this { + this.query.groupBy("largeText"); + return this; + } + + groupByLargeTextAs(retName: string): this { + this.query.groupBy("largeText", retName); + return this; + } + groupByRequiredBoolean(): this { + this.query.groupBy("requiredBoolean"); + return this; + } + + groupByRequiredBooleanAs(retName: string): this { + this.query.groupBy("requiredBoolean", retName); + return this; + } + groupByOptionalBoolean(): this { + this.query.groupBy("optionalBoolean"); + return this; + } + + groupByOptionalBooleanAs(retName: string): this { + this.query.groupBy("optionalBoolean", retName); + return this; + } + groupByRequiredInteger(): this { + this.query.groupBy("requiredInteger"); + return this; + } + + groupByRequiredIntegerAs(retName: string): this { + this.query.groupBy("requiredInteger", retName); + return this; + } + groupByOptionalInteger(): this { + this.query.groupBy("optionalInteger"); + return this; + } + + groupByOptionalIntegerAs(retName: string): this { + this.query.groupBy("optionalInteger", retName); + return this; + } + groupByRequiredLong(): this { + this.query.groupBy("requiredLong"); + return this; + } + + groupByRequiredLongAs(retName: string): this { + this.query.groupBy("requiredLong", retName); + return this; + } + groupByOptionalLong(): this { + this.query.groupBy("optionalLong"); + return this; + } + + groupByOptionalLongAs(retName: string): this { + this.query.groupBy("optionalLong", retName); + return this; + } + groupByRequiredDecimal(): this { + this.query.groupBy("requiredDecimal"); + return this; + } + + groupByRequiredDecimalAs(retName: string): this { + this.query.groupBy("requiredDecimal", retName); + return this; + } + groupByOptionalDecimal(): this { + this.query.groupBy("optionalDecimal"); + return this; + } + + groupByOptionalDecimalAs(retName: string): this { + this.query.groupBy("optionalDecimal", retName); + return this; + } + groupByRequiredFloat(): this { + this.query.groupBy("requiredFloat"); + return this; + } + + groupByRequiredFloatAs(retName: string): this { + this.query.groupBy("requiredFloat", retName); + return this; + } + groupByOptionalFloat(): this { + this.query.groupBy("optionalFloat"); + return this; + } + + groupByOptionalFloatAs(retName: string): this { + this.query.groupBy("optionalFloat", retName); + return this; + } + groupByRequiredDouble(): this { + this.query.groupBy("requiredDouble"); + return this; + } + + groupByRequiredDoubleAs(retName: string): this { + this.query.groupBy("requiredDouble", retName); + return this; + } + groupByOptionalDouble(): this { + this.query.groupBy("optionalDouble"); + return this; + } + + groupByOptionalDoubleAs(retName: string): this { + this.query.groupBy("optionalDouble", retName); + return this; + } + groupByRequiredDate(): this { + this.query.groupBy("requiredDate"); + return this; + } + + groupByRequiredDateAs(retName: string): this { + this.query.groupBy("requiredDate", retName); + return this; + } + groupByOptionalDate(): this { + this.query.groupBy("optionalDate"); + return this; + } + + groupByOptionalDateAs(retName: string): this { + this.query.groupBy("optionalDate", retName); + return this; + } + groupByRequiredTime(): this { + this.query.groupBy("requiredTime"); + return this; + } + + groupByRequiredTimeAs(retName: string): this { + this.query.groupBy("requiredTime", retName); + return this; + } + groupByOptionalTime(): this { + this.query.groupBy("optionalTime"); + return this; + } + + groupByOptionalTimeAs(retName: string): this { + this.query.groupBy("optionalTime", retName); + return this; + } + groupByRequiredDatetime(): this { + this.query.groupBy("requiredDatetime"); + return this; + } + + groupByRequiredDatetimeAs(retName: string): this { + this.query.groupBy("requiredDatetime", retName); + return this; + } + groupByOptionalDatetime(): this { + this.query.groupBy("optionalDatetime"); + return this; + } + + groupByOptionalDatetimeAs(retName: string): this { + this.query.groupBy("optionalDatetime", retName); + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime", retName); + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + facetByTypePlatformAs( + facetName: string, + request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "typePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByTypePlatformAs", relation: "typePlatform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof ScalarTypeProbe + ? entity + : ScalarTypeProbe.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableScalarTypeProbeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return ScalarTypeProbe.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/requests/TypePlatformRequest.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/requests/TypePlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d0caed3d9719c20a917e89fdcad7bad64597fb0 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/generated/requests/TypePlatformRequest.ts @@ -0,0 +1,1736 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { TypePlatform } from '../models/TypePlatform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class TypePlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("TypePlatform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "TypePlatform" { + return "TypePlatform"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTypePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableTypePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectScalarTypeProbeListWith(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "scalarTypeProbeList", request.toQuery(), "id", "typePlatform", true, + { kind: "relation-select", method: "selectScalarTypeProbeListWith", relation: "scalarTypeProbeList" }); + return this; + } + + haveScalarTypeProbes(): this { + return this.withScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + haveNoScalarTypeProbes(): this { + return this.withoutScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + withScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + withoutScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + countScalarTypeProbes(): this { + return this.countScalarTypeProbesAs("countScalarTypeProbes"); + } + + countScalarTypeProbesAs(alias: string): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + this.countScalarTypeProbesWith(alias, { entityName: "ScalarTypeProbe", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }; + return this; + } + + countScalarTypeProbesWith(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "relation-count", method: "countScalarTypeProbesWith", relation: "scalarTypeProbeList", alias }); + return this; + } + + minRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredIntegerOfScalarTypeProbesAs( + "minOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredIntegerOfScalarTypeProbesAs( + "maxOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredIntegerOfScalarTypeProbesAs( + "sumOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredIntegerOfScalarTypeProbesAs( + "avgOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredIntegerOfScalarTypeProbesAs( + "standardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredIntegerOfScalarTypeProbesAs( + "sampleVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalIntegerOfScalarTypeProbesAs( + "minOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalIntegerOfScalarTypeProbesAs( + "maxOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalIntegerOfScalarTypeProbesAs( + "sumOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalIntegerOfScalarTypeProbesAs( + "avgOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalIntegerOfScalarTypeProbesAs( + "standardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalIntegerOfScalarTypeProbesAs( + "sampleVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredLongOfScalarTypeProbesAs( + "minOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredLongOfScalarTypeProbesAs( + "maxOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredLongOfScalarTypeProbesAs( + "sumOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredLongOfScalarTypeProbesAs( + "avgOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredLongOfScalarTypeProbesAs( + "standardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredLongOfScalarTypeProbesAs( + "sampleVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalLongOfScalarTypeProbesAs( + "minOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalLongOfScalarTypeProbesAs( + "maxOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalLongOfScalarTypeProbesAs( + "sumOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalLongOfScalarTypeProbesAs( + "avgOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalLongOfScalarTypeProbesAs( + "standardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalLongOfScalarTypeProbesAs( + "sampleVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDecimalOfScalarTypeProbesAs( + "minOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDecimalOfScalarTypeProbesAs( + "maxOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDecimalOfScalarTypeProbesAs( + "sumOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDecimalOfScalarTypeProbesAs( + "avgOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDecimalOfScalarTypeProbesAs( + "standardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDecimalOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDecimalOfScalarTypeProbesAs( + "minOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDecimalOfScalarTypeProbesAs( + "maxOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDecimalOfScalarTypeProbesAs( + "sumOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDecimalOfScalarTypeProbesAs( + "avgOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDecimalOfScalarTypeProbesAs( + "standardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDecimalOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredFloatOfScalarTypeProbesAs( + "minOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredFloatOfScalarTypeProbesAs( + "maxOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredFloatOfScalarTypeProbesAs( + "sumOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredFloatOfScalarTypeProbesAs( + "avgOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredFloatOfScalarTypeProbesAs( + "standardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredFloatOfScalarTypeProbesAs( + "sampleVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalFloatOfScalarTypeProbesAs( + "minOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalFloatOfScalarTypeProbesAs( + "maxOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalFloatOfScalarTypeProbesAs( + "sumOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalFloatOfScalarTypeProbesAs( + "avgOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalFloatOfScalarTypeProbesAs( + "standardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalFloatOfScalarTypeProbesAs( + "sampleVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDoubleOfScalarTypeProbesAs( + "minOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDoubleOfScalarTypeProbesAs( + "maxOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDoubleOfScalarTypeProbesAs( + "sumOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDoubleOfScalarTypeProbesAs( + "avgOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDoubleOfScalarTypeProbesAs( + "standardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDoubleOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDoubleOfScalarTypeProbesAs( + "minOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDoubleOfScalarTypeProbesAs( + "maxOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDoubleOfScalarTypeProbesAs( + "sumOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDoubleOfScalarTypeProbesAs( + "avgOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDoubleOfScalarTypeProbesAs( + "standardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDoubleOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof TypePlatform + ? entity + : TypePlatform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTypePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return TypePlatform.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/runtime-module.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..4c4f061abab6174cf25a15f41f2a3367792bb284 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/runtime-module.ts @@ -0,0 +1,128 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "camelCase" as const, + entities: Object.freeze({ + "TypePlatform": Object.freeze({ + entityType: "TypePlatform", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "ScalarTypeProbe": Object.freeze({ + entityType: "ScalarTypeProbe", + profile: "camelCase" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "type_platform": Object.freeze({ canonicalName: "type_platform", wireName: "typePlatform", aliases: Object.freeze([] as string[]) }), + "required_string": Object.freeze({ canonicalName: "required_string", wireName: "requiredString", aliases: Object.freeze([] as string[]) }), + "optional_string": Object.freeze({ canonicalName: "optional_string", wireName: "optionalString", aliases: Object.freeze([] as string[]) }), + "large_text": Object.freeze({ canonicalName: "large_text", wireName: "largeText", aliases: Object.freeze([] as string[]) }), + "required_boolean": Object.freeze({ canonicalName: "required_boolean", wireName: "requiredBoolean", aliases: Object.freeze([] as string[]) }), + "optional_boolean": Object.freeze({ canonicalName: "optional_boolean", wireName: "optionalBoolean", aliases: Object.freeze([] as string[]) }), + "required_integer": Object.freeze({ canonicalName: "required_integer", wireName: "requiredInteger", aliases: Object.freeze([] as string[]) }), + "optional_integer": Object.freeze({ canonicalName: "optional_integer", wireName: "optionalInteger", aliases: Object.freeze([] as string[]) }), + "required_long": Object.freeze({ canonicalName: "required_long", wireName: "requiredLong", aliases: Object.freeze([] as string[]) }), + "optional_long": Object.freeze({ canonicalName: "optional_long", wireName: "optionalLong", aliases: Object.freeze([] as string[]) }), + "required_decimal": Object.freeze({ canonicalName: "required_decimal", wireName: "requiredDecimal", aliases: Object.freeze([] as string[]) }), + "optional_decimal": Object.freeze({ canonicalName: "optional_decimal", wireName: "optionalDecimal", aliases: Object.freeze([] as string[]) }), + "required_float": Object.freeze({ canonicalName: "required_float", wireName: "requiredFloat", aliases: Object.freeze([] as string[]) }), + "optional_float": Object.freeze({ canonicalName: "optional_float", wireName: "optionalFloat", aliases: Object.freeze([] as string[]) }), + "required_double": Object.freeze({ canonicalName: "required_double", wireName: "requiredDouble", aliases: Object.freeze([] as string[]) }), + "optional_double": Object.freeze({ canonicalName: "optional_double", wireName: "optionalDouble", aliases: Object.freeze([] as string[]) }), + "required_date": Object.freeze({ canonicalName: "required_date", wireName: "requiredDate", aliases: Object.freeze([] as string[]) }), + "optional_date": Object.freeze({ canonicalName: "optional_date", wireName: "optionalDate", aliases: Object.freeze([] as string[]) }), + "required_time": Object.freeze({ canonicalName: "required_time", wireName: "requiredTime", aliases: Object.freeze([] as string[]) }), + "optional_time": Object.freeze({ canonicalName: "optional_time", wireName: "optionalTime", aliases: Object.freeze([] as string[]) }), + "required_datetime": Object.freeze({ canonicalName: "required_datetime", wireName: "requiredDatetime", aliases: Object.freeze([] as string[]) }), + "optional_datetime": Object.freeze({ canonicalName: "optional_datetime", wireName: "optionalDatetime", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "createTime", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "updateTime", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "TypePlatform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "ScalarTypeProbe": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["type_platform"] === undefined) || mutation.payload["type_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("type_platform") }); + + if ((mutation.action === "Create" && mutation.payload["required_string"] === undefined) || mutation.payload["required_string"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_string") }); + if (mutation.payload["required_string"] != null && [...String(mutation.payload["required_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("required_string"), inputValue: mutation.payload["required_string"], systemValue: 100 }); + + if (mutation.payload["optional_string"] != null && [...String(mutation.payload["optional_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("optional_string"), inputValue: mutation.payload["optional_string"], systemValue: 100 }); + + + if ((mutation.action === "Create" && mutation.payload["required_boolean"] === undefined) || mutation.payload["required_boolean"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_boolean") }); + + + if ((mutation.action === "Create" && mutation.payload["required_integer"] === undefined) || mutation.payload["required_integer"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_integer") }); + + + if ((mutation.action === "Create" && mutation.payload["required_long"] === undefined) || mutation.payload["required_long"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_long") }); + + + if ((mutation.action === "Create" && mutation.payload["required_decimal"] === undefined) || mutation.payload["required_decimal"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_decimal") }); + + + if ((mutation.action === "Create" && mutation.payload["required_float"] === undefined) || mutation.payload["required_float"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_float") }); + + + if ((mutation.action === "Create" && mutation.payload["required_double"] === undefined) || mutation.payload["required_double"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_double") }); + + + if ((mutation.action === "Create" && mutation.payload["required_date"] === undefined) || mutation.payload["required_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_date") }); + + + if ((mutation.action === "Create" && mutation.payload["required_time"] === undefined) || mutation.payload["required_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_time") }); + + + if ((mutation.action === "Create" && mutation.payload["required_datetime"] === undefined) || mutation.payload["required_datetime"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_datetime") }); + + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "TypePlatform", id: "1", values: { "name": "Scalar Type Conformance" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-node-sql.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f5d108d228a1dbec1140e735022c1d72d704eb6 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-node-sql.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"TypePlatform": { + table: "type_platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"scalarTypeProbeList": { targetEntity: "ScalarTypeProbe", localKey: "id", foreignKey: "typePlatform", many: true }} +}, +"ScalarTypeProbe": { + table: "scalar_type_probe_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "typePlatform": { columnName: "type_platform", modelName: "type_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "requiredString": { columnName: "required_string", modelName: "required_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "optionalString": { columnName: "optional_string", modelName: "optional_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "largeText": { columnName: "large_text", modelName: "large_text", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "requiredBoolean": { columnName: "required_boolean", modelName: "required_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "optionalBoolean": { columnName: "optional_boolean", modelName: "optional_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: true }, "requiredInteger": { columnName: "required_integer", modelName: "required_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "optionalInteger": { columnName: "optional_integer", modelName: "optional_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: true, integer32: true }, "requiredLong": { columnName: "required_long", modelName: "required_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: false }, "optionalLong": { columnName: "optional_long", modelName: "optional_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: true }, "requiredDecimal": { columnName: "required_decimal", modelName: "required_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "optionalDecimal": { columnName: "optional_decimal", modelName: "optional_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: true }, "requiredFloat": { columnName: "required_float", modelName: "required_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalFloat": { columnName: "optional_float", modelName: "optional_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDouble": { columnName: "required_double", modelName: "required_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalDouble": { columnName: "optional_double", modelName: "optional_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDate": { columnName: "required_date", modelName: "required_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "optionalDate": { columnName: "optional_date", modelName: "optional_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: true }, "requiredTime": { columnName: "required_time", modelName: "required_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: false }, "optionalTime": { columnName: "optional_time", modelName: "optional_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: true }, "requiredDatetime": { columnName: "required_datetime", modelName: "required_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "optionalDatetime": { columnName: "optional_datetime", modelName: "optional_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: true }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"typePlatform": { targetEntity: "TypePlatform", localKey: "typePlatform", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-ts.ts b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..9983b00b27c90dc429fca76441f2bf077f825921 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/src/teaql-ts.ts @@ -0,0 +1,518 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/teaql-i18n.json b/source/teaql-ts/examples/expression-profiles/generated/camelCase/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..9bccc83b0cb5f837bc4c9ee6a49415974e1a4d50 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/teaql-i18n.json @@ -0,0 +1,127 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.scalarTypeProbe.largeText": "Large Text", + "property.scalarTypeProbe.requiredString": "Required String", + "property.scalarTypeProbe.id": "Id", + "property.scalarTypeProbe.optionalDecimal": "Optional Decimal", + "property.scalarTypeProbe.requiredDate": "Required Date", + "property.scalarTypeProbe.optionalString": "Optional String", + "property.scalarTypeProbe.requiredLong": "Required Long", + "property.typePlatform.version": "Version", + "entity.scalarTypeProbe": "Scalar Type Probe", + "property.scalarTypeProbe.optionalTime": "Optional Time", + "property.scalarTypeProbe.typePlatform": "Type Platform", + "property.scalarTypeProbe.optionalLong": "Optional Long", + "property.scalarTypeProbe.requiredDatetime": "Required Datetime", + "property.scalarTypeProbe.requiredTime": "Required Time", + "property.scalarTypeProbe.optionalBoolean": "Optional Boolean", + "property.scalarTypeProbe.optionalInteger": "Optional Integer", + "property.scalarTypeProbe.requiredDouble": "Required Double", + "entity.typePlatform": "Type Platform", + "property.scalarTypeProbe.requiredInteger": "Required Integer", + "property.scalarTypeProbe.optionalDouble": "Optional Double", + "property.scalarTypeProbe.optionalDatetime": "Optional Datetime", + "property.scalarTypeProbe.createTime": "Create Time", + "property.scalarTypeProbe.requiredFloat": "Required Float", + "property.typePlatform.id": "Id", + "property.scalarTypeProbe.requiredDecimal": "Required Decimal", + "property.scalarTypeProbe.optionalFloat": "Optional Float", + "property.scalarTypeProbe.version": "Version", + "property.scalarTypeProbe.requiredBoolean": "Required Boolean", + "property.scalarTypeProbe.updateTime": "Update Time", + "property.typePlatform.name": "Name", + "property.scalarTypeProbe.optionalDate": "Optional Date" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/camelCase/tsconfig.json b/source/teaql-ts/examples/expression-profiles/generated/camelCase/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/camelCase/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/manifest.json b/source/teaql-ts/examples/expression-profiles/generated/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..0f24d8c9f9087ce28e96b4c7faa74ac99a1ffef7 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/manifest.json @@ -0,0 +1,422 @@ +{ + "localSourceOnly": true, + "profiles": { + "camelCase": { + "evaluation": { + "solids": [ + { + "ruleId": "KSML-UPLOAD-001", + "title": "Model upload is non-empty", + "message": "The upload contains 1 files.", + "path": "model.zip", + "objectName": null, + "fieldName": null, + "xmlPath": null, + "lineNumber": null, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.zip" + }, + { + "ruleId": "KSML-UPLOAD-005", + "title": "Valid entrypoint found", + "message": "Resolved entrypoint: model.xml", + "path": "model.xml", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.xml" + }, + { + "ruleId": "KSML-XML-002", + "title": "XML is well-formed", + "message": "The XML document model.xml was parsed successfully.", + "path": "model.xml", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.xml" + }, + { + "ruleId": "KSML-ROOT-003", + "title": "Standard root name", + "message": "Root name 'scalar-type-conformance-service' is well-formed.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + }, + { + "ruleId": "KSML-ROOT-008", + "title": "Default JSON field naming", + "message": "External JSON business fields use the default camelCase profile.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + }, + { + "ruleId": "KSML-OBJECT-001", + "title": "Object display metadata exists", + "message": "Object 'type_platform' defines display name, module, and module key metadata.", + "path": "/root/type_platform", + "objectName": "type_platform", + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 7, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "type_platform" + }, + { + "ruleId": "KSML-OBJECT-001", + "title": "Object display metadata exists", + "message": "Object 'scalar_type_probe' defines display name, module, and module key metadata.", + "path": "/root/scalar_type_probe", + "objectName": "scalar_type_probe", + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 12, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "scalar_type_probe" + }, + { + "ruleId": "KSML-REFERENCE-003", + "title": "Reference target exists", + "message": "Reference 'type_platform' in 'scalar_type_probe' successfully resolves to target object 'type_platform'.", + "path": "/root/scalar_type_probe/type_platform", + "objectName": "scalar_type_probe", + "fieldName": "type_platform", + "xmlPath": "model.xml", + "lineNumber": 15, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "scalar_type_probe.type_platform" + }, + { + "ruleId": "KSML-DOMAIN-ROOT-003", + "title": "One domain root found", + "message": "Exactly one domain root candidate 'type_platform' was found.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + } + ], + "warnings": [], + "suggestions": [], + "errors": [], + "privacyFindings": [], + "privacyRegions": [], + "errorSummaries": [] + }, + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "c96e60f771a2477dc64ece64a860c117a63d79790f229683f375aae1f89ac14f", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "b8898eecf41ea135ba72efe960cfda1eede40ec5cc1afba5a077ba4c6b8dfcf5", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "modelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762" + }, + "snake_case": { + "evaluation": { + "solids": [ + { + "ruleId": "KSML-UPLOAD-001", + "title": "Model upload is non-empty", + "message": "The upload contains 1 files.", + "path": "model.zip", + "objectName": null, + "fieldName": null, + "xmlPath": null, + "lineNumber": null, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.zip" + }, + { + "ruleId": "KSML-UPLOAD-005", + "title": "Valid entrypoint found", + "message": "Resolved entrypoint: model.xml", + "path": "model.xml", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.xml" + }, + { + "ruleId": "KSML-XML-002", + "title": "XML is well-formed", + "message": "The XML document model.xml was parsed successfully.", + "path": "model.xml", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.xml" + }, + { + "ruleId": "KSML-ROOT-003", + "title": "Standard root name", + "message": "Root name 'scalar-type-conformance-service' is well-formed.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + }, + { + "ruleId": "KSML-ROOT-008", + "title": "Explicit JSON field naming", + "message": "External JSON business fields use the snake_case profile.", + "path": "/root/@json_field_naming", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root/@json_field_naming" + }, + { + "ruleId": "KSML-OBJECT-001", + "title": "Object display metadata exists", + "message": "Object 'type_platform' defines display name, module, and module key metadata.", + "path": "/root/type_platform", + "objectName": "type_platform", + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 7, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "type_platform" + }, + { + "ruleId": "KSML-OBJECT-001", + "title": "Object display metadata exists", + "message": "Object 'scalar_type_probe' defines display name, module, and module key metadata.", + "path": "/root/scalar_type_probe", + "objectName": "scalar_type_probe", + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 12, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "scalar_type_probe" + }, + { + "ruleId": "KSML-REFERENCE-003", + "title": "Reference target exists", + "message": "Reference 'type_platform' in 'scalar_type_probe' successfully resolves to target object 'type_platform'.", + "path": "/root/scalar_type_probe/type_platform", + "objectName": "scalar_type_probe", + "fieldName": "type_platform", + "xmlPath": "model.xml", + "lineNumber": 15, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "scalar_type_probe.type_platform" + }, + { + "ruleId": "KSML-DOMAIN-ROOT-003", + "title": "One domain root found", + "message": "Exactly one domain root candidate 'type_platform' was found.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + } + ], + "warnings": [], + "suggestions": [], + "errors": [], + "privacyFindings": [], + "privacyRegions": [], + "errorSummaries": [] + }, + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "2f00d292b921bfc9d2587bd39b479f5c199d2ee14d7b2ad59164ece6ae701a53", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "25be59abce5f53f0434f3cb781ff29930118e08d851e2c7f8930a447e6b34956", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "7612e85788dcb016d17e25d87b392484eb6e2a14e530c2cee955f54048e091d4", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "modelSha256": "2dbbcfea6057a5dc7c7c356ea4d0dacec5d5165538f6a9c5903d4d3b64ee13c6" + }, + "PascalCase": { + "evaluation": { + "solids": [ + { + "ruleId": "KSML-UPLOAD-001", + "title": "Model upload is non-empty", + "message": "The upload contains 1 files.", + "path": "model.zip", + "objectName": null, + "fieldName": null, + "xmlPath": null, + "lineNumber": null, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.zip" + }, + { + "ruleId": "KSML-UPLOAD-005", + "title": "Valid entrypoint found", + "message": "Resolved entrypoint: model.xml", + "path": "model.xml", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.xml" + }, + { + "ruleId": "KSML-XML-002", + "title": "XML is well-formed", + "message": "The XML document model.xml was parsed successfully.", + "path": "model.xml", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "model.xml" + }, + { + "ruleId": "KSML-ROOT-003", + "title": "Standard root name", + "message": "Root name 'scalar-type-conformance-service' is well-formed.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + }, + { + "ruleId": "KSML-ROOT-008", + "title": "Explicit JSON field naming", + "message": "External JSON business fields use the PascalCase profile.", + "path": "/root/@json_field_naming", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root/@json_field_naming" + }, + { + "ruleId": "KSML-OBJECT-001", + "title": "Object display metadata exists", + "message": "Object 'type_platform' defines display name, module, and module key metadata.", + "path": "/root/type_platform", + "objectName": "type_platform", + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 7, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "type_platform" + }, + { + "ruleId": "KSML-OBJECT-001", + "title": "Object display metadata exists", + "message": "Object 'scalar_type_probe' defines display name, module, and module key metadata.", + "path": "/root/scalar_type_probe", + "objectName": "scalar_type_probe", + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 12, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "scalar_type_probe" + }, + { + "ruleId": "KSML-REFERENCE-003", + "title": "Reference target exists", + "message": "Reference 'type_platform' in 'scalar_type_probe' successfully resolves to target object 'type_platform'.", + "path": "/root/scalar_type_probe/type_platform", + "objectName": "scalar_type_probe", + "fieldName": "type_platform", + "xmlPath": "model.xml", + "lineNumber": 15, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "scalar_type_probe.type_platform" + }, + { + "ruleId": "KSML-DOMAIN-ROOT-003", + "title": "One domain root found", + "message": "Exactly one domain root candidate 'type_platform' was found.", + "path": "/root", + "objectName": null, + "fieldName": null, + "xmlPath": "model.xml", + "lineNumber": 2, + "action": "Check agents/ERROR-FIX.md", + "reportTarget": "/root" + } + ], + "warnings": [], + "suggestions": [], + "errors": [], + "privacyFindings": [], + "privacyRegions": [], + "errorSummaries": [] + }, + "files": { + "src/generated/Q.ts": "e9c654d67ae27c4fdb1fbb38cfdb99a4a89b88fdeeac3de2ae862358bae3b143", + "src/generated/requests/TypePlatformRequest.ts": "8e1d934620cb0d219a1c49b784f3393405ab6ab55fc078bc7c5457c8fe384439", + "src/generated/requests/ScalarTypeProbeRequest.ts": "4482165d965b0f3243097325d7fa3e0e13c36434188a04e11a8524d32d101dad", + "teaql-i18n.json": "a2b6c40ece22b6c1c4b0231036e6859c294494c3ed6db8d24d57f08448457163", + "src/generated/E.ts": "308087ba9c10dcd6f8c95d5e2d58733d2dcd8b8c1a4863b9f95b4de30040b612", + "package.json": "cb8450ca7d5fb93070a44708c994db3788f2cf37a70e6e0d5009003889ae83a2", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "e9c3dcd04b5a092d3cb7dcd428bcfbe07dc80fc4b7de5288cf97c86861c4e104", + "src/teaql-node-sql.ts": "6061936d57cb9f57cdf2a60acb10aeb84ab839e5d927b0f14fe64ae47156ebd6", + "src/runtime-module.ts": "c7f821936abf6f09486447f7a47dd4a83213bf12477d72aa06fd5d76ce2d6748", + "src/generated-bootstrap.ts": "e5846bf3490e0b4262851afdc458015ce6c5b73462381ac276205826a4da1707", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/TypePlatform.ts": "816950380f56762036989697251520c4f29c673eac2a614a1c7ff142978630bc", + "src/generated/models/ScalarTypeProbe.ts": "5905fc0e5421edc4391214b5ab68eabe975243d0c7e8e276d7ccc26d6e6dade8" + }, + "modelSha256": "f836540a765f8c372bd7103a25a83ca316797253079ac63f8a1ef5ee4ded027d" + } + }, + "language": "typescript", + "schema": "teaql.generated-expression-model-profiles/v1", + "baseModelSha256": "8d3017392ffd00abbc06be2555ced27ac6360e2d05fabc4299e27a5ef8f1c762" +} diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/model.xml b/source/teaql-ts/examples/expression-profiles/generated/snake_case/model.xml new file mode 100644 index 0000000000000000000000000000000000000000..21d6fd273f45e5de194997ec750288138e4fa781 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/model.xml @@ -0,0 +1,39 @@ + + + + + + diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/package.json b/source/teaql-ts/examples/expression-profiles/generated/snake_case/package.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc0449fe65f58906b3f4b83d82fd3074e3aaf88 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/package.json @@ -0,0 +1,18 @@ +{ + "name": "scalar-type-conformance-service-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.3.1", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated-bootstrap.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated-bootstrap.ts new file mode 100644 index 0000000000000000000000000000000000000000..c32758df9a96057fe59280ac184fac252759e0b2 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated-bootstrap.ts @@ -0,0 +1,14 @@ +import { UserContext, decimal, long, localTime } from './teaql-ts'; +import { Q } from './generated/Q'; +import { TypePlatform } from './generated/models/TypePlatform'; + +/** @internal Generated typed Mutation bootstrap; never call from application code. */ +export async function ensureGeneratedBootstrap(context: UserContext): Promise { + let domainRoot = (await Q.typePlatforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; + if (!domainRoot) { + domainRoot = TypePlatform.teaqlBootstrapNew(context, '1'); + domainRoot.updateName("Scalar Type Conformance"); + await domainRoot.auditAs('create generated Domain Root TypePlatform').save(context); + } + context.withActiveRoot({ entity: 'TypePlatform', id: domainRoot.id! }); +} diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated-search-models.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated-search-models.ts new file mode 100644 index 0000000000000000000000000000000000000000..40a79e6c3579b1785644cba497ee964459a779bc --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated-search-models.ts @@ -0,0 +1,130 @@ +import type { GeneratedSearchModel } from "teaql-ts"; + +/** Generated trusted naming/type metadata. No query execution or authorization lives here. */ +export const GENERATED_SEARCH_MODELS: Readonly> = Object.freeze({ + "TypePlatform": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "name": "string" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "name": "name", + "version": "version", + }), + relations: Object.freeze({ + "scalarTypeProbeList": "ScalarTypeProbe", + }), + }), + "ScalarTypeProbe": Object.freeze({ + fields: Object.freeze({ + "id": "integer" as const, + "type_platform": "integer" as const, + "typePlatform": "integer" as const, + "required_string": "string" as const, + "requiredString": "string" as const, + "optional_string": "string" as const, + "optionalString": "string" as const, + "large_text": "string" as const, + "largeText": "string" as const, + "required_boolean": "boolean" as const, + "requiredBoolean": "boolean" as const, + "optional_boolean": "boolean" as const, + "optionalBoolean": "boolean" as const, + "required_integer": "integer" as const, + "requiredInteger": "integer" as const, + "optional_integer": "integer" as const, + "optionalInteger": "integer" as const, + "required_long": "integer" as const, + "requiredLong": "integer" as const, + "optional_long": "integer" as const, + "optionalLong": "integer" as const, + "required_decimal": "decimal" as const, + "requiredDecimal": "decimal" as const, + "optional_decimal": "decimal" as const, + "optionalDecimal": "decimal" as const, + "required_float": "number" as const, + "requiredFloat": "number" as const, + "optional_float": "number" as const, + "optionalFloat": "number" as const, + "required_double": "number" as const, + "requiredDouble": "number" as const, + "optional_double": "number" as const, + "optionalDouble": "number" as const, + "required_date": "date" as const, + "requiredDate": "date" as const, + "optional_date": "date" as const, + "optionalDate": "date" as const, + "required_time": "unsupported" as const, + "requiredTime": "unsupported" as const, + "optional_time": "unsupported" as const, + "optionalTime": "unsupported" as const, + "required_datetime": "timestamp" as const, + "requiredDatetime": "timestamp" as const, + "optional_datetime": "timestamp" as const, + "optionalDatetime": "timestamp" as const, + "create_time": "timestamp" as const, + "createTime": "timestamp" as const, + "update_time": "timestamp" as const, + "updateTime": "timestamp" as const, + "version": "integer" as const, + }), + queryFields: Object.freeze({ + "id": "id", + "type_platform": "typePlatform", + "typePlatform": "typePlatform", + "required_string": "requiredString", + "requiredString": "requiredString", + "optional_string": "optionalString", + "optionalString": "optionalString", + "large_text": "largeText", + "largeText": "largeText", + "required_boolean": "requiredBoolean", + "requiredBoolean": "requiredBoolean", + "optional_boolean": "optionalBoolean", + "optionalBoolean": "optionalBoolean", + "required_integer": "requiredInteger", + "requiredInteger": "requiredInteger", + "optional_integer": "optionalInteger", + "optionalInteger": "optionalInteger", + "required_long": "requiredLong", + "requiredLong": "requiredLong", + "optional_long": "optionalLong", + "optionalLong": "optionalLong", + "required_decimal": "requiredDecimal", + "requiredDecimal": "requiredDecimal", + "optional_decimal": "optionalDecimal", + "optionalDecimal": "optionalDecimal", + "required_float": "requiredFloat", + "requiredFloat": "requiredFloat", + "optional_float": "optionalFloat", + "optionalFloat": "optionalFloat", + "required_double": "requiredDouble", + "requiredDouble": "requiredDouble", + "optional_double": "optionalDouble", + "optionalDouble": "optionalDouble", + "required_date": "requiredDate", + "requiredDate": "requiredDate", + "optional_date": "optionalDate", + "optionalDate": "optionalDate", + "required_time": "requiredTime", + "requiredTime": "requiredTime", + "optional_time": "optionalTime", + "optionalTime": "optionalTime", + "required_datetime": "requiredDatetime", + "requiredDatetime": "requiredDatetime", + "optional_datetime": "optionalDatetime", + "optionalDatetime": "optionalDatetime", + "create_time": "createTime", + "createTime": "createTime", + "update_time": "updateTime", + "updateTime": "updateTime", + "version": "version", + }), + relations: Object.freeze({ + "type_platform": "TypePlatform", + "typePlatform": "TypePlatform", + }), + }), +}); \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/E.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..8a040e3336a6948804ac265e5ccec06b27ea4fd7 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/E.ts @@ -0,0 +1,564 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { TypePlatform } from './models/TypePlatform'; +import { ScalarTypeProbe } from './models/ScalarTypeProbe'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class TypePlatformExpression { + constructor( + private readonly value: TypePlatform | null | undefined, + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.typePlatform()', 'snake_case'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): TypePlatform | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + scalarTypeProbeList(): ScalarTypeProbeListExpression { + const path = this.path.member('scalar_type_probe_list', 'scalarTypeProbeList'); + if (this.notLoaded) { + return new ScalarTypeProbeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return ScalarTypeProbeListExpression.missing(this.root, path); + if (!this.value.isLoaded('scalarTypeProbeList')) { + return new ScalarTypeProbeListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'scalar_type_probe_list')); + } + return new ScalarTypeProbeListExpression( + this.value.scalarTypeProbeList(), this.root, path, + ); + } +} + +export class ScalarTypeProbeExpression { + constructor( + private readonly value: ScalarTypeProbe | null | undefined, + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.scalarTypeProbe()', 'snake_case'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): ScalarTypeProbe | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + requiredString(): ValueExpression { + const path = this.path.member('required_string', 'requiredString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_string'), + ); + } + return new ValueExpression(this.value.requiredString); + } + + optionalString(): ValueExpression { + const path = this.path.member('optional_string', 'optionalString'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalString')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_string'), + ); + } + return new ValueExpression(this.value.optionalString); + } + + largeText(): ValueExpression { + const path = this.path.member('large_text', 'largeText'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('largeText')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'large_text'), + ); + } + return new ValueExpression(this.value.largeText); + } + + requiredBoolean(): ValueExpression { + const path = this.path.member('required_boolean', 'requiredBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_boolean'), + ); + } + return new ValueExpression(this.value.requiredBoolean); + } + + optionalBoolean(): ValueExpression { + const path = this.path.member('optional_boolean', 'optionalBoolean'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalBoolean')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_boolean'), + ); + } + return new ValueExpression(this.value.optionalBoolean); + } + + requiredInteger(): ValueExpression { + const path = this.path.member('required_integer', 'requiredInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_integer'), + ); + } + const error = integer32Error(this.value.requiredInteger, 'ScalarTypeProbe', 'required_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.requiredInteger); + } + + optionalInteger(): ValueExpression { + const path = this.path.member('optional_integer', 'optionalInteger'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalInteger')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_integer'), + ); + } + const error = integer32Error(this.value.optionalInteger, 'ScalarTypeProbe', 'optional_integer'); + if (error) return ValueExpression.invalid(error); + return new ValueExpression(this.value.optionalInteger); + } + + requiredLong(): ValueExpression { + const path = this.path.member('required_long', 'requiredLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_long'), + ); + } + return new ValueExpression(this.value.requiredLong); + } + + optionalLong(): ValueExpression { + const path = this.path.member('optional_long', 'optionalLong'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalLong')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_long'), + ); + } + return new ValueExpression(this.value.optionalLong); + } + + requiredDecimal(): ValueExpression { + const path = this.path.member('required_decimal', 'requiredDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_decimal'), + ); + } + return new ValueExpression(this.value.requiredDecimal); + } + + optionalDecimal(): ValueExpression { + const path = this.path.member('optional_decimal', 'optionalDecimal'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDecimal')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_decimal'), + ); + } + return new ValueExpression(this.value.optionalDecimal); + } + + requiredFloat(): ValueExpression { + const path = this.path.member('required_float', 'requiredFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_float'), + ); + } + return new ValueExpression(this.value.requiredFloat); + } + + optionalFloat(): ValueExpression { + const path = this.path.member('optional_float', 'optionalFloat'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalFloat')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_float'), + ); + } + return new ValueExpression(this.value.optionalFloat); + } + + requiredDouble(): ValueExpression { + const path = this.path.member('required_double', 'requiredDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_double'), + ); + } + return new ValueExpression(this.value.requiredDouble); + } + + optionalDouble(): ValueExpression { + const path = this.path.member('optional_double', 'optionalDouble'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDouble')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_double'), + ); + } + return new ValueExpression(this.value.optionalDouble); + } + + requiredDate(): ValueExpression { + const path = this.path.member('required_date', 'requiredDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_date'), + ); + } + return new ValueExpression(this.value.requiredDate); + } + + optionalDate(): ValueExpression { + const path = this.path.member('optional_date', 'optionalDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDate')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_date'), + ); + } + return new ValueExpression(this.value.optionalDate); + } + + requiredTime(): ValueExpression { + const path = this.path.member('required_time', 'requiredTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_time'), + ); + } + return new ValueExpression(this.value.requiredTime); + } + + optionalTime(): ValueExpression { + const path = this.path.member('optional_time', 'optionalTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_time'), + ); + } + return new ValueExpression(this.value.optionalTime); + } + + requiredDatetime(): ValueExpression { + const path = this.path.member('required_datetime', 'requiredDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('requiredDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'required_datetime'), + ); + } + return new ValueExpression(this.value.requiredDatetime); + } + + optionalDatetime(): ValueExpression { + const path = this.path.member('optional_datetime', 'optionalDatetime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('optionalDatetime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'optional_datetime'), + ); + } + return new ValueExpression(this.value.optionalDatetime); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + typePlatformId(): ValueExpression { + const path = this.path.member('type_platform', 'typePlatformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('typePlatform')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'type_platform'), + ); + } + const reference = this.value.typePlatform; + return new ValueExpression( + reference instanceof TypePlatform + ? reference.id : reference as string | number | undefined, + ); + } + + typePlatform(): TypePlatformExpression { + const path = this.path.member('type_platform', 'typePlatform'); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TypePlatformExpression(undefined, this.root, path); + if (!this.value.isLoaded('typePlatform')) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const relation = this.value.typePlatform; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof TypePlatform)) { + return new TypePlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'type_platform')); + } + const target = relation instanceof TypePlatform ? relation : undefined; + return new TypePlatformExpression(target, this.root, path); + } + +} + +export class TypePlatformListExpression { + constructor( + private readonly items: readonly TypePlatform[], + private readonly root = 'TypePlatform(null)', + private readonly path = ExpressionPath.root('E.entity()', 'snake_case'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'snake_case')): TypePlatformListExpression { + return new TypePlatformListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TypePlatformExpression { + return this.item(0, true); + } + + get(index: number): TypePlatformExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TypePlatformExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TypePlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TypePlatformExpression(undefined, this.root, itemPath) + : new TypePlatformExpression(this.items[index], this.root, itemPath); + } +} + +export class ScalarTypeProbeListExpression { + constructor( + private readonly items: readonly ScalarTypeProbe[], + private readonly root = 'ScalarTypeProbe(null)', + private readonly path = ExpressionPath.root('E.entity()', 'snake_case'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'snake_case')): ScalarTypeProbeListExpression { + return new ScalarTypeProbeListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): ScalarTypeProbeExpression { + return this.item(0, true); + } + + get(index: number): ScalarTypeProbeExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): ScalarTypeProbeExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new ScalarTypeProbeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new ScalarTypeProbeExpression(undefined, this.root, itemPath) + : new ScalarTypeProbeExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static typePlatform( + value: TypePlatform | null | undefined, + ): TypePlatformExpression { + return new TypePlatformExpression( + value, 'TypePlatform', ExpressionPath.root('E.typePlatform()', 'snake_case'), + ); + } + + static scalarTypeProbe( + value: ScalarTypeProbe | null | undefined, + ): ScalarTypeProbeExpression { + return new ScalarTypeProbeExpression( + value, 'ScalarTypeProbe', ExpressionPath.root('E.scalarTypeProbe()', 'snake_case'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/Q.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..5124d7963158b57d5460ab83052c5800791f46aa --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/Q.ts @@ -0,0 +1,20 @@ +import { TeaQLClient } from '../teaql-ts'; +import { TypePlatformRequest } from './requests/TypePlatformRequest'; +import { ScalarTypeProbeRequest } from './requests/ScalarTypeProbeRequest'; + +export class Q { + static typePlatforms(): TypePlatformRequest { + return new TypePlatformRequest(false); + } + + static typePlatformsWithMinimalFields(): TypePlatformRequest { + return new TypePlatformRequest(true); + } + static scalarTypeProbes(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(false); + } + + static scalarTypeProbesWithMinimalFields(): ScalarTypeProbeRequest { + return new ScalarTypeProbeRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/models/ScalarTypeProbe.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/models/ScalarTypeProbe.ts new file mode 100644 index 0000000000000000000000000000000000000000..90f93cf19ac480a4c610bf02ac8696c043c90b2d --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/models/ScalarTypeProbe.ts @@ -0,0 +1,576 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { TypePlatform } from './TypePlatform'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class ScalarTypeProbe { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("ScalarTypeProbe", + ["id", "type_platform", "required_string", "optional_string", "large_text", "required_boolean", "optional_boolean", "required_integer", "optional_integer", "required_long", "optional_long", "required_decimal", "optional_decimal", "required_float", "optional_float", "required_double", "optional_double", "required_date", "optional_date", "required_time", "optional_time", "required_datetime", "optional_datetime", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + typePlatform?: TypePlatform | string; + requiredString?: string; + optionalString?: string | null; + largeText?: string | null; + requiredBoolean?: boolean; + optionalBoolean?: boolean | null; + requiredInteger?: number; + optionalInteger?: number | null; + requiredLong?: Long; + optionalLong?: Long | null; + requiredDecimal?: Decimal; + optionalDecimal?: Decimal | null; + requiredFloat?: number; + optionalFloat?: number | null; + requiredDouble?: number; + optionalDouble?: number | null; + requiredDate?: string; + optionalDate?: string | null; + requiredTime?: LocalTime; + optionalTime?: LocalTime | null; + requiredDatetime?: string; + optionalDatetime?: string | null; + createTime?: string; + updateTime?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(init?.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --ScalarTypeProbe.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).typePlatform && typeof (init as any).typePlatform === "object") { + this.typePlatform = (init as any).typePlatform instanceof TypePlatform + ? (init as any).typePlatform + : TypePlatform.fromRecord((init as any).typePlatform); + this.markLoaded("typePlatform"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "ScalarTypeProbe", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): ScalarTypeProbe { + const entity = EntityCreation.hydrated(new ScalarTypeProbe(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.requiredInteger, "ScalarTypeProbe", "required_integer"); if (error) throw error; } + + { const error = integer32Error(this.optionalInteger, "ScalarTypeProbe", "optional_integer"); if (error) throw error; } + + + + + + + + + + + + + + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): ScalarTypeProbe { + return ScalarTypeProbe.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): ScalarTypeProbe { + return EntityCreation.bootstrap(context, "ScalarTypeProbe", id, + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "ScalarTypeProbe", + reserved => new ScalarTypeProbe({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "type_platform": "TypePlatform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + ScalarTypeProbe.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "ScalarTypeProbe", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(ScalarTypeProbe.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "typePlatform", canonical: "type_platform" }, { member: "requiredString", canonical: "required_string" }, { member: "optionalString", canonical: "optional_string" }, { member: "largeText", canonical: "large_text" }, { member: "requiredBoolean", canonical: "required_boolean" }, { member: "optionalBoolean", canonical: "optional_boolean" }, { member: "requiredInteger", canonical: "required_integer" }, { member: "optionalInteger", canonical: "optional_integer" }, { member: "requiredLong", canonical: "required_long" }, { member: "optionalLong", canonical: "optional_long" }, { member: "requiredDecimal", canonical: "required_decimal" }, { member: "optionalDecimal", canonical: "optional_decimal" }, { member: "requiredFloat", canonical: "required_float" }, { member: "optionalFloat", canonical: "optional_float" }, { member: "requiredDouble", canonical: "required_double" }, { member: "optionalDouble", canonical: "optional_double" }, { member: "requiredDate", canonical: "required_date" }, { member: "optionalDate", canonical: "optional_date" }, { member: "requiredTime", canonical: "required_time" }, { member: "optionalTime", canonical: "optional_time" }, { member: "requiredDatetime", canonical: "required_datetime" }, { member: "optionalDatetime", canonical: "optional_datetime" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "ScalarTypeProbe", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "ScalarTypeProbe", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "ScalarTypeProbe", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "type_platform": this.typePlatform, + "required_string": this.requiredString, + "optional_string": this.optionalString, + "large_text": this.largeText, + "required_boolean": this.requiredBoolean, + "optional_boolean": this.optionalBoolean, + "required_integer": this.requiredInteger, + "optional_integer": this.optionalInteger, + "required_long": this.requiredLong, + "optional_long": this.optionalLong, + "required_decimal": this.requiredDecimal, + "optional_decimal": this.optionalDecimal, + "required_float": this.requiredFloat, + "optional_float": this.optionalFloat, + "required_double": this.requiredDouble, + "optional_double": this.optionalDouble, + "required_date": this.requiredDate, + "optional_date": this.optionalDate, + "required_time": this.requiredTime, + "optional_time": this.optionalTime, + "required_datetime": this.requiredDatetime, + "optional_datetime": this.optionalDatetime, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateRequiredString(value: string): this { + this.requiredString = value; + this.markLoaded("requiredString"); + (this as any)._root.set(this.teaqlEntityKey(), "required_string", value); + return this; + } + + updateOptionalString(value: string | null): this { + this.optionalString = value; + this.markLoaded("optionalString"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_string", value); + return this; + } + + updateLargeText(value: string | null): this { + this.largeText = value; + this.markLoaded("largeText"); + (this as any)._root.set(this.teaqlEntityKey(), "large_text", value); + return this; + } + + updateRequiredBoolean(value: boolean): this { + this.requiredBoolean = value; + this.markLoaded("requiredBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "required_boolean", value); + return this; + } + + updateOptionalBoolean(value: boolean | null): this { + this.optionalBoolean = value; + this.markLoaded("optionalBoolean"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_boolean", value); + return this; + } + + updateRequiredInteger(value: number): this { + this.requiredInteger = value; + this.markLoaded("requiredInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "required_integer", value); + return this; + } + + updateOptionalInteger(value: number | null): this { + this.optionalInteger = value; + this.markLoaded("optionalInteger"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_integer", value); + return this; + } + + updateRequiredLong(value: Long): this { + if (value != null) value = long(value); + this.requiredLong = value; + this.markLoaded("requiredLong"); + (this as any)._root.set(this.teaqlEntityKey(), "required_long", value); + return this; + } + + updateOptionalLong(value: Long | null): this { + if (value != null) value = long(value); + this.optionalLong = value; + this.markLoaded("optionalLong"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_long", value); + return this; + } + + updateRequiredDecimal(value: Decimal): this { + if (value != null) value = decimal(value); + this.requiredDecimal = value; + this.markLoaded("requiredDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "required_decimal", value); + return this; + } + + updateOptionalDecimal(value: Decimal | null): this { + if (value != null) value = decimal(value); + this.optionalDecimal = value; + this.markLoaded("optionalDecimal"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_decimal", value); + return this; + } + + updateRequiredFloat(value: number): this { + this.requiredFloat = value; + this.markLoaded("requiredFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "required_float", value); + return this; + } + + updateOptionalFloat(value: number | null): this { + this.optionalFloat = value; + this.markLoaded("optionalFloat"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_float", value); + return this; + } + + updateRequiredDouble(value: number): this { + this.requiredDouble = value; + this.markLoaded("requiredDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "required_double", value); + return this; + } + + updateOptionalDouble(value: number | null): this { + this.optionalDouble = value; + this.markLoaded("optionalDouble"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_double", value); + return this; + } + + updateRequiredDate(value: string): this { + this.requiredDate = value; + this.markLoaded("requiredDate"); + (this as any)._root.set(this.teaqlEntityKey(), "required_date", value); + return this; + } + + updateOptionalDate(value: string | null): this { + this.optionalDate = value; + this.markLoaded("optionalDate"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_date", value); + return this; + } + + updateRequiredTime(value: LocalTime): this { + if (value != null) value = localTime(value); + this.requiredTime = value; + this.markLoaded("requiredTime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_time", value); + return this; + } + + updateOptionalTime(value: LocalTime | null): this { + if (value != null) value = localTime(value); + this.optionalTime = value; + this.markLoaded("optionalTime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_time", value); + return this; + } + + updateRequiredDatetime(value: string): this { + this.requiredDatetime = value; + this.markLoaded("requiredDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "required_datetime", value); + return this; + } + + updateOptionalDatetime(value: string | null): this { + this.optionalDatetime = value; + this.markLoaded("optionalDatetime"); + (this as any)._root.set(this.teaqlEntityKey(), "optional_datetime", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updateTypePlatform(value: any): this { + this.typePlatform = value?.id ?? value; + this.markLoaded("typePlatform"); + (this as any)._root.set(this.teaqlEntityKey(), "type_platform", this.typePlatform); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/models/TypePlatform.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/models/TypePlatform.ts new file mode 100644 index 0000000000000000000000000000000000000000..00fc9ee5d876db31834d06abe61c11f063127e61 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/models/TypePlatform.ts @@ -0,0 +1,403 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { ScalarTypeProbe } from './ScalarTypeProbe'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class TypePlatform { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("TypePlatform", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --TypePlatform.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_scalarTypeProbeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["scalarTypeProbeList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).scalarTypeProbeList)) { + const selected = (init as any).scalarTypeProbeList; + (this as any)._scalarTypeProbeList = new SmartList(selected.map( + (child: unknown) => child instanceof ScalarTypeProbe + ? child + : ScalarTypeProbe.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("scalarTypeProbeList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "TypePlatform", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._scalarTypeProbeList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): TypePlatform { + const entity = EntityCreation.hydrated(new TypePlatform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("scalarTypeProbeList")) result["scalarTypeProbeList"] = (this as any)._scalarTypeProbeList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): TypePlatform { + return TypePlatform.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): TypePlatform { + return EntityCreation.bootstrap(context, "TypePlatform", id, + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "TypePlatform", + reserved => new TypePlatform({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._scalarTypeProbeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._scalarTypeProbeList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "scalar_type_probe_list": graph.sourceMembers((this as any)._scalarTypeProbeList) + })); + for (const child of (this as any)._scalarTypeProbeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + TypePlatform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "TypePlatform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(TypePlatform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "TypePlatform", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "TypePlatform", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "TypePlatform", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._scalarTypeProbeList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.typePlatform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("typePlatform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateTypePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("scalar_type_probe_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + scalarTypeProbeList(): SmartList { + return (this as any)._scalarTypeProbeList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/requests/ScalarTypeProbeRequest.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/requests/ScalarTypeProbeRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..3aab674d36faae5691bcfb6d8a395878245cbaa4 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/requests/ScalarTypeProbeRequest.ts @@ -0,0 +1,3073 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { ScalarTypeProbe } from '../models/ScalarTypeProbe'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class ScalarTypeProbeRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("ScalarTypeProbe"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "ScalarTypeProbe" { + return "ScalarTypeProbe"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableScalarTypeProbeRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableScalarTypeProbeRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "typePlatform", "requiredString", "optionalString", "largeText", "requiredBoolean", "optionalBoolean", "requiredInteger", "optionalInteger", "requiredLong", "optionalLong", "requiredDecimal", "optionalDecimal", "requiredFloat", "optionalFloat", "requiredDouble", "optionalDouble", "requiredDate", "optionalDate", "requiredTime", "optionalTime", "requiredDatetime", "optionalDatetime", "createTime", "updateTime", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + + selectRequiredString(): this { + this.query.select(["requiredString"]); + return this; + } + + selectOptionalString(): this { + this.query.select(["optionalString"]); + return this; + } + + selectLargeText(): this { + this.query.select(["largeText"]); + return this; + } + + selectRequiredBoolean(): this { + this.query.select(["requiredBoolean"]); + return this; + } + + selectOptionalBoolean(): this { + this.query.select(["optionalBoolean"]); + return this; + } + + selectRequiredInteger(): this { + this.query.select(["requiredInteger"]); + return this; + } + + selectOptionalInteger(): this { + this.query.select(["optionalInteger"]); + return this; + } + + selectRequiredLong(): this { + this.query.select(["requiredLong"]); + return this; + } + + selectOptionalLong(): this { + this.query.select(["optionalLong"]); + return this; + } + + selectRequiredDecimal(): this { + this.query.select(["requiredDecimal"]); + return this; + } + + selectOptionalDecimal(): this { + this.query.select(["optionalDecimal"]); + return this; + } + + selectRequiredFloat(): this { + this.query.select(["requiredFloat"]); + return this; + } + + selectOptionalFloat(): this { + this.query.select(["optionalFloat"]); + return this; + } + + selectRequiredDouble(): this { + this.query.select(["requiredDouble"]); + return this; + } + + selectOptionalDouble(): this { + this.query.select(["optionalDouble"]); + return this; + } + + selectRequiredDate(): this { + this.query.select(["requiredDate"]); + return this; + } + + selectOptionalDate(): this { + this.query.select(["optionalDate"]); + return this; + } + + selectRequiredTime(): this { + this.query.select(["requiredTime"]); + return this; + } + + selectOptionalTime(): this { + this.query.select(["optionalTime"]); + return this; + } + + selectRequiredDatetime(): this { + this.query.select(["requiredDatetime"]); + return this; + } + + selectOptionalDatetime(): this { + this.query.select(["optionalDatetime"]); + return this; + } + + selectCreateTime(): this { + this.query.select(["createTime"]); + return this; + } + + selectUpdateTime(): this { + this.query.select(["updateTime"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + selectTypePlatformWith(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.query.select(["typePlatform"]); + this.query.relationQuery( + "typePlatform", request.toQuery(), "typePlatform", "id", false, + { kind: "relation-select", method: "selectTypePlatformWith", relation: "typePlatform" }); + return this; + } + + withTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$inSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + withoutTypePlatformMatching(request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }): this { + this.filters.push({ + "typePlatform": { + "$notInSubquery": { query: request.toQuery(), field: "id" }, + }, + }); + return this; + } + + + + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + filterByTypePlatform(val: any): this { + this.filters.push({ "typePlatform": { "$eq": val } }); + return this; + } + + filterByTypePlatformIn(...vals: any[]): this { + this.filters.push({ "typePlatform": { "$in": vals } }); + return this; + } + + withTypePlatformIsKnown(): this { + this.filters.push({ "typePlatform": { "$isNull": false } }); + return this; + } + + withTypePlatformIsUnknown(): this { + this.filters.push({ "typePlatform": { "$isNull": true } }); + return this; + } + + withRequiredStringContaining(val: string): this { + this.filters.push({ "requiredString": { "$contains": val } }); + return this; + } + + withRequiredStringIs(val: string): this { + this.filters.push({ "requiredString": { "$eq": val } }); + return this; + } + + withRequiredStringIsNot(val: string): this { + this.filters.push({ "requiredString": { "$ne": val } }); + return this; + } + + withRequiredStringIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$in": vals } }); + return this; + } + + withRequiredStringNotIn(...vals: string[]): this { + this.filters.push({ "requiredString": { "$notIn": vals } }); + return this; + } + + withRequiredStringGreaterThan(val: string): this { + this.filters.push({ "requiredString": { "$gt": val } }); + return this; + } + + withRequiredStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$gte": val } }); + return this; + } + + withRequiredStringLessThan(val: string): this { + this.filters.push({ "requiredString": { "$lt": val } }); + return this; + } + + withRequiredStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredString": { "$lte": val } }); + return this; + } + + withRequiredStringBetween(lower: string, upper: string): this { + this.filters.push({ "requiredString": { "$between": [lower, upper] } }); + return this; + } + + withRequiredStringIsKnown(): this { + this.filters.push({ "requiredString": { "$isNull": false } }); + return this; + } + + withRequiredStringIsUnknown(): this { + this.filters.push({ "requiredString": { "$isNull": true } }); + return this; + } + withRequiredStringNotContaining(val: string): this { + this.filters.push({ "requiredString": { "$notContains": val } }); + return this; + } + + withRequiredStringStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$startsWith": val } }); + return this; + } + + withRequiredStringNotStartingWith(val: string): this { + this.filters.push({ "requiredString": { "$notStartsWith": val } }); + return this; + } + + withRequiredStringEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$endsWith": val } }); + return this; + } + + withRequiredStringNotEndingWith(val: string): this { + this.filters.push({ "requiredString": { "$notEndsWith": val } }); + return this; + } + + withRequiredStringSoundingLike(val: string): this { + this.filters.push({ "requiredString": { "$soundLike": val } }); + return this; + } + + withOptionalStringContaining(val: string): this { + this.filters.push({ "optionalString": { "$contains": val } }); + return this; + } + + withOptionalStringIs(val: string): this { + this.filters.push({ "optionalString": { "$eq": val } }); + return this; + } + + withOptionalStringIsNot(val: string): this { + this.filters.push({ "optionalString": { "$ne": val } }); + return this; + } + + withOptionalStringIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$in": vals } }); + return this; + } + + withOptionalStringNotIn(...vals: string[]): this { + this.filters.push({ "optionalString": { "$notIn": vals } }); + return this; + } + + withOptionalStringGreaterThan(val: string): this { + this.filters.push({ "optionalString": { "$gt": val } }); + return this; + } + + withOptionalStringGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$gte": val } }); + return this; + } + + withOptionalStringLessThan(val: string): this { + this.filters.push({ "optionalString": { "$lt": val } }); + return this; + } + + withOptionalStringLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalString": { "$lte": val } }); + return this; + } + + withOptionalStringBetween(lower: string, upper: string): this { + this.filters.push({ "optionalString": { "$between": [lower, upper] } }); + return this; + } + + withOptionalStringIsKnown(): this { + this.filters.push({ "optionalString": { "$isNull": false } }); + return this; + } + + withOptionalStringIsUnknown(): this { + this.filters.push({ "optionalString": { "$isNull": true } }); + return this; + } + withOptionalStringNotContaining(val: string): this { + this.filters.push({ "optionalString": { "$notContains": val } }); + return this; + } + + withOptionalStringStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$startsWith": val } }); + return this; + } + + withOptionalStringNotStartingWith(val: string): this { + this.filters.push({ "optionalString": { "$notStartsWith": val } }); + return this; + } + + withOptionalStringEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$endsWith": val } }); + return this; + } + + withOptionalStringNotEndingWith(val: string): this { + this.filters.push({ "optionalString": { "$notEndsWith": val } }); + return this; + } + + withOptionalStringSoundingLike(val: string): this { + this.filters.push({ "optionalString": { "$soundLike": val } }); + return this; + } + + withLargeTextContaining(val: string): this { + this.filters.push({ "largeText": { "$contains": val } }); + return this; + } + + withLargeTextIs(val: string): this { + this.filters.push({ "largeText": { "$eq": val } }); + return this; + } + + withLargeTextIsNot(val: string): this { + this.filters.push({ "largeText": { "$ne": val } }); + return this; + } + + withLargeTextIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$in": vals } }); + return this; + } + + withLargeTextNotIn(...vals: string[]): this { + this.filters.push({ "largeText": { "$notIn": vals } }); + return this; + } + + withLargeTextGreaterThan(val: string): this { + this.filters.push({ "largeText": { "$gt": val } }); + return this; + } + + withLargeTextGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$gte": val } }); + return this; + } + + withLargeTextLessThan(val: string): this { + this.filters.push({ "largeText": { "$lt": val } }); + return this; + } + + withLargeTextLessThanOrEqualTo(val: string): this { + this.filters.push({ "largeText": { "$lte": val } }); + return this; + } + + withLargeTextBetween(lower: string, upper: string): this { + this.filters.push({ "largeText": { "$between": [lower, upper] } }); + return this; + } + + withLargeTextIsKnown(): this { + this.filters.push({ "largeText": { "$isNull": false } }); + return this; + } + + withLargeTextIsUnknown(): this { + this.filters.push({ "largeText": { "$isNull": true } }); + return this; + } + withLargeTextNotContaining(val: string): this { + this.filters.push({ "largeText": { "$notContains": val } }); + return this; + } + + withLargeTextStartingWith(val: string): this { + this.filters.push({ "largeText": { "$startsWith": val } }); + return this; + } + + withLargeTextNotStartingWith(val: string): this { + this.filters.push({ "largeText": { "$notStartsWith": val } }); + return this; + } + + withLargeTextEndingWith(val: string): this { + this.filters.push({ "largeText": { "$endsWith": val } }); + return this; + } + + withLargeTextNotEndingWith(val: string): this { + this.filters.push({ "largeText": { "$notEndsWith": val } }); + return this; + } + + withLargeTextSoundingLike(val: string): this { + this.filters.push({ "largeText": { "$soundLike": val } }); + return this; + } + + whichAreRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": true } }); + return this; + } + + whichAreNotRequiredBoolean(): this { + this.filters.push({ "requiredBoolean": { "$eq": false } }); + return this; + } + withRequiredBooleanIsNot(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$ne": val } }); + return this; + } + + withRequiredBooleanIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$in": vals } }); + return this; + } + + withRequiredBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "requiredBoolean": { "$notIn": vals } }); + return this; + } + + withRequiredBooleanGreaterThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gt": val } }); + return this; + } + + withRequiredBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$gte": val } }); + return this; + } + + withRequiredBooleanLessThan(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lt": val } }); + return this; + } + + withRequiredBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "requiredBoolean": { "$lte": val } }); + return this; + } + + withRequiredBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "requiredBoolean": { "$between": [lower, upper] } }); + return this; + } + + withRequiredBooleanIsKnown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": false } }); + return this; + } + + withRequiredBooleanIsUnknown(): this { + this.filters.push({ "requiredBoolean": { "$isNull": true } }); + return this; + } + + whichAreOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": true } }); + return this; + } + + whichAreNotOptionalBoolean(): this { + this.filters.push({ "optionalBoolean": { "$eq": false } }); + return this; + } + withOptionalBooleanIsNot(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$ne": val } }); + return this; + } + + withOptionalBooleanIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$in": vals } }); + return this; + } + + withOptionalBooleanNotIn(...vals: boolean[]): this { + this.filters.push({ "optionalBoolean": { "$notIn": vals } }); + return this; + } + + withOptionalBooleanGreaterThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gt": val } }); + return this; + } + + withOptionalBooleanGreaterThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$gte": val } }); + return this; + } + + withOptionalBooleanLessThan(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lt": val } }); + return this; + } + + withOptionalBooleanLessThanOrEqualTo(val: boolean): this { + this.filters.push({ "optionalBoolean": { "$lte": val } }); + return this; + } + + withOptionalBooleanBetween(lower: boolean, upper: boolean): this { + this.filters.push({ "optionalBoolean": { "$between": [lower, upper] } }); + return this; + } + + withOptionalBooleanIsKnown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": false } }); + return this; + } + + withOptionalBooleanIsUnknown(): this { + this.filters.push({ "optionalBoolean": { "$isNull": true } }); + return this; + } + + withRequiredIntegerIs(val: number): this { + this.filters.push({ "requiredInteger": { "$eq": val } }); + return this; + } + + withRequiredIntegerIsNot(val: number): this { + this.filters.push({ "requiredInteger": { "$ne": val } }); + return this; + } + + withRequiredIntegerIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$in": vals } }); + return this; + } + + withRequiredIntegerNotIn(...vals: number[]): this { + this.filters.push({ "requiredInteger": { "$notIn": vals } }); + return this; + } + + withRequiredIntegerGreaterThan(val: number): this { + this.filters.push({ "requiredInteger": { "$gt": val } }); + return this; + } + + withRequiredIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$gte": val } }); + return this; + } + + withRequiredIntegerLessThan(val: number): this { + this.filters.push({ "requiredInteger": { "$lt": val } }); + return this; + } + + withRequiredIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredInteger": { "$lte": val } }); + return this; + } + + withRequiredIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "requiredInteger": { "$between": [lower, upper] } }); + return this; + } + + withRequiredIntegerIsKnown(): this { + this.filters.push({ "requiredInteger": { "$isNull": false } }); + return this; + } + + withRequiredIntegerIsUnknown(): this { + this.filters.push({ "requiredInteger": { "$isNull": true } }); + return this; + } + + withOptionalIntegerIs(val: number): this { + this.filters.push({ "optionalInteger": { "$eq": val } }); + return this; + } + + withOptionalIntegerIsNot(val: number): this { + this.filters.push({ "optionalInteger": { "$ne": val } }); + return this; + } + + withOptionalIntegerIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$in": vals } }); + return this; + } + + withOptionalIntegerNotIn(...vals: number[]): this { + this.filters.push({ "optionalInteger": { "$notIn": vals } }); + return this; + } + + withOptionalIntegerGreaterThan(val: number): this { + this.filters.push({ "optionalInteger": { "$gt": val } }); + return this; + } + + withOptionalIntegerGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$gte": val } }); + return this; + } + + withOptionalIntegerLessThan(val: number): this { + this.filters.push({ "optionalInteger": { "$lt": val } }); + return this; + } + + withOptionalIntegerLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalInteger": { "$lte": val } }); + return this; + } + + withOptionalIntegerBetween(lower: number, upper: number): this { + this.filters.push({ "optionalInteger": { "$between": [lower, upper] } }); + return this; + } + + withOptionalIntegerIsKnown(): this { + this.filters.push({ "optionalInteger": { "$isNull": false } }); + return this; + } + + withOptionalIntegerIsUnknown(): this { + this.filters.push({ "optionalInteger": { "$isNull": true } }); + return this; + } + + withRequiredLongIs(val: Long): this { + this.filters.push({ "requiredLong": { "$eq": val } }); + return this; + } + + withRequiredLongIsNot(val: Long): this { + this.filters.push({ "requiredLong": { "$ne": val } }); + return this; + } + + withRequiredLongIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$in": vals } }); + return this; + } + + withRequiredLongNotIn(...vals: Long[]): this { + this.filters.push({ "requiredLong": { "$notIn": vals } }); + return this; + } + + withRequiredLongGreaterThan(val: Long): this { + this.filters.push({ "requiredLong": { "$gt": val } }); + return this; + } + + withRequiredLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$gte": val } }); + return this; + } + + withRequiredLongLessThan(val: Long): this { + this.filters.push({ "requiredLong": { "$lt": val } }); + return this; + } + + withRequiredLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "requiredLong": { "$lte": val } }); + return this; + } + + withRequiredLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "requiredLong": { "$between": [lower, upper] } }); + return this; + } + + withRequiredLongIsKnown(): this { + this.filters.push({ "requiredLong": { "$isNull": false } }); + return this; + } + + withRequiredLongIsUnknown(): this { + this.filters.push({ "requiredLong": { "$isNull": true } }); + return this; + } + + withOptionalLongIs(val: Long): this { + this.filters.push({ "optionalLong": { "$eq": val } }); + return this; + } + + withOptionalLongIsNot(val: Long): this { + this.filters.push({ "optionalLong": { "$ne": val } }); + return this; + } + + withOptionalLongIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$in": vals } }); + return this; + } + + withOptionalLongNotIn(...vals: Long[]): this { + this.filters.push({ "optionalLong": { "$notIn": vals } }); + return this; + } + + withOptionalLongGreaterThan(val: Long): this { + this.filters.push({ "optionalLong": { "$gt": val } }); + return this; + } + + withOptionalLongGreaterThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$gte": val } }); + return this; + } + + withOptionalLongLessThan(val: Long): this { + this.filters.push({ "optionalLong": { "$lt": val } }); + return this; + } + + withOptionalLongLessThanOrEqualTo(val: Long): this { + this.filters.push({ "optionalLong": { "$lte": val } }); + return this; + } + + withOptionalLongBetween(lower: Long, upper: Long): this { + this.filters.push({ "optionalLong": { "$between": [lower, upper] } }); + return this; + } + + withOptionalLongIsKnown(): this { + this.filters.push({ "optionalLong": { "$isNull": false } }); + return this; + } + + withOptionalLongIsUnknown(): this { + this.filters.push({ "optionalLong": { "$isNull": true } }); + return this; + } + + withRequiredDecimalIs(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$eq": val } }); + return this; + } + + withRequiredDecimalIsNot(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$ne": val } }); + return this; + } + + withRequiredDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$in": vals } }); + return this; + } + + withRequiredDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "requiredDecimal": { "$notIn": vals } }); + return this; + } + + withRequiredDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gt": val } }); + return this; + } + + withRequiredDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$gte": val } }); + return this; + } + + withRequiredDecimalLessThan(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lt": val } }); + return this; + } + + withRequiredDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "requiredDecimal": { "$lte": val } }); + return this; + } + + withRequiredDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "requiredDecimal": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDecimalIsKnown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": false } }); + return this; + } + + withRequiredDecimalIsUnknown(): this { + this.filters.push({ "requiredDecimal": { "$isNull": true } }); + return this; + } + + withOptionalDecimalIs(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$eq": val } }); + return this; + } + + withOptionalDecimalIsNot(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$ne": val } }); + return this; + } + + withOptionalDecimalIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$in": vals } }); + return this; + } + + withOptionalDecimalNotIn(...vals: Decimal[]): this { + this.filters.push({ "optionalDecimal": { "$notIn": vals } }); + return this; + } + + withOptionalDecimalGreaterThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gt": val } }); + return this; + } + + withOptionalDecimalGreaterThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$gte": val } }); + return this; + } + + withOptionalDecimalLessThan(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lt": val } }); + return this; + } + + withOptionalDecimalLessThanOrEqualTo(val: Decimal): this { + this.filters.push({ "optionalDecimal": { "$lte": val } }); + return this; + } + + withOptionalDecimalBetween(lower: Decimal, upper: Decimal): this { + this.filters.push({ "optionalDecimal": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDecimalIsKnown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": false } }); + return this; + } + + withOptionalDecimalIsUnknown(): this { + this.filters.push({ "optionalDecimal": { "$isNull": true } }); + return this; + } + + withRequiredFloatIs(val: number): this { + this.filters.push({ "requiredFloat": { "$eq": val } }); + return this; + } + + withRequiredFloatIsNot(val: number): this { + this.filters.push({ "requiredFloat": { "$ne": val } }); + return this; + } + + withRequiredFloatIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$in": vals } }); + return this; + } + + withRequiredFloatNotIn(...vals: number[]): this { + this.filters.push({ "requiredFloat": { "$notIn": vals } }); + return this; + } + + withRequiredFloatGreaterThan(val: number): this { + this.filters.push({ "requiredFloat": { "$gt": val } }); + return this; + } + + withRequiredFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$gte": val } }); + return this; + } + + withRequiredFloatLessThan(val: number): this { + this.filters.push({ "requiredFloat": { "$lt": val } }); + return this; + } + + withRequiredFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredFloat": { "$lte": val } }); + return this; + } + + withRequiredFloatBetween(lower: number, upper: number): this { + this.filters.push({ "requiredFloat": { "$between": [lower, upper] } }); + return this; + } + + withRequiredFloatIsKnown(): this { + this.filters.push({ "requiredFloat": { "$isNull": false } }); + return this; + } + + withRequiredFloatIsUnknown(): this { + this.filters.push({ "requiredFloat": { "$isNull": true } }); + return this; + } + + withOptionalFloatIs(val: number): this { + this.filters.push({ "optionalFloat": { "$eq": val } }); + return this; + } + + withOptionalFloatIsNot(val: number): this { + this.filters.push({ "optionalFloat": { "$ne": val } }); + return this; + } + + withOptionalFloatIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$in": vals } }); + return this; + } + + withOptionalFloatNotIn(...vals: number[]): this { + this.filters.push({ "optionalFloat": { "$notIn": vals } }); + return this; + } + + withOptionalFloatGreaterThan(val: number): this { + this.filters.push({ "optionalFloat": { "$gt": val } }); + return this; + } + + withOptionalFloatGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$gte": val } }); + return this; + } + + withOptionalFloatLessThan(val: number): this { + this.filters.push({ "optionalFloat": { "$lt": val } }); + return this; + } + + withOptionalFloatLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalFloat": { "$lte": val } }); + return this; + } + + withOptionalFloatBetween(lower: number, upper: number): this { + this.filters.push({ "optionalFloat": { "$between": [lower, upper] } }); + return this; + } + + withOptionalFloatIsKnown(): this { + this.filters.push({ "optionalFloat": { "$isNull": false } }); + return this; + } + + withOptionalFloatIsUnknown(): this { + this.filters.push({ "optionalFloat": { "$isNull": true } }); + return this; + } + + withRequiredDoubleIs(val: number): this { + this.filters.push({ "requiredDouble": { "$eq": val } }); + return this; + } + + withRequiredDoubleIsNot(val: number): this { + this.filters.push({ "requiredDouble": { "$ne": val } }); + return this; + } + + withRequiredDoubleIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$in": vals } }); + return this; + } + + withRequiredDoubleNotIn(...vals: number[]): this { + this.filters.push({ "requiredDouble": { "$notIn": vals } }); + return this; + } + + withRequiredDoubleGreaterThan(val: number): this { + this.filters.push({ "requiredDouble": { "$gt": val } }); + return this; + } + + withRequiredDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$gte": val } }); + return this; + } + + withRequiredDoubleLessThan(val: number): this { + this.filters.push({ "requiredDouble": { "$lt": val } }); + return this; + } + + withRequiredDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "requiredDouble": { "$lte": val } }); + return this; + } + + withRequiredDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "requiredDouble": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDoubleIsKnown(): this { + this.filters.push({ "requiredDouble": { "$isNull": false } }); + return this; + } + + withRequiredDoubleIsUnknown(): this { + this.filters.push({ "requiredDouble": { "$isNull": true } }); + return this; + } + + withOptionalDoubleIs(val: number): this { + this.filters.push({ "optionalDouble": { "$eq": val } }); + return this; + } + + withOptionalDoubleIsNot(val: number): this { + this.filters.push({ "optionalDouble": { "$ne": val } }); + return this; + } + + withOptionalDoubleIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$in": vals } }); + return this; + } + + withOptionalDoubleNotIn(...vals: number[]): this { + this.filters.push({ "optionalDouble": { "$notIn": vals } }); + return this; + } + + withOptionalDoubleGreaterThan(val: number): this { + this.filters.push({ "optionalDouble": { "$gt": val } }); + return this; + } + + withOptionalDoubleGreaterThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$gte": val } }); + return this; + } + + withOptionalDoubleLessThan(val: number): this { + this.filters.push({ "optionalDouble": { "$lt": val } }); + return this; + } + + withOptionalDoubleLessThanOrEqualTo(val: number): this { + this.filters.push({ "optionalDouble": { "$lte": val } }); + return this; + } + + withOptionalDoubleBetween(lower: number, upper: number): this { + this.filters.push({ "optionalDouble": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDoubleIsKnown(): this { + this.filters.push({ "optionalDouble": { "$isNull": false } }); + return this; + } + + withOptionalDoubleIsUnknown(): this { + this.filters.push({ "optionalDouble": { "$isNull": true } }); + return this; + } + + withRequiredDateIs(val: string): this { + this.filters.push({ "requiredDate": { "$eq": val } }); + return this; + } + + withRequiredDateIsNot(val: string): this { + this.filters.push({ "requiredDate": { "$ne": val } }); + return this; + } + + withRequiredDateIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$in": vals } }); + return this; + } + + withRequiredDateNotIn(...vals: string[]): this { + this.filters.push({ "requiredDate": { "$notIn": vals } }); + return this; + } + + withRequiredDateGreaterThan(val: string): this { + this.filters.push({ "requiredDate": { "$gt": val } }); + return this; + } + + withRequiredDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$gte": val } }); + return this; + } + + withRequiredDateLessThan(val: string): this { + this.filters.push({ "requiredDate": { "$lt": val } }); + return this; + } + + withRequiredDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDate": { "$lte": val } }); + return this; + } + + withRequiredDateBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDate": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDateIsKnown(): this { + this.filters.push({ "requiredDate": { "$isNull": false } }); + return this; + } + + withRequiredDateIsUnknown(): this { + this.filters.push({ "requiredDate": { "$isNull": true } }); + return this; + } + + withOptionalDateIs(val: string): this { + this.filters.push({ "optionalDate": { "$eq": val } }); + return this; + } + + withOptionalDateIsNot(val: string): this { + this.filters.push({ "optionalDate": { "$ne": val } }); + return this; + } + + withOptionalDateIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$in": vals } }); + return this; + } + + withOptionalDateNotIn(...vals: string[]): this { + this.filters.push({ "optionalDate": { "$notIn": vals } }); + return this; + } + + withOptionalDateGreaterThan(val: string): this { + this.filters.push({ "optionalDate": { "$gt": val } }); + return this; + } + + withOptionalDateGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$gte": val } }); + return this; + } + + withOptionalDateLessThan(val: string): this { + this.filters.push({ "optionalDate": { "$lt": val } }); + return this; + } + + withOptionalDateLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDate": { "$lte": val } }); + return this; + } + + withOptionalDateBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDate": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDateIsKnown(): this { + this.filters.push({ "optionalDate": { "$isNull": false } }); + return this; + } + + withOptionalDateIsUnknown(): this { + this.filters.push({ "optionalDate": { "$isNull": true } }); + return this; + } + + withRequiredTimeIs(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$eq": val } }); + return this; + } + + withRequiredTimeIsNot(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$ne": val } }); + return this; + } + + withRequiredTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$in": vals } }); + return this; + } + + withRequiredTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "requiredTime": { "$notIn": vals } }); + return this; + } + + withRequiredTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gt": val } }); + return this; + } + + withRequiredTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$gte": val } }); + return this; + } + + withRequiredTimeLessThan(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lt": val } }); + return this; + } + + withRequiredTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "requiredTime": { "$lte": val } }); + return this; + } + + withRequiredTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "requiredTime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredTimeIsKnown(): this { + this.filters.push({ "requiredTime": { "$isNull": false } }); + return this; + } + + withRequiredTimeIsUnknown(): this { + this.filters.push({ "requiredTime": { "$isNull": true } }); + return this; + } + + withOptionalTimeIs(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$eq": val } }); + return this; + } + + withOptionalTimeIsNot(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$ne": val } }); + return this; + } + + withOptionalTimeIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$in": vals } }); + return this; + } + + withOptionalTimeNotIn(...vals: LocalTime[]): this { + this.filters.push({ "optionalTime": { "$notIn": vals } }); + return this; + } + + withOptionalTimeGreaterThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gt": val } }); + return this; + } + + withOptionalTimeGreaterThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$gte": val } }); + return this; + } + + withOptionalTimeLessThan(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lt": val } }); + return this; + } + + withOptionalTimeLessThanOrEqualTo(val: LocalTime): this { + this.filters.push({ "optionalTime": { "$lte": val } }); + return this; + } + + withOptionalTimeBetween(lower: LocalTime, upper: LocalTime): this { + this.filters.push({ "optionalTime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalTimeIsKnown(): this { + this.filters.push({ "optionalTime": { "$isNull": false } }); + return this; + } + + withOptionalTimeIsUnknown(): this { + this.filters.push({ "optionalTime": { "$isNull": true } }); + return this; + } + + withRequiredDatetimeIs(val: string): this { + this.filters.push({ "requiredDatetime": { "$eq": val } }); + return this; + } + + withRequiredDatetimeIsNot(val: string): this { + this.filters.push({ "requiredDatetime": { "$ne": val } }); + return this; + } + + withRequiredDatetimeIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$in": vals } }); + return this; + } + + withRequiredDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "requiredDatetime": { "$notIn": vals } }); + return this; + } + + withRequiredDatetimeGreaterThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$gt": val } }); + return this; + } + + withRequiredDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$gte": val } }); + return this; + } + + withRequiredDatetimeLessThan(val: string): this { + this.filters.push({ "requiredDatetime": { "$lt": val } }); + return this; + } + + withRequiredDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "requiredDatetime": { "$lte": val } }); + return this; + } + + withRequiredDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "requiredDatetime": { "$between": [lower, upper] } }); + return this; + } + + withRequiredDatetimeIsKnown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": false } }); + return this; + } + + withRequiredDatetimeIsUnknown(): this { + this.filters.push({ "requiredDatetime": { "$isNull": true } }); + return this; + } + + withOptionalDatetimeIs(val: string): this { + this.filters.push({ "optionalDatetime": { "$eq": val } }); + return this; + } + + withOptionalDatetimeIsNot(val: string): this { + this.filters.push({ "optionalDatetime": { "$ne": val } }); + return this; + } + + withOptionalDatetimeIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$in": vals } }); + return this; + } + + withOptionalDatetimeNotIn(...vals: string[]): this { + this.filters.push({ "optionalDatetime": { "$notIn": vals } }); + return this; + } + + withOptionalDatetimeGreaterThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$gt": val } }); + return this; + } + + withOptionalDatetimeGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$gte": val } }); + return this; + } + + withOptionalDatetimeLessThan(val: string): this { + this.filters.push({ "optionalDatetime": { "$lt": val } }); + return this; + } + + withOptionalDatetimeLessThanOrEqualTo(val: string): this { + this.filters.push({ "optionalDatetime": { "$lte": val } }); + return this; + } + + withOptionalDatetimeBetween(lower: string, upper: string): this { + this.filters.push({ "optionalDatetime": { "$between": [lower, upper] } }); + return this; + } + + withOptionalDatetimeIsKnown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": false } }); + return this; + } + + withOptionalDatetimeIsUnknown(): this { + this.filters.push({ "optionalDatetime": { "$isNull": true } }); + return this; + } + + withCreateTimeIs(val: unknown): this { + this.filters.push({ "createTime": { "$eq": val } }); + return this; + } + + withCreateTimeIsNot(val: unknown): this { + this.filters.push({ "createTime": { "$ne": val } }); + return this; + } + + withCreateTimeIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$in": vals } }); + return this; + } + + withCreateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "createTime": { "$notIn": vals } }); + return this; + } + + withCreateTimeGreaterThan(val: unknown): this { + this.filters.push({ "createTime": { "$gt": val } }); + return this; + } + + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$gte": val } }); + return this; + } + + withCreateTimeLessThan(val: unknown): this { + this.filters.push({ "createTime": { "$lt": val } }); + return this; + } + + withCreateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "createTime": { "$lte": val } }); + return this; + } + + withCreateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "createTime": { "$between": [lower, upper] } }); + return this; + } + + withCreateTimeIsKnown(): this { + this.filters.push({ "createTime": { "$isNull": false } }); + return this; + } + + withCreateTimeIsUnknown(): this { + this.filters.push({ "createTime": { "$isNull": true } }); + return this; + } + + withUpdateTimeIs(val: unknown): this { + this.filters.push({ "updateTime": { "$eq": val } }); + return this; + } + + withUpdateTimeIsNot(val: unknown): this { + this.filters.push({ "updateTime": { "$ne": val } }); + return this; + } + + withUpdateTimeIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$in": vals } }); + return this; + } + + withUpdateTimeNotIn(...vals: unknown[]): this { + this.filters.push({ "updateTime": { "$notIn": vals } }); + return this; + } + + withUpdateTimeGreaterThan(val: unknown): this { + this.filters.push({ "updateTime": { "$gt": val } }); + return this; + } + + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$gte": val } }); + return this; + } + + withUpdateTimeLessThan(val: unknown): this { + this.filters.push({ "updateTime": { "$lt": val } }); + return this; + } + + withUpdateTimeLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "updateTime": { "$lte": val } }); + return this; + } + + withUpdateTimeBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "updateTime": { "$between": [lower, upper] } }); + return this; + } + + withUpdateTimeIsKnown(): this { + this.filters.push({ "updateTime": { "$isNull": false } }); + return this; + } + + withUpdateTimeIsUnknown(): this { + this.filters.push({ "updateTime": { "$isNull": true } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + + orderByRequiredStringAscending(): this { + this.query.orderBy("requiredString", "asc"); + return this; + } + + orderByRequiredStringDescending(): this { + this.query.orderBy("requiredString", "desc"); + return this; + } + + orderByOptionalStringAscending(): this { + this.query.orderBy("optionalString", "asc"); + return this; + } + + orderByOptionalStringDescending(): this { + this.query.orderBy("optionalString", "desc"); + return this; + } + + orderByLargeTextAscending(): this { + this.query.orderBy("largeText", "asc"); + return this; + } + + orderByLargeTextDescending(): this { + this.query.orderBy("largeText", "desc"); + return this; + } + + orderByRequiredBooleanAscending(): this { + this.query.orderBy("requiredBoolean", "asc"); + return this; + } + + orderByRequiredBooleanDescending(): this { + this.query.orderBy("requiredBoolean", "desc"); + return this; + } + + orderByOptionalBooleanAscending(): this { + this.query.orderBy("optionalBoolean", "asc"); + return this; + } + + orderByOptionalBooleanDescending(): this { + this.query.orderBy("optionalBoolean", "desc"); + return this; + } + + orderByRequiredIntegerAscending(): this { + this.query.orderBy("requiredInteger", "asc"); + return this; + } + + orderByRequiredIntegerDescending(): this { + this.query.orderBy("requiredInteger", "desc"); + return this; + } + + orderByOptionalIntegerAscending(): this { + this.query.orderBy("optionalInteger", "asc"); + return this; + } + + orderByOptionalIntegerDescending(): this { + this.query.orderBy("optionalInteger", "desc"); + return this; + } + + orderByRequiredLongAscending(): this { + this.query.orderBy("requiredLong", "asc"); + return this; + } + + orderByRequiredLongDescending(): this { + this.query.orderBy("requiredLong", "desc"); + return this; + } + + orderByOptionalLongAscending(): this { + this.query.orderBy("optionalLong", "asc"); + return this; + } + + orderByOptionalLongDescending(): this { + this.query.orderBy("optionalLong", "desc"); + return this; + } + + orderByRequiredDecimalAscending(): this { + this.query.orderBy("requiredDecimal", "asc"); + return this; + } + + orderByRequiredDecimalDescending(): this { + this.query.orderBy("requiredDecimal", "desc"); + return this; + } + + orderByOptionalDecimalAscending(): this { + this.query.orderBy("optionalDecimal", "asc"); + return this; + } + + orderByOptionalDecimalDescending(): this { + this.query.orderBy("optionalDecimal", "desc"); + return this; + } + + orderByRequiredFloatAscending(): this { + this.query.orderBy("requiredFloat", "asc"); + return this; + } + + orderByRequiredFloatDescending(): this { + this.query.orderBy("requiredFloat", "desc"); + return this; + } + + orderByOptionalFloatAscending(): this { + this.query.orderBy("optionalFloat", "asc"); + return this; + } + + orderByOptionalFloatDescending(): this { + this.query.orderBy("optionalFloat", "desc"); + return this; + } + + orderByRequiredDoubleAscending(): this { + this.query.orderBy("requiredDouble", "asc"); + return this; + } + + orderByRequiredDoubleDescending(): this { + this.query.orderBy("requiredDouble", "desc"); + return this; + } + + orderByOptionalDoubleAscending(): this { + this.query.orderBy("optionalDouble", "asc"); + return this; + } + + orderByOptionalDoubleDescending(): this { + this.query.orderBy("optionalDouble", "desc"); + return this; + } + + orderByRequiredDateAscending(): this { + this.query.orderBy("requiredDate", "asc"); + return this; + } + + orderByRequiredDateDescending(): this { + this.query.orderBy("requiredDate", "desc"); + return this; + } + + orderByOptionalDateAscending(): this { + this.query.orderBy("optionalDate", "asc"); + return this; + } + + orderByOptionalDateDescending(): this { + this.query.orderBy("optionalDate", "desc"); + return this; + } + + orderByRequiredTimeAscending(): this { + this.query.orderBy("requiredTime", "asc"); + return this; + } + + orderByRequiredTimeDescending(): this { + this.query.orderBy("requiredTime", "desc"); + return this; + } + + orderByOptionalTimeAscending(): this { + this.query.orderBy("optionalTime", "asc"); + return this; + } + + orderByOptionalTimeDescending(): this { + this.query.orderBy("optionalTime", "desc"); + return this; + } + + orderByRequiredDatetimeAscending(): this { + this.query.orderBy("requiredDatetime", "asc"); + return this; + } + + orderByRequiredDatetimeDescending(): this { + this.query.orderBy("requiredDatetime", "desc"); + return this; + } + + orderByOptionalDatetimeAscending(): this { + this.query.orderBy("optionalDatetime", "asc"); + return this; + } + + orderByOptionalDatetimeDescending(): this { + this.query.orderBy("optionalDatetime", "desc"); + return this; + } + + orderByCreateTimeAscending(): this { + this.query.orderBy("createTime", "asc"); + return this; + } + + orderByCreateTimeDescending(): this { + this.query.orderBy("createTime", "desc"); + return this; + } + + orderByUpdateTimeAscending(): this { + this.query.orderBy("updateTime", "asc"); + return this; + } + + orderByUpdateTimeDescending(): this { + this.query.orderBy("updateTime", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + minRequiredInteger(): this { + return this.minRequiredIntegerAs("minOfRequiredInteger"); + } + + minRequiredIntegerAs(retName: string): this { + this.query.aggregate("min", "requiredInteger", retName); + return this; + } + maxRequiredInteger(): this { + return this.maxRequiredIntegerAs("maxOfRequiredInteger"); + } + + maxRequiredIntegerAs(retName: string): this { + this.query.aggregate("max", "requiredInteger", retName); + return this; + } + sumRequiredInteger(): this { + return this.sumRequiredIntegerAs("sumOfRequiredInteger"); + } + + sumRequiredIntegerAs(retName: string): this { + this.query.aggregate("sum", "requiredInteger", retName); + return this; + } + avgRequiredInteger(): this { + return this.avgRequiredIntegerAs("avgOfRequiredInteger"); + } + + avgRequiredIntegerAs(retName: string): this { + this.query.aggregate("avg", "requiredInteger", retName); + return this; + } + standardDeviationRequiredInteger(): this { + return this.standardDeviationRequiredIntegerAs("standardDeviationOfRequiredInteger"); + } + + standardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev", "requiredInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredInteger(): this { + return this.squareRootOfPopulationStandardDeviationRequiredIntegerAs("squareRootOfPopulationStandardDeviationOfRequiredInteger"); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredInteger", retName); + return this; + } + sampleVarianceRequiredInteger(): this { + return this.sampleVarianceRequiredIntegerAs("sampleVarianceOfRequiredInteger"); + } + + sampleVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "requiredInteger", retName); + return this; + } + samplePopulationVarianceRequiredInteger(): this { + return this.samplePopulationVarianceRequiredIntegerAs("samplePopulationVarianceOfRequiredInteger"); + } + + samplePopulationVarianceRequiredIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "requiredInteger", retName); + return this; + } + minOptionalInteger(): this { + return this.minOptionalIntegerAs("minOfOptionalInteger"); + } + + minOptionalIntegerAs(retName: string): this { + this.query.aggregate("min", "optionalInteger", retName); + return this; + } + maxOptionalInteger(): this { + return this.maxOptionalIntegerAs("maxOfOptionalInteger"); + } + + maxOptionalIntegerAs(retName: string): this { + this.query.aggregate("max", "optionalInteger", retName); + return this; + } + sumOptionalInteger(): this { + return this.sumOptionalIntegerAs("sumOfOptionalInteger"); + } + + sumOptionalIntegerAs(retName: string): this { + this.query.aggregate("sum", "optionalInteger", retName); + return this; + } + avgOptionalInteger(): this { + return this.avgOptionalIntegerAs("avgOfOptionalInteger"); + } + + avgOptionalIntegerAs(retName: string): this { + this.query.aggregate("avg", "optionalInteger", retName); + return this; + } + standardDeviationOptionalInteger(): this { + return this.standardDeviationOptionalIntegerAs("standardDeviationOfOptionalInteger"); + } + + standardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev", "optionalInteger", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalInteger(): this { + return this.squareRootOfPopulationStandardDeviationOptionalIntegerAs("squareRootOfPopulationStandardDeviationOfOptionalInteger"); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalInteger", retName); + return this; + } + sampleVarianceOptionalInteger(): this { + return this.sampleVarianceOptionalIntegerAs("sampleVarianceOfOptionalInteger"); + } + + sampleVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_samp", "optionalInteger", retName); + return this; + } + samplePopulationVarianceOptionalInteger(): this { + return this.samplePopulationVarianceOptionalIntegerAs("samplePopulationVarianceOfOptionalInteger"); + } + + samplePopulationVarianceOptionalIntegerAs(retName: string): this { + this.query.aggregate("var_pop", "optionalInteger", retName); + return this; + } + minRequiredLong(): this { + return this.minRequiredLongAs("minOfRequiredLong"); + } + + minRequiredLongAs(retName: string): this { + this.query.aggregate("min", "requiredLong", retName); + return this; + } + maxRequiredLong(): this { + return this.maxRequiredLongAs("maxOfRequiredLong"); + } + + maxRequiredLongAs(retName: string): this { + this.query.aggregate("max", "requiredLong", retName); + return this; + } + sumRequiredLong(): this { + return this.sumRequiredLongAs("sumOfRequiredLong"); + } + + sumRequiredLongAs(retName: string): this { + this.query.aggregate("sum", "requiredLong", retName); + return this; + } + avgRequiredLong(): this { + return this.avgRequiredLongAs("avgOfRequiredLong"); + } + + avgRequiredLongAs(retName: string): this { + this.query.aggregate("avg", "requiredLong", retName); + return this; + } + standardDeviationRequiredLong(): this { + return this.standardDeviationRequiredLongAs("standardDeviationOfRequiredLong"); + } + + standardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev", "requiredLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLong(): this { + return this.squareRootOfPopulationStandardDeviationRequiredLongAs("squareRootOfPopulationStandardDeviationOfRequiredLong"); + } + + squareRootOfPopulationStandardDeviationRequiredLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredLong", retName); + return this; + } + sampleVarianceRequiredLong(): this { + return this.sampleVarianceRequiredLongAs("sampleVarianceOfRequiredLong"); + } + + sampleVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_samp", "requiredLong", retName); + return this; + } + samplePopulationVarianceRequiredLong(): this { + return this.samplePopulationVarianceRequiredLongAs("samplePopulationVarianceOfRequiredLong"); + } + + samplePopulationVarianceRequiredLongAs(retName: string): this { + this.query.aggregate("var_pop", "requiredLong", retName); + return this; + } + minOptionalLong(): this { + return this.minOptionalLongAs("minOfOptionalLong"); + } + + minOptionalLongAs(retName: string): this { + this.query.aggregate("min", "optionalLong", retName); + return this; + } + maxOptionalLong(): this { + return this.maxOptionalLongAs("maxOfOptionalLong"); + } + + maxOptionalLongAs(retName: string): this { + this.query.aggregate("max", "optionalLong", retName); + return this; + } + sumOptionalLong(): this { + return this.sumOptionalLongAs("sumOfOptionalLong"); + } + + sumOptionalLongAs(retName: string): this { + this.query.aggregate("sum", "optionalLong", retName); + return this; + } + avgOptionalLong(): this { + return this.avgOptionalLongAs("avgOfOptionalLong"); + } + + avgOptionalLongAs(retName: string): this { + this.query.aggregate("avg", "optionalLong", retName); + return this; + } + standardDeviationOptionalLong(): this { + return this.standardDeviationOptionalLongAs("standardDeviationOfOptionalLong"); + } + + standardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev", "optionalLong", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLong(): this { + return this.squareRootOfPopulationStandardDeviationOptionalLongAs("squareRootOfPopulationStandardDeviationOfOptionalLong"); + } + + squareRootOfPopulationStandardDeviationOptionalLongAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalLong", retName); + return this; + } + sampleVarianceOptionalLong(): this { + return this.sampleVarianceOptionalLongAs("sampleVarianceOfOptionalLong"); + } + + sampleVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_samp", "optionalLong", retName); + return this; + } + samplePopulationVarianceOptionalLong(): this { + return this.samplePopulationVarianceOptionalLongAs("samplePopulationVarianceOfOptionalLong"); + } + + samplePopulationVarianceOptionalLongAs(retName: string): this { + this.query.aggregate("var_pop", "optionalLong", retName); + return this; + } + minRequiredDecimal(): this { + return this.minRequiredDecimalAs("minOfRequiredDecimal"); + } + + minRequiredDecimalAs(retName: string): this { + this.query.aggregate("min", "requiredDecimal", retName); + return this; + } + maxRequiredDecimal(): this { + return this.maxRequiredDecimalAs("maxOfRequiredDecimal"); + } + + maxRequiredDecimalAs(retName: string): this { + this.query.aggregate("max", "requiredDecimal", retName); + return this; + } + sumRequiredDecimal(): this { + return this.sumRequiredDecimalAs("sumOfRequiredDecimal"); + } + + sumRequiredDecimalAs(retName: string): this { + this.query.aggregate("sum", "requiredDecimal", retName); + return this; + } + avgRequiredDecimal(): this { + return this.avgRequiredDecimalAs("avgOfRequiredDecimal"); + } + + avgRequiredDecimalAs(retName: string): this { + this.query.aggregate("avg", "requiredDecimal", retName); + return this; + } + standardDeviationRequiredDecimal(): this { + return this.standardDeviationRequiredDecimalAs("standardDeviationOfRequiredDecimal"); + } + + standardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev", "requiredDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimal(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDecimalAs("squareRootOfPopulationStandardDeviationOfRequiredDecimal"); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDecimal", retName); + return this; + } + sampleVarianceRequiredDecimal(): this { + return this.sampleVarianceRequiredDecimalAs("sampleVarianceOfRequiredDecimal"); + } + + sampleVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDecimal", retName); + return this; + } + samplePopulationVarianceRequiredDecimal(): this { + return this.samplePopulationVarianceRequiredDecimalAs("samplePopulationVarianceOfRequiredDecimal"); + } + + samplePopulationVarianceRequiredDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDecimal", retName); + return this; + } + minOptionalDecimal(): this { + return this.minOptionalDecimalAs("minOfOptionalDecimal"); + } + + minOptionalDecimalAs(retName: string): this { + this.query.aggregate("min", "optionalDecimal", retName); + return this; + } + maxOptionalDecimal(): this { + return this.maxOptionalDecimalAs("maxOfOptionalDecimal"); + } + + maxOptionalDecimalAs(retName: string): this { + this.query.aggregate("max", "optionalDecimal", retName); + return this; + } + sumOptionalDecimal(): this { + return this.sumOptionalDecimalAs("sumOfOptionalDecimal"); + } + + sumOptionalDecimalAs(retName: string): this { + this.query.aggregate("sum", "optionalDecimal", retName); + return this; + } + avgOptionalDecimal(): this { + return this.avgOptionalDecimalAs("avgOfOptionalDecimal"); + } + + avgOptionalDecimalAs(retName: string): this { + this.query.aggregate("avg", "optionalDecimal", retName); + return this; + } + standardDeviationOptionalDecimal(): this { + return this.standardDeviationOptionalDecimalAs("standardDeviationOfOptionalDecimal"); + } + + standardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev", "optionalDecimal", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimal(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDecimalAs("squareRootOfPopulationStandardDeviationOfOptionalDecimal"); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDecimal", retName); + return this; + } + sampleVarianceOptionalDecimal(): this { + return this.sampleVarianceOptionalDecimalAs("sampleVarianceOfOptionalDecimal"); + } + + sampleVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDecimal", retName); + return this; + } + samplePopulationVarianceOptionalDecimal(): this { + return this.samplePopulationVarianceOptionalDecimalAs("samplePopulationVarianceOfOptionalDecimal"); + } + + samplePopulationVarianceOptionalDecimalAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDecimal", retName); + return this; + } + minRequiredFloat(): this { + return this.minRequiredFloatAs("minOfRequiredFloat"); + } + + minRequiredFloatAs(retName: string): this { + this.query.aggregate("min", "requiredFloat", retName); + return this; + } + maxRequiredFloat(): this { + return this.maxRequiredFloatAs("maxOfRequiredFloat"); + } + + maxRequiredFloatAs(retName: string): this { + this.query.aggregate("max", "requiredFloat", retName); + return this; + } + sumRequiredFloat(): this { + return this.sumRequiredFloatAs("sumOfRequiredFloat"); + } + + sumRequiredFloatAs(retName: string): this { + this.query.aggregate("sum", "requiredFloat", retName); + return this; + } + avgRequiredFloat(): this { + return this.avgRequiredFloatAs("avgOfRequiredFloat"); + } + + avgRequiredFloatAs(retName: string): this { + this.query.aggregate("avg", "requiredFloat", retName); + return this; + } + standardDeviationRequiredFloat(): this { + return this.standardDeviationRequiredFloatAs("standardDeviationOfRequiredFloat"); + } + + standardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev", "requiredFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloat(): this { + return this.squareRootOfPopulationStandardDeviationRequiredFloatAs("squareRootOfPopulationStandardDeviationOfRequiredFloat"); + } + + squareRootOfPopulationStandardDeviationRequiredFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredFloat", retName); + return this; + } + sampleVarianceRequiredFloat(): this { + return this.sampleVarianceRequiredFloatAs("sampleVarianceOfRequiredFloat"); + } + + sampleVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_samp", "requiredFloat", retName); + return this; + } + samplePopulationVarianceRequiredFloat(): this { + return this.samplePopulationVarianceRequiredFloatAs("samplePopulationVarianceOfRequiredFloat"); + } + + samplePopulationVarianceRequiredFloatAs(retName: string): this { + this.query.aggregate("var_pop", "requiredFloat", retName); + return this; + } + minOptionalFloat(): this { + return this.minOptionalFloatAs("minOfOptionalFloat"); + } + + minOptionalFloatAs(retName: string): this { + this.query.aggregate("min", "optionalFloat", retName); + return this; + } + maxOptionalFloat(): this { + return this.maxOptionalFloatAs("maxOfOptionalFloat"); + } + + maxOptionalFloatAs(retName: string): this { + this.query.aggregate("max", "optionalFloat", retName); + return this; + } + sumOptionalFloat(): this { + return this.sumOptionalFloatAs("sumOfOptionalFloat"); + } + + sumOptionalFloatAs(retName: string): this { + this.query.aggregate("sum", "optionalFloat", retName); + return this; + } + avgOptionalFloat(): this { + return this.avgOptionalFloatAs("avgOfOptionalFloat"); + } + + avgOptionalFloatAs(retName: string): this { + this.query.aggregate("avg", "optionalFloat", retName); + return this; + } + standardDeviationOptionalFloat(): this { + return this.standardDeviationOptionalFloatAs("standardDeviationOfOptionalFloat"); + } + + standardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev", "optionalFloat", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloat(): this { + return this.squareRootOfPopulationStandardDeviationOptionalFloatAs("squareRootOfPopulationStandardDeviationOfOptionalFloat"); + } + + squareRootOfPopulationStandardDeviationOptionalFloatAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalFloat", retName); + return this; + } + sampleVarianceOptionalFloat(): this { + return this.sampleVarianceOptionalFloatAs("sampleVarianceOfOptionalFloat"); + } + + sampleVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_samp", "optionalFloat", retName); + return this; + } + samplePopulationVarianceOptionalFloat(): this { + return this.samplePopulationVarianceOptionalFloatAs("samplePopulationVarianceOfOptionalFloat"); + } + + samplePopulationVarianceOptionalFloatAs(retName: string): this { + this.query.aggregate("var_pop", "optionalFloat", retName); + return this; + } + minRequiredDouble(): this { + return this.minRequiredDoubleAs("minOfRequiredDouble"); + } + + minRequiredDoubleAs(retName: string): this { + this.query.aggregate("min", "requiredDouble", retName); + return this; + } + maxRequiredDouble(): this { + return this.maxRequiredDoubleAs("maxOfRequiredDouble"); + } + + maxRequiredDoubleAs(retName: string): this { + this.query.aggregate("max", "requiredDouble", retName); + return this; + } + sumRequiredDouble(): this { + return this.sumRequiredDoubleAs("sumOfRequiredDouble"); + } + + sumRequiredDoubleAs(retName: string): this { + this.query.aggregate("sum", "requiredDouble", retName); + return this; + } + avgRequiredDouble(): this { + return this.avgRequiredDoubleAs("avgOfRequiredDouble"); + } + + avgRequiredDoubleAs(retName: string): this { + this.query.aggregate("avg", "requiredDouble", retName); + return this; + } + standardDeviationRequiredDouble(): this { + return this.standardDeviationRequiredDoubleAs("standardDeviationOfRequiredDouble"); + } + + standardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev", "requiredDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDouble(): this { + return this.squareRootOfPopulationStandardDeviationRequiredDoubleAs("squareRootOfPopulationStandardDeviationOfRequiredDouble"); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "requiredDouble", retName); + return this; + } + sampleVarianceRequiredDouble(): this { + return this.sampleVarianceRequiredDoubleAs("sampleVarianceOfRequiredDouble"); + } + + sampleVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "requiredDouble", retName); + return this; + } + samplePopulationVarianceRequiredDouble(): this { + return this.samplePopulationVarianceRequiredDoubleAs("samplePopulationVarianceOfRequiredDouble"); + } + + samplePopulationVarianceRequiredDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "requiredDouble", retName); + return this; + } + minOptionalDouble(): this { + return this.minOptionalDoubleAs("minOfOptionalDouble"); + } + + minOptionalDoubleAs(retName: string): this { + this.query.aggregate("min", "optionalDouble", retName); + return this; + } + maxOptionalDouble(): this { + return this.maxOptionalDoubleAs("maxOfOptionalDouble"); + } + + maxOptionalDoubleAs(retName: string): this { + this.query.aggregate("max", "optionalDouble", retName); + return this; + } + sumOptionalDouble(): this { + return this.sumOptionalDoubleAs("sumOfOptionalDouble"); + } + + sumOptionalDoubleAs(retName: string): this { + this.query.aggregate("sum", "optionalDouble", retName); + return this; + } + avgOptionalDouble(): this { + return this.avgOptionalDoubleAs("avgOfOptionalDouble"); + } + + avgOptionalDoubleAs(retName: string): this { + this.query.aggregate("avg", "optionalDouble", retName); + return this; + } + standardDeviationOptionalDouble(): this { + return this.standardDeviationOptionalDoubleAs("standardDeviationOfOptionalDouble"); + } + + standardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev", "optionalDouble", retName); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDouble(): this { + return this.squareRootOfPopulationStandardDeviationOptionalDoubleAs("squareRootOfPopulationStandardDeviationOfOptionalDouble"); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleAs(retName: string): this { + this.query.aggregate("stddev_pop", "optionalDouble", retName); + return this; + } + sampleVarianceOptionalDouble(): this { + return this.sampleVarianceOptionalDoubleAs("sampleVarianceOfOptionalDouble"); + } + + sampleVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_samp", "optionalDouble", retName); + return this; + } + samplePopulationVarianceOptionalDouble(): this { + return this.samplePopulationVarianceOptionalDoubleAs("samplePopulationVarianceOfOptionalDouble"); + } + + samplePopulationVarianceOptionalDoubleAs(retName: string): this { + this.query.aggregate("var_pop", "optionalDouble", retName); + return this; + } + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByTypePlatform(): this { + this.query.groupBy("typePlatform"); + return this; + } + + groupByTypePlatformAs(retName: string): this { + this.query.groupBy("typePlatform", retName); + return this; + } + groupByRequiredString(): this { + this.query.groupBy("requiredString"); + return this; + } + + groupByRequiredStringAs(retName: string): this { + this.query.groupBy("requiredString", retName); + return this; + } + groupByOptionalString(): this { + this.query.groupBy("optionalString"); + return this; + } + + groupByOptionalStringAs(retName: string): this { + this.query.groupBy("optionalString", retName); + return this; + } + groupByLargeText(): this { + this.query.groupBy("largeText"); + return this; + } + + groupByLargeTextAs(retName: string): this { + this.query.groupBy("largeText", retName); + return this; + } + groupByRequiredBoolean(): this { + this.query.groupBy("requiredBoolean"); + return this; + } + + groupByRequiredBooleanAs(retName: string): this { + this.query.groupBy("requiredBoolean", retName); + return this; + } + groupByOptionalBoolean(): this { + this.query.groupBy("optionalBoolean"); + return this; + } + + groupByOptionalBooleanAs(retName: string): this { + this.query.groupBy("optionalBoolean", retName); + return this; + } + groupByRequiredInteger(): this { + this.query.groupBy("requiredInteger"); + return this; + } + + groupByRequiredIntegerAs(retName: string): this { + this.query.groupBy("requiredInteger", retName); + return this; + } + groupByOptionalInteger(): this { + this.query.groupBy("optionalInteger"); + return this; + } + + groupByOptionalIntegerAs(retName: string): this { + this.query.groupBy("optionalInteger", retName); + return this; + } + groupByRequiredLong(): this { + this.query.groupBy("requiredLong"); + return this; + } + + groupByRequiredLongAs(retName: string): this { + this.query.groupBy("requiredLong", retName); + return this; + } + groupByOptionalLong(): this { + this.query.groupBy("optionalLong"); + return this; + } + + groupByOptionalLongAs(retName: string): this { + this.query.groupBy("optionalLong", retName); + return this; + } + groupByRequiredDecimal(): this { + this.query.groupBy("requiredDecimal"); + return this; + } + + groupByRequiredDecimalAs(retName: string): this { + this.query.groupBy("requiredDecimal", retName); + return this; + } + groupByOptionalDecimal(): this { + this.query.groupBy("optionalDecimal"); + return this; + } + + groupByOptionalDecimalAs(retName: string): this { + this.query.groupBy("optionalDecimal", retName); + return this; + } + groupByRequiredFloat(): this { + this.query.groupBy("requiredFloat"); + return this; + } + + groupByRequiredFloatAs(retName: string): this { + this.query.groupBy("requiredFloat", retName); + return this; + } + groupByOptionalFloat(): this { + this.query.groupBy("optionalFloat"); + return this; + } + + groupByOptionalFloatAs(retName: string): this { + this.query.groupBy("optionalFloat", retName); + return this; + } + groupByRequiredDouble(): this { + this.query.groupBy("requiredDouble"); + return this; + } + + groupByRequiredDoubleAs(retName: string): this { + this.query.groupBy("requiredDouble", retName); + return this; + } + groupByOptionalDouble(): this { + this.query.groupBy("optionalDouble"); + return this; + } + + groupByOptionalDoubleAs(retName: string): this { + this.query.groupBy("optionalDouble", retName); + return this; + } + groupByRequiredDate(): this { + this.query.groupBy("requiredDate"); + return this; + } + + groupByRequiredDateAs(retName: string): this { + this.query.groupBy("requiredDate", retName); + return this; + } + groupByOptionalDate(): this { + this.query.groupBy("optionalDate"); + return this; + } + + groupByOptionalDateAs(retName: string): this { + this.query.groupBy("optionalDate", retName); + return this; + } + groupByRequiredTime(): this { + this.query.groupBy("requiredTime"); + return this; + } + + groupByRequiredTimeAs(retName: string): this { + this.query.groupBy("requiredTime", retName); + return this; + } + groupByOptionalTime(): this { + this.query.groupBy("optionalTime"); + return this; + } + + groupByOptionalTimeAs(retName: string): this { + this.query.groupBy("optionalTime", retName); + return this; + } + groupByRequiredDatetime(): this { + this.query.groupBy("requiredDatetime"); + return this; + } + + groupByRequiredDatetimeAs(retName: string): this { + this.query.groupBy("requiredDatetime", retName); + return this; + } + groupByOptionalDatetime(): this { + this.query.groupBy("optionalDatetime"); + return this; + } + + groupByOptionalDatetimeAs(retName: string): this { + this.query.groupBy("optionalDatetime", retName); + return this; + } + groupByCreateTime(): this { + this.query.groupBy("createTime"); + return this; + } + + groupByCreateTimeAs(retName: string): this { + this.query.groupBy("createTime", retName); + return this; + } + groupByUpdateTime(): this { + this.query.groupBy("updateTime"); + return this; + } + + groupByUpdateTimeAs(retName: string): this { + this.query.groupBy("updateTime", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + facetByTypePlatformAs( + facetName: string, + request: { readonly entityName: "TypePlatform"; toQuery(): SelectQuery }, + includeAllFacets = true, + ): this { + this.query.facetBy(facetName, "typePlatform", request, includeAllFacets, + { kind: "facet", method: "facetByTypePlatformAs", relation: "typePlatform", alias: facetName }); + return this; + } + + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof ScalarTypeProbe + ? row + : ScalarTypeProbe.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof ScalarTypeProbe + ? entity + : ScalarTypeProbe.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableScalarTypeProbeRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return ScalarTypeProbe.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/requests/TypePlatformRequest.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/requests/TypePlatformRequest.ts new file mode 100644 index 0000000000000000000000000000000000000000..1d0caed3d9719c20a917e89fdcad7bad64597fb0 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/generated/requests/TypePlatformRequest.ts @@ -0,0 +1,1736 @@ +import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; +import { TypePlatform } from '../models/TypePlatform'; +import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; +import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; + + + +export class TypePlatformRequest { + private query: SelectQuery; + private filters: any[] = []; + private _purpose: string | undefined; + private _comment: string | undefined; + private _pageCountAlias: string | undefined; + private _pageCountMethod: "count" | "countAs" | undefined; + private _dynamicSearchWarnings: DynamicSearchWarning[] = []; + + constructor(minimal = false) { + this.query = new SelectQuery("TypePlatform"); + this.filters.push({ version: { "$gte": 1 } }); + if (minimal) { + this.selectId(); + this.selectVersion(); + } + else this.selectSelfFields(); + } + + get entityName(): "TypePlatform" { + return "TypePlatform"; + } + + comment(c: string): this { + this.query.comment(c); + this._comment = c; + return this; + } + + filterByJson(source: unknown, warn?: (warning: DynamicSearchWarning) => void): this { + const base = this.query.clone(); + if (this.filters.length > 0) base.filter({ "$and": this.filters }); + const merged = mergeGeneratedScalarSearch(base, source, GENERATED_SEARCH_MODELS, warn); + this.query = merged.query as SelectQuery; + this.filters = this.query.filterCondition ? [this.query.filterCondition] : []; + this._dynamicSearchWarnings.push(...merged.warnings); + return this; + } + + get dynamicSearchWarnings(): readonly DynamicSearchWarning[] { + return this._dynamicSearchWarnings.map(warning => ({ ...warning })); + } + + purpose(p: string): ExecutableTypePlatformRequest { + this.query.purpose(p); + this._purpose = p; + return new ExecutableTypePlatformRequest( + (context) => context.withQueryRequest(this.query, () => this.executeForListInternal(context)), + (context) => context.withQueryRequest(this.query, () => this.executeForRowsInternal(context)), + (context, chunkSize) => this.executeForStreamInternal(context, chunkSize), + () => this.limit(1), + (c) => this.comment(c), + () => this.ensureIntent()); + } + + optimizeForContinuousPageFetch(): this { + this.query.optimizeForContinuousPageFetch(); + return this; + } + + optimizeForContinuousPageFetchWith(namespace: string, ttlSeconds: number): this { + this.query.optimizeForContinuousPageFetchWith(namespace, ttlSeconds); + return this; + } + + optimizePaginationWithIdSet(): this { + this.query.optimizePaginationWithIdSet(); + return this; + } + + optimizePaginationWithIdSetConfig(namespace: string, ttlSeconds: number, maxIds: number): this { + this.query.optimizePaginationWithIdSetConfig(namespace, ttlSeconds, maxIds); + return this; + } + + topNProbeParentThreshold(threshold: number): this { + this.query.topNProbeParentThreshold(threshold); + return this; + } + + limit(n: number): this { + this.query.limit(n); + return this; + } + + offset(n: number): this { + this.query.offset(n); + return this; + } + + toQuery(): SelectQuery { + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + return this.query; + } + + withDeletedRows(): this { + this.query.withDeletedRows(); + this.filters = this.filters.filter(filter => !("version" in filter)); + return this; + } + + deletedRowsOnly(): this { + this.withDeletedRows(); + this.query.deletedRowsOnly(); + this.filters.push({ version: { "$lte": -1 } }); + return this; + } + + selectSelfFields(): this { + this.query.select(["id", "name", "version"]); + return this; + } + + selectId(): this { + this.query.select(["id"]); + return this; + } + + selectName(): this { + this.query.select(["name"]); + return this; + } + + selectVersion(): this { + this.query.select(["version"]); + return this; + } + + + + + selectScalarTypeProbeListWith(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.query.relationQuery( + "scalarTypeProbeList", request.toQuery(), "id", "typePlatform", true, + { kind: "relation-select", method: "selectScalarTypeProbeListWith", relation: "scalarTypeProbeList" }); + return this; + } + + haveScalarTypeProbes(): this { + return this.withScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + haveNoScalarTypeProbes(): this { + return this.withoutScalarTypeProbeListMatching({ + entityName: "ScalarTypeProbe", + toQuery: () => new SelectQuery("ScalarTypeProbe"), + }); + } + + withScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$inSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + withoutScalarTypeProbeListMatching(request: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + this.filters.push({ + "id": { + "$notInSubquery": { + query: request.toQuery(), field: "typePlatform", + }, + }, + }); + return this; + } + + countScalarTypeProbes(): this { + return this.countScalarTypeProbesAs("countScalarTypeProbes"); + } + + countScalarTypeProbesAs(alias: string): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + this.countScalarTypeProbesWith(alias, { entityName: "ScalarTypeProbe", toQuery: () => query }); + this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { + kind: "relation-count", method: "countScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }; + return this; + } + + countScalarTypeProbesWith(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("Count", "id", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "relation-count", method: "countScalarTypeProbesWith", relation: "scalarTypeProbeList", alias }); + return this; + } + + minRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredIntegerOfScalarTypeProbesAs( + "minOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredIntegerOfScalarTypeProbesAs( + "maxOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredIntegerOfScalarTypeProbesAs( + "sumOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredIntegerOfScalarTypeProbesAs( + "avgOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredIntegerOfScalarTypeProbesAs( + "standardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredIntegerOfScalarTypeProbesAs( + "sampleVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalIntegerOfScalarTypeProbesAs( + "minOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalIntegerOfScalarTypeProbesAs( + "maxOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalIntegerOfScalarTypeProbesAs( + "sumOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalIntegerOfScalarTypeProbesAs( + "avgOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalIntegerOfScalarTypeProbesAs( + "standardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalIntegerOfScalarTypeProbesAs( + "sampleVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalIntegerOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalIntegerOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalInteger", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalIntegerOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredLongOfScalarTypeProbesAs( + "minOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredLongOfScalarTypeProbesAs( + "maxOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredLongOfScalarTypeProbesAs( + "sumOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredLongOfScalarTypeProbesAs( + "avgOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredLongOfScalarTypeProbesAs( + "standardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredLongOfScalarTypeProbesAs( + "sampleVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalLongOfScalarTypeProbesAs( + "minOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalLongOfScalarTypeProbesAs( + "maxOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalLongOfScalarTypeProbesAs( + "sumOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalLongOfScalarTypeProbesAs( + "avgOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalLongOfScalarTypeProbesAs( + "standardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalLongOfScalarTypeProbesAs( + "sampleVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalLongOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalLongOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalLongOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalLongOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalLong", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalLongOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDecimalOfScalarTypeProbesAs( + "minOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDecimalOfScalarTypeProbesAs( + "maxOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDecimalOfScalarTypeProbesAs( + "sumOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDecimalOfScalarTypeProbesAs( + "avgOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDecimalOfScalarTypeProbesAs( + "standardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDecimalOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDecimalOfScalarTypeProbesAs( + "minOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDecimalOfScalarTypeProbesAs( + "maxOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDecimalOfScalarTypeProbesAs( + "sumOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDecimalOfScalarTypeProbesAs( + "avgOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDecimalOfScalarTypeProbesAs( + "standardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDecimalOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDecimalOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDecimalOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDecimal", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDecimalOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredFloatOfScalarTypeProbesAs( + "minOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredFloatOfScalarTypeProbesAs( + "maxOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredFloatOfScalarTypeProbesAs( + "sumOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredFloatOfScalarTypeProbesAs( + "avgOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredFloatOfScalarTypeProbesAs( + "standardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredFloatOfScalarTypeProbesAs( + "sampleVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalFloatOfScalarTypeProbesAs( + "minOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalFloatOfScalarTypeProbesAs( + "maxOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalFloatOfScalarTypeProbesAs( + "sumOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalFloatOfScalarTypeProbesAs( + "avgOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalFloatOfScalarTypeProbesAs( + "standardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalFloatOfScalarTypeProbesAs( + "sampleVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalFloatOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalFloatOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalFloat", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalFloatOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minRequiredDoubleOfScalarTypeProbesAs( + "minOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxRequiredDoubleOfScalarTypeProbesAs( + "maxOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumRequiredDoubleOfScalarTypeProbesAs( + "sumOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgRequiredDoubleOfScalarTypeProbesAs( + "avgOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationRequiredDoubleOfScalarTypeProbesAs( + "standardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceRequiredDoubleOfScalarTypeProbesAs( + "sampleVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceRequiredDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfRequiredDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "requiredDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceRequiredDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + minOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.minOptionalDoubleOfScalarTypeProbesAs( + "minOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + minOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("min", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "minOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + maxOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.maxOptionalDoubleOfScalarTypeProbesAs( + "maxOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + maxOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("max", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "maxOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sumOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sumOptionalDoubleOfScalarTypeProbesAs( + "sumOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sumOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("sum", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sumOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + avgOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.avgOptionalDoubleOfScalarTypeProbesAs( + "avgOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + avgOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("avg", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "avgOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + standardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.standardDeviationOptionalDoubleOfScalarTypeProbesAs( + "standardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + standardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "standardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs( + "squareRootOfPopulationStandardDeviationOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("stddev_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "squareRootOfPopulationStandardDeviationOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + sampleVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.sampleVarianceOptionalDoubleOfScalarTypeProbesAs( + "sampleVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + sampleVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_samp", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "sampleVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + samplePopulationVarianceOptionalDoubleOfScalarTypeProbes(): this { + const query = new SelectQuery("ScalarTypeProbe").filter({ version: { "$gte": 1 } }); + return this.samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs( + "samplePopulationVarianceOfOptionalDoubleOfScalarTypeProbes", { entityName: "ScalarTypeProbe", toQuery: () => query }); + } + + samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs(alias: string, child: { readonly entityName: "ScalarTypeProbe"; toQuery(): SelectQuery }): this { + const query = child.toQuery().clone(); + query.aggregateItems = []; + query.aggregate("var_pop", "optionalDouble", alias); + this.query.relationAggregate("scalarTypeProbeList", alias, query, true, + { kind: "aggregate", method: "samplePopulationVarianceOptionalDoubleOfScalarTypeProbesAs", relation: "scalarTypeProbeList", alias }); + return this; + } + + withIdIs(val: string): this { + this.filters.push({ "id": { "$eq": val } }); + return this; + } + + withIdIsNot(val: string): this { + this.filters.push({ "id": { "$ne": val } }); + return this; + } + + withIdIn(...vals: string[]): this { + this.filters.push({ "id": { "$in": vals } }); + return this; + } + + withIdNotIn(...vals: string[]): this { + this.filters.push({ "id": { "$notIn": vals } }); + return this; + } + + withIdGreaterThan(val: string): this { + this.filters.push({ "id": { "$gt": val } }); + return this; + } + + withIdGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$gte": val } }); + return this; + } + + withIdLessThan(val: string): this { + this.filters.push({ "id": { "$lt": val } }); + return this; + } + + withIdLessThanOrEqualTo(val: string): this { + this.filters.push({ "id": { "$lte": val } }); + return this; + } + + withIdBetween(lower: string, upper: string): this { + this.filters.push({ "id": { "$between": [lower, upper] } }); + return this; + } + + withIdIsKnown(): this { + this.filters.push({ "id": { "$isNull": false } }); + return this; + } + + withIdIsUnknown(): this { + this.filters.push({ "id": { "$isNull": true } }); + return this; + } + + withNameContaining(val: string): this { + this.filters.push({ "name": { "$contains": val } }); + return this; + } + + withNameIs(val: string): this { + this.filters.push({ "name": { "$eq": val } }); + return this; + } + + withNameIsNot(val: string): this { + this.filters.push({ "name": { "$ne": val } }); + return this; + } + + withNameIn(...vals: string[]): this { + this.filters.push({ "name": { "$in": vals } }); + return this; + } + + withNameNotIn(...vals: string[]): this { + this.filters.push({ "name": { "$notIn": vals } }); + return this; + } + + withNameGreaterThan(val: string): this { + this.filters.push({ "name": { "$gt": val } }); + return this; + } + + withNameGreaterThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$gte": val } }); + return this; + } + + withNameLessThan(val: string): this { + this.filters.push({ "name": { "$lt": val } }); + return this; + } + + withNameLessThanOrEqualTo(val: string): this { + this.filters.push({ "name": { "$lte": val } }); + return this; + } + + withNameBetween(lower: string, upper: string): this { + this.filters.push({ "name": { "$between": [lower, upper] } }); + return this; + } + + withNameIsKnown(): this { + this.filters.push({ "name": { "$isNull": false } }); + return this; + } + + withNameIsUnknown(): this { + this.filters.push({ "name": { "$isNull": true } }); + return this; + } + withNameNotContaining(val: string): this { + this.filters.push({ "name": { "$notContains": val } }); + return this; + } + + withNameStartingWith(val: string): this { + this.filters.push({ "name": { "$startsWith": val } }); + return this; + } + + withNameNotStartingWith(val: string): this { + this.filters.push({ "name": { "$notStartsWith": val } }); + return this; + } + + withNameEndingWith(val: string): this { + this.filters.push({ "name": { "$endsWith": val } }); + return this; + } + + withNameNotEndingWith(val: string): this { + this.filters.push({ "name": { "$notEndsWith": val } }); + return this; + } + + withNameSoundingLike(val: string): this { + this.filters.push({ "name": { "$soundLike": val } }); + return this; + } + + withVersionIs(val: unknown): this { + this.filters.push({ "version": { "$eq": val } }); + return this; + } + + withVersionIsNot(val: unknown): this { + this.filters.push({ "version": { "$ne": val } }); + return this; + } + + withVersionIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$in": vals } }); + return this; + } + + withVersionNotIn(...vals: unknown[]): this { + this.filters.push({ "version": { "$notIn": vals } }); + return this; + } + + withVersionGreaterThan(val: unknown): this { + this.filters.push({ "version": { "$gt": val } }); + return this; + } + + withVersionGreaterThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$gte": val } }); + return this; + } + + withVersionLessThan(val: unknown): this { + this.filters.push({ "version": { "$lt": val } }); + return this; + } + + withVersionLessThanOrEqualTo(val: unknown): this { + this.filters.push({ "version": { "$lte": val } }); + return this; + } + + withVersionBetween(lower: unknown, upper: unknown): this { + this.filters.push({ "version": { "$between": [lower, upper] } }); + return this; + } + + withVersionIsKnown(): this { + this.filters.push({ "version": { "$isNull": false } }); + return this; + } + + withVersionIsUnknown(): this { + this.filters.push({ "version": { "$isNull": true } }); + return this; + } + + orderByIdAscending(): this { + this.query.orderBy("id", "asc"); + return this; + } + + orderByIdDescending(): this { + this.query.orderBy("id", "desc"); + return this; + } + + orderByNameAscending(): this { + this.query.orderBy("name", "asc"); + return this; + } + + orderByNameDescending(): this { + this.query.orderBy("name", "desc"); + return this; + } + + orderByVersionAscending(): this { + this.query.orderBy("version", "asc"); + return this; + } + + orderByVersionDescending(): this { + this.query.orderBy("version", "desc"); + return this; + } + + + // --- Aggregations --- + count(): this { + this.query.aggregate("Count", "id", "count"); + this._pageCountAlias = "count"; + this._pageCountMethod = "count"; + return this; + } + + countAs(retName: string): this { + this.query.aggregate("Count", "id", retName); + this._pageCountAlias = retName; + this._pageCountMethod = "countAs"; + return this; + } + + + // --- Group By --- + groupById(): this { + this.query.groupBy("id"); + return this; + } + + groupByIdAs(retName: string): this { + this.query.groupBy("id", retName); + return this; + } + groupByName(): this { + this.query.groupBy("name"); + return this; + } + + groupByNameAs(retName: string): this { + this.query.groupBy("name", retName); + return this; + } + groupByVersion(): this { + this.query.groupBy("version"); + return this; + } + + groupByVersionAs(retName: string): this { + this.query.groupBy("version", retName); + return this; + } + + // --- Facets --- + + private async executeForListInternal(context: UserContext): Promise> { + this.ensureIntent(); + if (this._pageCountAlias !== undefined) return this.executeCountedListInternal(context); + if (this.filters.length > 0) { + this.query.filter({ "$and": this.filters }); + } + + const service = context.requireResource("dataService"); + const rows = await service.executeQuery(context.prepareQuery(this.query)); + const aggregateOnly = this.query.aggregateItems.length > 0 && this.query.groupByItems.length === 0; + const data = aggregateOnly ? [] : rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot())); + const result = new SmartList(data); + if (aggregateOnly && rows[0]) Object.assign(result.aggregations, rows[0]); + + if (this.query.facets.length > 0) { + result.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), this.query, this.query.facets); + } + + return result; + } + + private async executeForRowsInternal(context: UserContext): Promise>> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + return new SmartList>( + await service.executeQuery(context.prepareQuery(this.query)) as Record[]); + } + + private async executeCountedListInternal( + context: UserContext, + ): Promise> { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + const useIdSet = preparedQuery.localIdSetPaginationOptions() !== undefined; + const countOperation = { kind: "named-count" as const, + method: this._pageCountMethod ?? "count", + ...(this._pageCountMethod === "countAs" ? { alias: this._pageCountAlias } : {}) }; + const totalCountBeforeRows = useIdSet ? undefined : await service.executeCount( + preparedQuery, this._pageCountAlias, countOperation); + const pageQuery = preparedQuery.clone(); + // A page count describes the full filtered set, not an aggregate-only page row. + pageQuery.aggregateItems = pageQuery.aggregateItems.filter(item => + !(String(item.function).toLowerCase() === "count" && item.alias === this._pageCountAlias)); + const rows = await service.executeQuery(pageQuery); + const totalCount = useIdSet && context.idSetPaginationCountAccuracy === "EXACT" + ? context.idSetPaginationCount! + : (totalCountBeforeRows ?? await service.executeCount(preparedQuery, this._pageCountAlias, countOperation)); + const data = new SmartList(rows.map((row: unknown) => + row instanceof TypePlatform + ? row + : TypePlatform.fromRecord(row as Record, new EntityRoot()))); + data.totalCount = totalCount; + if (this._pageCountAlias !== undefined) data.aggregations[this._pageCountAlias] = totalCount; + if (this.query.facets.length > 0) { + data.facets = await executeRelationFacets( + service, (query: any) => context.prepareQuery(query), preparedQuery, preparedQuery.facets); + } + return data; + } + + private executeForStreamInternal(context: UserContext, chunkSize: number): AsyncIterable { + this.ensureIntent(); + if (this.filters.length > 0) this.query.filter({ "$and": this.filters }); + const service = context.requireResource("dataService"); + const preparedQuery = context.prepareQuery(this.query); + // Prepare Context and capture the runtime request before returning a lazy iterator. + const chunks = service.executeForStream(preparedQuery, chunkSize); + return (async function* () { + for await (const chunk of chunks) { + for (const entity of chunk) { + yield entity instanceof TypePlatform + ? entity + : TypePlatform.fromRecord(entity as Record, new EntityRoot()); + } + } + })(); + } + + private ensureIntent(): void { + // Runtime owns validation, Unicode whitespace rules and typed diagnostics. + new QueryIntent(this._comment, this._purpose); + } + +} + +export class ExecutableTypePlatformRequest { + constructor( + private readonly execute: (context: UserContext) => Promise>, + private readonly executeRows: (context: UserContext) => Promise>>, + private readonly stream: (context: UserContext, chunkSize: number) => AsyncIterable, + private readonly limitOne: () => void, + private readonly addComment: (comment: string) => void, + private readonly ensureIntent: () => void, + ) {} + + comment(c: string): this { + this.addComment(c); + return this; + } + + async newEntity(context: UserContext): Promise { + this.ensureIntent(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return TypePlatform.teaqlCreate(context); + } + + executeForList(context: UserContext): Promise> { + this.ensureIntent(); + return this.execute(context); + } + + executeForRows(context: UserContext): Promise>> { + this.ensureIntent(); + return this.executeRows(context); + } + + executeForStream(context: UserContext, chunkSize = 1000): AsyncIterable { + this.ensureIntent(); + return this.stream(context, chunkSize); + } + + async executeForOne(context: UserContext): Promise { + this.limitOne(); + return (await this.executeForList(context))[0]; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/runtime-module.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/runtime-module.ts new file mode 100644 index 0000000000000000000000000000000000000000..de8df88e537c284dcbf024eab5e3271c241ee1e0 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/runtime-module.ts @@ -0,0 +1,128 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; +import { ObjectLocation, RuntimeModule } from "teaql-ts"; +import { ENTITY_SCHEMAS } from "./teaql-node-sql"; +import { ensureGeneratedBootstrap } from "./generated-bootstrap"; + +/** Generated canonical KSML to selected-wire mapping. Never infer this from TS members. */ +export const GENERATED_WIRE_MODEL_METADATA = Object.freeze({ + profile: "snake_case" as const, + entities: Object.freeze({ + "TypePlatform": Object.freeze({ + entityType: "TypePlatform", + profile: "snake_case" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "name": Object.freeze({ canonicalName: "name", wireName: "name", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }), + "ScalarTypeProbe": Object.freeze({ + entityType: "ScalarTypeProbe", + profile: "snake_case" as const, + fields: Object.freeze({ + "id": Object.freeze({ canonicalName: "id", wireName: "id", aliases: Object.freeze([] as string[]) }), + "type_platform": Object.freeze({ canonicalName: "type_platform", wireName: "type_platform", aliases: Object.freeze([] as string[]) }), + "required_string": Object.freeze({ canonicalName: "required_string", wireName: "required_string", aliases: Object.freeze([] as string[]) }), + "optional_string": Object.freeze({ canonicalName: "optional_string", wireName: "optional_string", aliases: Object.freeze([] as string[]) }), + "large_text": Object.freeze({ canonicalName: "large_text", wireName: "large_text", aliases: Object.freeze([] as string[]) }), + "required_boolean": Object.freeze({ canonicalName: "required_boolean", wireName: "required_boolean", aliases: Object.freeze([] as string[]) }), + "optional_boolean": Object.freeze({ canonicalName: "optional_boolean", wireName: "optional_boolean", aliases: Object.freeze([] as string[]) }), + "required_integer": Object.freeze({ canonicalName: "required_integer", wireName: "required_integer", aliases: Object.freeze([] as string[]) }), + "optional_integer": Object.freeze({ canonicalName: "optional_integer", wireName: "optional_integer", aliases: Object.freeze([] as string[]) }), + "required_long": Object.freeze({ canonicalName: "required_long", wireName: "required_long", aliases: Object.freeze([] as string[]) }), + "optional_long": Object.freeze({ canonicalName: "optional_long", wireName: "optional_long", aliases: Object.freeze([] as string[]) }), + "required_decimal": Object.freeze({ canonicalName: "required_decimal", wireName: "required_decimal", aliases: Object.freeze([] as string[]) }), + "optional_decimal": Object.freeze({ canonicalName: "optional_decimal", wireName: "optional_decimal", aliases: Object.freeze([] as string[]) }), + "required_float": Object.freeze({ canonicalName: "required_float", wireName: "required_float", aliases: Object.freeze([] as string[]) }), + "optional_float": Object.freeze({ canonicalName: "optional_float", wireName: "optional_float", aliases: Object.freeze([] as string[]) }), + "required_double": Object.freeze({ canonicalName: "required_double", wireName: "required_double", aliases: Object.freeze([] as string[]) }), + "optional_double": Object.freeze({ canonicalName: "optional_double", wireName: "optional_double", aliases: Object.freeze([] as string[]) }), + "required_date": Object.freeze({ canonicalName: "required_date", wireName: "required_date", aliases: Object.freeze([] as string[]) }), + "optional_date": Object.freeze({ canonicalName: "optional_date", wireName: "optional_date", aliases: Object.freeze([] as string[]) }), + "required_time": Object.freeze({ canonicalName: "required_time", wireName: "required_time", aliases: Object.freeze([] as string[]) }), + "optional_time": Object.freeze({ canonicalName: "optional_time", wireName: "optional_time", aliases: Object.freeze([] as string[]) }), + "required_datetime": Object.freeze({ canonicalName: "required_datetime", wireName: "required_datetime", aliases: Object.freeze([] as string[]) }), + "optional_datetime": Object.freeze({ canonicalName: "optional_datetime", wireName: "optional_datetime", aliases: Object.freeze([] as string[]) }), + "create_time": Object.freeze({ canonicalName: "create_time", wireName: "create_time", aliases: Object.freeze([] as string[]) }), + "update_time": Object.freeze({ canonicalName: "update_time", wireName: "update_time", aliases: Object.freeze([] as string[]) }), + "version": Object.freeze({ canonicalName: "version", wireName: "version", aliases: Object.freeze([] as string[]) }) + }), + }) + }), +}); + +/** Passive generated metadata manifest. It never modifies the database schema. */ +export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { + "TypePlatform": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if ((mutation.action === "Create" && mutation.payload["name"] === undefined) || mutation.payload["name"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("name") }); + if (mutation.payload["name"] != null && [...String(mutation.payload["name"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("name"), inputValue: mutation.payload["name"], systemValue: 100 }); + + + }, + }, + "ScalarTypeProbe": { + checkAndFix(context, mutation, results) { + const now = context.getResource("fixTime"); + if (mutation.action === "Create" && mutation.payload["create_time"] == null) { + mutation.payload["create_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "create_time", source: "clock", sourceLabel: "graphClock" }); + } + + if (mutation.action === "Create" && mutation.payload["update_time"] == null) { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + if (mutation.action === "Update") { + mutation.payload["update_time"] = now; + context.recordFixEvidence({ entityType: "ScalarTypeProbe", modelPath: "update_time", source: "clock", sourceLabel: "graphClock" }); + } + + + if ((mutation.action === "Create" && mutation.payload["type_platform"] === undefined) || mutation.payload["type_platform"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("type_platform") }); + + if ((mutation.action === "Create" && mutation.payload["required_string"] === undefined) || mutation.payload["required_string"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_string") }); + if (mutation.payload["required_string"] != null && [...String(mutation.payload["required_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("required_string"), inputValue: mutation.payload["required_string"], systemValue: 100 }); + + if (mutation.payload["optional_string"] != null && [...String(mutation.payload["optional_string"])].length > 100) results.push({ ruleId: "max_length", location: ObjectLocation.property("optional_string"), inputValue: mutation.payload["optional_string"], systemValue: 100 }); + + + if ((mutation.action === "Create" && mutation.payload["required_boolean"] === undefined) || mutation.payload["required_boolean"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_boolean") }); + + + if ((mutation.action === "Create" && mutation.payload["required_integer"] === undefined) || mutation.payload["required_integer"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_integer") }); + + + if ((mutation.action === "Create" && mutation.payload["required_long"] === undefined) || mutation.payload["required_long"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_long") }); + + + if ((mutation.action === "Create" && mutation.payload["required_decimal"] === undefined) || mutation.payload["required_decimal"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_decimal") }); + + + if ((mutation.action === "Create" && mutation.payload["required_float"] === undefined) || mutation.payload["required_float"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_float") }); + + + if ((mutation.action === "Create" && mutation.payload["required_double"] === undefined) || mutation.payload["required_double"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_double") }); + + + if ((mutation.action === "Create" && mutation.payload["required_date"] === undefined) || mutation.payload["required_date"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_date") }); + + + if ((mutation.action === "Create" && mutation.payload["required_time"] === undefined) || mutation.payload["required_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_time") }); + + + if ((mutation.action === "Create" && mutation.payload["required_datetime"] === undefined) || mutation.payload["required_datetime"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("required_datetime") }); + + + if ((mutation.action === "Create" && mutation.payload["create_time"] === undefined) || mutation.payload["create_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("create_time") }); + + if ((mutation.action === "Create" && mutation.payload["update_time"] === undefined) || mutation.payload["update_time"] === null) results.push({ ruleId: "required", location: ObjectLocation.property("update_time") }); + + + }, + } +}, { ...{ + defaultDomainRoot: { entity: "TypePlatform", id: "1", values: { "name": "Scalar Type Conformance" } }, + constants: [] +}, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-node-sql.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-node-sql.ts new file mode 100644 index 0000000000000000000000000000000000000000..7f5d108d228a1dbec1140e735022c1d72d704eb6 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-node-sql.ts @@ -0,0 +1,16 @@ +import { EntitySchema } from "teaql-ts/sql/core"; + +export const ENTITY_SCHEMAS: Record = { +"TypePlatform": { + table: "type_platform_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"scalarTypeProbeList": { targetEntity: "ScalarTypeProbe", localKey: "id", foreignKey: "typePlatform", many: true }} +}, +"ScalarTypeProbe": { + table: "scalar_type_probe_data", + auditMaskFields: [], + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "typePlatform": { columnName: "type_platform", modelName: "type_platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "requiredString": { columnName: "required_string", modelName: "required_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "optionalString": { columnName: "optional_string", modelName: "optional_string", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "largeText": { columnName: "large_text", modelName: "large_text", logPolicy: "plain", logicalType: "text", decode: "native", nullable: true }, "requiredBoolean": { columnName: "required_boolean", modelName: "required_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "optionalBoolean": { columnName: "optional_boolean", modelName: "optional_boolean", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: true }, "requiredInteger": { columnName: "required_integer", modelName: "required_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "optionalInteger": { columnName: "optional_integer", modelName: "optional_integer", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: true, integer32: true }, "requiredLong": { columnName: "required_long", modelName: "required_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: false }, "optionalLong": { columnName: "optional_long", modelName: "optional_long", logPolicy: "plain", logicalType: "long", decode: "long", nullable: true }, "requiredDecimal": { columnName: "required_decimal", modelName: "required_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "optionalDecimal": { columnName: "optional_decimal", modelName: "optional_decimal", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: true }, "requiredFloat": { columnName: "required_float", modelName: "required_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalFloat": { columnName: "optional_float", modelName: "optional_float", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDouble": { columnName: "required_double", modelName: "required_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: false }, "optionalDouble": { columnName: "optional_double", modelName: "optional_double", logPolicy: "plain", logicalType: "double", decode: "number", nullable: true }, "requiredDate": { columnName: "required_date", modelName: "required_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "optionalDate": { columnName: "optional_date", modelName: "optional_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: true }, "requiredTime": { columnName: "required_time", modelName: "required_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: false }, "optionalTime": { columnName: "optional_time", modelName: "optional_time", logPolicy: "plain", logicalType: "time", decode: "time", nullable: true }, "requiredDatetime": { columnName: "required_datetime", modelName: "required_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "optionalDatetime": { columnName: "optional_datetime", modelName: "optional_datetime", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: true }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + relations: {"typePlatform": { targetEntity: "TypePlatform", localKey: "typePlatform", foreignKey: "id", many: false }} +} +}; \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-node-sqlite.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-node-sqlite.ts new file mode 100644 index 0000000000000000000000000000000000000000..bc3ded598b7e15ab43f23ad385e5ced318843a32 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-node-sqlite.ts @@ -0,0 +1,14 @@ +import { + SQLiteDriver, + SQLiteTeaQLClient as RuntimeSQLiteTeaQLClient +} from "teaql-ts/sql/sqlite"; +import { GENERATED_RUNTIME_MODULE } from "./runtime-module"; + +export { SQLiteDriver } from "teaql-ts/sql/sqlite"; + +export class SQLiteTeaQLClient extends RuntimeSQLiteTeaQLClient { + constructor(filename: string) { + super(filename, {}); + this.install(GENERATED_RUNTIME_MODULE); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-ts.ts b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-ts.ts new file mode 100644 index 0000000000000000000000000000000000000000..9983b00b27c90dc429fca76441f2bf077f825921 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/src/teaql-ts.ts @@ -0,0 +1,518 @@ +import { + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, + SelectQuery as RuntimeSelectQuery, UserContext, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, +} from "teaql-ts"; + +export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; +export type { EntityKey } from "teaql-ts"; +export type { TeaQLPage } from "teaql-ts"; +import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; + +function soundex(input: unknown): string { + const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); + if (!text) return ""; + const code = (char: string): string => "BFPV".includes(char) ? "1" + : "CGJKQSXZ".includes(char) ? "2" : "DT".includes(char) ? "3" + : char === "L" ? "4" : "MN".includes(char) ? "5" : char === "R" ? "6" : ""; + let result = text[0], previous = code(text[0]); + for (const char of text.slice(1)) { + const current = code(char); + if (current && current !== previous) result += current; + previous = current; + if (result.length === 4) break; + } + return (result + "000").slice(0, 4); +} + +/** Generated naming adapter; query policy and execution remain in the formal runtime. */ +export class SelectQuery extends RuntimeSelectQuery { + orderBy(field: string, direction: string): this { + return this.order({ field, expr: null, direction: direction === "desc" ? "Desc" : "Asc" } as any); + } + + relationQuery( + name: string, query: RuntimeSelectQuery, localKey = "id", foreignKey = "id", many = true, + operation?: QueryOperation, + ): this { + return super.relationQuery(name, query, localKey, foreignKey, many, operation); + } +} + +export interface TeaQLDataService { + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; + preflightMutation(mutation: any): any; + afterGraphCommit(work: () => void): void; + afterGraphRollback(work: () => void): void; + executeMutation(mutation: any): Promise; + executeQuery(query: any): Promise; + executeCount(query: any, alias?: string, operation?: QueryOperation): Promise; + executeForStream(query: any, chunkSize?: number): AsyncIterable; + close?(): Promise; +} + +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { + private data: Record> = {}; + private nextIds: Record = {}; + private readonly checkers: Record = {}; + private readonly schemas: Record = {}; + private userContext = new UserContext(); + private graphSaveActive = false; + private activeGraph?: GraphMutationSession; + private graphCommitActions: Array<() => void> = []; + private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; + private graphSaveTail: Promise = Promise.resolve(); + private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; + + constructor(private storagePath?: string) { + super(); + if (storagePath) { + const fs = require("fs"); + if (fs.existsSync(storagePath)) { + const state = JSON.parse(fs.readFileSync(storagePath, "utf8")); + this.data = state.data || {}; + this.nextIds = state.nextIds || {}; + } + } + } + + /** Installs passive generated metadata. It never mutates storage. */ + install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); + Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); + return this; + } + + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + + setUserContext(context: UserContext): this { + this.userContext = context; + return this; + } + + get mutationGovernanceTrace(): readonly any[] { + return [...this.mutationGovernanceEvents]; + } + + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + + private persist() { + if (!this.storagePath) return; + const fs = require("fs"); + const path = require("path"); + fs.mkdirSync(path.dirname(path.resolve(this.storagePath)), { recursive: true }); + const temporaryPath = `${this.storagePath}.tmp`; + fs.writeFileSync(temporaryPath, JSON.stringify({ data: this.data, nextIds: this.nextIds })); + fs.renameSync(temporaryPath, this.storagePath); + } + + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { + const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const dataSnapshot = JSON.parse(JSON.stringify(this.data)); + const nextIdsSnapshot = { ...this.nextIds }; + let fixEvidenceStarted = false; + let mutationPolicyGraphStarted = false; + let committed = false; + try { + graph.validatePreparedSources(); + this.graphSaveActive = true; + this.activeGraph = graph; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); + mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); + const result = await work(graph); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); + return result; + } catch (error) { + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } + throw error; + } finally { + this.graphSaveActive = false; + this.activeGraph = undefined; + this.graphCommitActions = []; + this.graphRollbackActions = []; + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); + release(); + } + } + + afterGraphCommit(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphCommitActions.push(work); + } + + afterGraphRollback(work: () => void): void { + if (!this.graphSaveActive) throw new Error("No graph save is active"); + this.graphRollbackActions.push(work); + } + + preflightMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); + return mutation; + } + + private checkAndFixMutation(mutation: any): any { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); + mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } + const results: any[] = []; + const ownsFixTime = this.userContext.getResource("fixTime") === undefined; + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); + try { + checker.checkAndFix(this.userContext, mutation, results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); + if (results.length) throw new CheckException(results); + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); + } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } + } + + async executeMutation(mutation: any): Promise { + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); + const mutationGovernance = this.userContext.enterMutationPolicy(mutation); + const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); + if (mutation.action === "Create") { + const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; + table[String(id)] = record; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); + } + if (["Update", "Delete", "Recover"].includes(mutation.action)) { + const id = String(mutation.id); + if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { + throw new Error( + `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); + } + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; + if (!this.graphSaveActive) this.persist(); + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); + } + throw new Error(`Unsupported mutation action: ${mutation.action}`); + } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } + async query(context: any, req: any): Promise { + return { rows: [] }; + } + async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; + if (!(query instanceof RuntimeSelectQuery)) { + throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); + } + query.prepareForList(); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); + const matches = (row: any, expression: any): boolean => { + if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); + return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); + if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); + if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); + if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); + if (predicate?.$notStartsWith !== undefined) return !String(row[field] ?? "").startsWith(String(predicate.$notStartsWith)); + if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); + if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); + if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; + if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; + return true; + }); + }; + if (query.filterCondition) rows = rows.filter(row => matches(row, query.filterCondition)); + if (query.aggregateItems?.length) { + return [Object.fromEntries(query.aggregateItems.map((aggregate: any) => { + if (String(aggregate.function).toLowerCase() !== "count") { + throw new Error(`Unsupported local aggregate: ${aggregate.function}`); + } + return [aggregate.alias, rows.length]; + }))]; + } + for (const order of [...query.orderItems].reverse()) { + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + } + const start = query.offsetValue || 0; + rows = rows.slice(start, start + query.limitValue); + for (const relation of (query.relations || []) as any[]) { + for (const row of rows) { + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); + row[relation.name] = relation.many === false ? matches[0] : matches; + } + } + if (query.selectItems.length > 0) { + const selections = new Set(query.selectItems); + for (const relation of (query.relations || []) as any[]) selections.add(relation.name); + rows = rows.map((row: any) => Object.fromEntries( + Object.entries(row).filter(([field]) => selections.has(field)))); + } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); + return rows; + } + async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { + if (typeof query?.forExactCount !== "function") { + throw new Error("TeaQL exact count requires the formal runtime SelectQuery"); + } + const alias = countAlias ?? "__teaql_total"; + const request = new QueryRequest(query).deriveOperation(query.forExactCount(alias), operation ?? { + kind: "named-count", ...(countAlias === undefined ? {} : { alias: countAlias }) }); + const rows = await this.executeQuery(request.query); + const value = rows[0]?.[alias]; + if (typeof value !== "number" || !Number.isFinite(value)) { + throw new Error(`TeaQL provider did not return exact count alias ${alias}`); + } + return value; + } + async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; + if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); + const rows = await this.executeQuery(query); + for (let offset = 0; offset < rows.length; offset += chunkSize) { + yield rows.slice(offset, offset + chunkSize); + } + } +} + +declare const require: any; + +export function eq(a: any, b: any) { return {type: 'eq', field: a, value: b}; } +export function contain(a: any, b: any) { return {type: 'contain', field: a, value: b}; } \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/teaql-i18n.json b/source/teaql-ts/examples/expression-profiles/generated/snake_case/teaql-i18n.json new file mode 100644 index 0000000000000000000000000000000000000000..9bccc83b0cb5f837bc4c9ee6a49415974e1a4d50 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/teaql-i18n.json @@ -0,0 +1,127 @@ +{ + "schema": "teaql.i18n/v1", + "defaultLocale": "en", + "locales": { + "de": { + "vocabulary": { + }, + "messages": { + } + }, + "ko": { + "vocabulary": { + }, + "messages": { + } + }, + "pt": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-TW": { + "vocabulary": { + }, + "messages": { + } + }, + "fil": { + "vocabulary": { + }, + "messages": { + } + }, + "en": { + "vocabulary": { + "property.scalarTypeProbe.largeText": "Large Text", + "property.scalarTypeProbe.requiredString": "Required String", + "property.scalarTypeProbe.id": "Id", + "property.scalarTypeProbe.optionalDecimal": "Optional Decimal", + "property.scalarTypeProbe.requiredDate": "Required Date", + "property.scalarTypeProbe.optionalString": "Optional String", + "property.scalarTypeProbe.requiredLong": "Required Long", + "property.typePlatform.version": "Version", + "entity.scalarTypeProbe": "Scalar Type Probe", + "property.scalarTypeProbe.optionalTime": "Optional Time", + "property.scalarTypeProbe.typePlatform": "Type Platform", + "property.scalarTypeProbe.optionalLong": "Optional Long", + "property.scalarTypeProbe.requiredDatetime": "Required Datetime", + "property.scalarTypeProbe.requiredTime": "Required Time", + "property.scalarTypeProbe.optionalBoolean": "Optional Boolean", + "property.scalarTypeProbe.optionalInteger": "Optional Integer", + "property.scalarTypeProbe.requiredDouble": "Required Double", + "entity.typePlatform": "Type Platform", + "property.scalarTypeProbe.requiredInteger": "Required Integer", + "property.scalarTypeProbe.optionalDouble": "Optional Double", + "property.scalarTypeProbe.optionalDatetime": "Optional Datetime", + "property.scalarTypeProbe.createTime": "Create Time", + "property.scalarTypeProbe.requiredFloat": "Required Float", + "property.typePlatform.id": "Id", + "property.scalarTypeProbe.requiredDecimal": "Required Decimal", + "property.scalarTypeProbe.optionalFloat": "Optional Float", + "property.scalarTypeProbe.version": "Version", + "property.scalarTypeProbe.requiredBoolean": "Required Boolean", + "property.scalarTypeProbe.updateTime": "Update Time", + "property.typePlatform.name": "Name", + "property.scalarTypeProbe.optionalDate": "Optional Date" + }, + "messages": { + } + }, + "fr": { + "vocabulary": { + }, + "messages": { + } + }, + "zh-CN": { + "vocabulary": { + }, + "messages": { + } + }, + "es": { + "vocabulary": { + }, + "messages": { + } + }, + "ar": { + "vocabulary": { + }, + "messages": { + } + }, + "vi": { + "vocabulary": { + }, + "messages": { + } + }, + "th": { + "vocabulary": { + }, + "messages": { + } + }, + "uk": { + "vocabulary": { + }, + "messages": { + } + }, + "ja": { + "vocabulary": { + }, + "messages": { + } + }, + "id": { + "vocabulary": { + }, + "messages": { + } + } + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/generated/snake_case/tsconfig.json b/source/teaql-ts/examples/expression-profiles/generated/snake_case/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..18139f743ca48c921f9a21e51be3b1485651513c --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/generated/snake_case/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "es2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "declaration": true + }, + "include": ["src/**/*", "*.d.ts"] +} \ No newline at end of file diff --git a/source/teaql-ts/examples/expression-profiles/main.test.ts b/source/teaql-ts/examples/expression-profiles/main.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..6d307bf876bb82ce7d960be94db57ad02e8b00fd --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/main.test.ts @@ -0,0 +1,55 @@ +import { Q } from 'scalar-lib/generated/Q'; +import { E } from 'scalar-lib/generated/E'; +import { SQLiteTeaQLClient } from 'scalar-lib/teaql-node-sqlite'; +import { TeaQLNotLoadedError, UserContext } from 'teaql-ts'; +import { expect, jest, test } from '@jest/globals'; + +test('generated E uses the selected model profile without an application override', async () => { + const profile = process.env.TEAQL_EXPRESSION_PROFILE as 'camelCase' | 'snake_case' | 'PascalCase'; + const pointer = { camelCase: '/scalarTypeProbeList', snake_case: '/scalar_type_probe_list', PascalCase: '/ScalarTypeProbeList' }[profile]; + const suffix = { camelCase: '/0/requiredString', snake_case: '/0/required_string', PascalCase: '/0/RequiredString' }[profile]; + expect(pointer).toBeDefined(); + const client = new SQLiteTeaQLClient(process.env.TEAQL_EXPRESSION_DB!); + const context = new UserContext().insertResource('dataService', client); + const query = jest.spyOn((client as any).driver, 'query'); + const transaction = jest.spyOn((client as any).driver, 'transaction'); + try { + await context.ensureSchema(); + query.mockClear(); transaction.mockClear(); + const row = await Q.typePlatforms().withIdIs('1').limit(1) + .comment('Load the root without its reverse list') + .purpose('Verify generated E diagnostics under the modeled JSON profile').executeForOne(context); + expect(row).toBeDefined(); + expect(String(E.typePlatform(row!).id().eval())).toBe('1'); + const name = E.typePlatform(row!).name().eval(); + const calibrated = { query: query.mock.calls.length, transaction: transaction.mock.calls.length, audit: client.auditTrace.length }; + expect(calibrated.query).toBeGreaterThan(0); + let diagnostic: { wire: ReturnType; human: string } | undefined; + try { E.typePlatform(row!).scalarTypeProbeList().first().requiredString().eval(); } + catch (error) { + if (!(error instanceof TeaQLNotLoadedError)) throw error; + diagnostic = { wire: error.toWire(), human: error.message }; + } + expect(diagnostic).toBeDefined(); + const { wire, human } = diagnostic!; + const location = [{ kind: 'property', name: 'scalar_type_probe_list' }]; + expect(wire.code).toBe('NOT_LOADED'); + expect(wire.location).toEqual(location); + expect(wire.suggestedFix).toEqual({ action: 'preload', location }); + expect(wire.attemptedLocation).toEqual([...location, { kind: 'index', index: 0 }, { kind: 'property', name: 'required_string' }]); + expect(wire.instancePath).toBe(pointer); expect(wire.attemptedInstancePath).toBe(pointer! + suffix); + expect(wire.breakPoint).toBe('scalar_type_probe_list'); expect(wire.breakPointIndex).toBe(0); + expect(wire.originalExpression).toBe('E.typePlatform().scalarTypeProbeList().first().requiredString().eval()'); + expect(wire.expressionWithBrokenPoint).toBe('E.typePlatform().scalarTypeProbeList().first().requiredString().eval()'); + expect(human.startsWith('TeaQLNotLoadedError:')).toBe(true); + expect(human).toContain('expression=' + wire.expressionWithBrokenPoint); + expect(human).not.toContain('"instancePath"'); + expect({ query: query.mock.calls.length, transaction: transaction.mock.calls.length, audit: client.auditTrace.length }).toEqual(calibrated); + expect(E.typePlatform(row!).name().eval()).toBe(name); + process.stdout.write('GENERATED_E_MODEL_PROFILE=' + JSON.stringify({ + language: 'typescript', profile, round: Number(process.env.TEAQL_EXPRESSION_ROUND), passed: true, + wire, human, providerEntries: 0, queryCalibration: calibrated.query, selectedNameUnchanged: true, + runtimeOrigin: require.resolve('teaql-ts'), + }) + '\n'); + } finally { await client.close(); } +}); diff --git a/source/teaql-ts/examples/expression-profiles/provenance.json b/source/teaql-ts/examples/expression-profiles/provenance.json new file mode 100644 index 0000000000000000000000000000000000000000..3b7b2c2db1e0c880c9a6fea486219582aa7d009c --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/provenance.json @@ -0,0 +1,12 @@ +{ + "producerReportSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "manifestSha256": "46ea37da8b663e8d4e8842dbf1633dfa20134e0787f427b8116696997c346bdb", + "producer": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "generatorCommit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "generatorSourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937", + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousManifestSha256": "4e8a121b68777b55cbc5209576f47c831ca9a756718411870b072a083177fd1b" +} diff --git a/source/teaql-ts/examples/expression-profiles/verify-local.cjs b/source/teaql-ts/examples/expression-profiles/verify-local.cjs new file mode 100644 index 0000000000000000000000000000000000000000..38ef11020fcbe93ab98147a9d61404bf8fdb5bb7 --- /dev/null +++ b/source/teaql-ts/examples/expression-profiles/verify-local.cjs @@ -0,0 +1,76 @@ +#!/usr/bin/env node +'use strict'; +const fs=require('node:fs'),path=require('node:path'),os=require('node:os'),cp=require('node:child_process'),crypto=require('node:crypto'),assert=require('node:assert/strict'); +const {createOwnedRunner,ownedBytes}=require('../fix-e-alignment/owned-command.cjs'); +const EXAMPLE=__dirname,REPO=path.resolve(EXAMPLE,'../..'),PROFILES=['camelCase','snake_case','PascalCase'],LANGUAGE="typescript"; +const ORIGIN=path.resolve(process.env.TEAQL_TYPESCRIPT_EXAMPLE_SOURCE_ROOT||REPO); +const sha=b=>crypto.createHash('sha256').update(b).digest('hex'),digest=f=>sha(fs.readFileSync(f)); +function sourceHash(root=REPO){ + assert.equal(fs.realpathSync(root),root,'source root cannot be a symlink alias'); + const names=[...new Set(cp.execFileSync('git',['-C',ORIGIN,'ls-files','-z','--cached','--others','--exclude-standard']).toString().split('\0').filter(Boolean))].sort(),h=crypto.createHash('sha256'); + for(const n of names){assert(!path.isAbsolute(n)&&!n.split('/').includes('..'));const f=path.join(root,n);h.update(n+'\0');assert.equal(fs.realpathSync(f),f);const s=fs.lstatSync(f);assert(s.isFile()&&!s.isSymbolicLink());h.update(String(s.mode)+'\0');h.update(fs.readFileSync(f));h.update('\0');}return h.digest('hex'); +} +function sourceIdentity(){ + const body=sourceHash();assert.equal(body,sourceHash(ORIGIN),'isolated runtime must match its real Git origin before execution'); + return{commit:cp.execFileSync('git',['-C',ORIGIN,'rev-parse','HEAD'],{encoding:'utf8'}).trim(),sourceContentsSha256:body}; +} +function fixture(){ + const root=path.join(EXAMPLE,'generated'),manifest=JSON.parse(fs.readFileSync(path.join(root,'manifest.json'))),provenance=JSON.parse(fs.readFileSync(path.join(EXAMPLE,'provenance.json'))); + assert.equal(manifest.schema,'teaql.generated-expression-model-profiles/v1');assert.equal(manifest.language,"typescript");assert.equal(manifest.localSourceOnly,true); + assert.equal(digest(path.join(root,'manifest.json')),provenance.manifestSha256);assert.deepEqual(Object.keys(manifest.profiles).sort(),[...PROFILES].sort()); + for(const[p,v]of Object.entries(manifest.profiles)){assert.deepEqual(v.evaluation.errors,[]);assert.equal(digest(path.join(root,p,'model.xml')),v.modelSha256); + for(const[n,h]of Object.entries(v.files)){const f=path.resolve(root,p,n);assert(f.startsWith(path.join(root,p)+path.sep));assert.equal(fs.realpathSync(f),f);assert.equal(digest(f),h);}} + return{manifest,provenance,provenanceSha256:digest(path.join(EXAMPLE,'provenance.json'))}; +} +async function main(){ + const requested=process.env.TEAQL_GENERATED_E_PROFILE_EVIDENCE_DIR,output=requested?path.resolve(requested):fs.mkdtempSync(path.join(os.tmpdir(),'teaql-'+LANGUAGE+'-expression-evidence-')); + if(requested){assert(path.isAbsolute(requested)&&!fs.existsSync(output));fs.mkdirSync(output,{recursive:true});} + const report={schema:'teaql.'+LANGUAGE+'-generated-e-model-profiles/v1',passed:false,localSourceOnly:true,publicPublication:false,installedArtifactAccepted:false,completeExampleInventoryAccepted:false,allP0P1Complete:false,commands:[],profiles:{}}; + let scratch,runner; + try{ + const disk=fs.statfsSync(os.tmpdir());assert(disk.bavail*disk.bsize>8*1024**3); + report.sourceBefore=sourceIdentity();report.executionSource={path:REPO,origin:ORIGIN,sourceContentsSha256:report.sourceBefore.sourceContentsSha256};report.fixture=fixture();report.controllerSha256=digest(__filename); + scratch=fs.mkdtempSync(path.join(os.tmpdir(),'teaql-'+LANGUAGE+'-expression-build-'));runner=createOwnedRunner(); + const env={...process.env,TMPDIR:scratch}; + async function run(profile,name,command,cwd,timeout=300000){ + const folder=path.join(output,profile);fs.mkdirSync(folder,{recursive:true});const file=path.join(folder,name+'.log'),fd=fs.openSync(file,'wx');let result; + try{result=await runner.run(command,{cwd,env,timeout,stdio:['ignore',fd,fd]});}finally{fs.closeSync(fd);} + const log=fs.readFileSync(file,'utf8');report.commands.push({profile,name,command,exitCode:result.status,signal:result.signal,logSha256:digest(file)}); + assert.equal(result.status,0,log.slice(-6000));assert.equal(result.signal,null);assert(runner.safeToClean);return log; + } + for(const profile of PROFILES){ + const work=path.join(scratch,profile);fs.mkdirSync(work);env.TEAQL_EXPRESSION_PROFILE=profile;env.TEAQL_EXPRESSION_DB=path.join(output,profile,'fixture.sqlite'); + fs.mkdirSync(path.join(output,profile));const state={rounds:[],sameDatabase:true};report.profiles[profile]=state; + + report.applicationSha256=digest(path.join(EXAMPLE,'main.test.ts')); + const runtime=path.join(scratch,'source'),example=path.join(runtime,'examples/expression-profiles'); + if(profile==='camelCase'){ + const names=[...new Set(cp.execFileSync('git',['-C',ORIGIN,'ls-files','-z','--cached','--others','--exclude-standard']).toString().split('\0').filter(Boolean))]; + for(const n of names){const from=path.join(REPO,n);if(!fs.existsSync(from))continue;assert(fs.lstatSync(from).isFile());const to=path.join(runtime,n);fs.mkdirSync(path.dirname(to),{recursive:true});fs.copyFileSync(from,to);fs.chmodSync(to,fs.statSync(from).mode&0o777);} + assert.equal(sourceHash(runtime),report.sourceBefore.sourceContentsSha256);report.runtimeSourceCopy={path:runtime,origin:REPO,sourceContentsSha256:sourceHash(runtime)}; + await run(profile,'dependencies',['npm','ci','--offline','--no-audit','--fund=false'],runtime); + assert.equal(sourceHash(runtime),report.sourceBefore.sourceContentsSha256); + } + const tsconfig=path.join(work,'tsconfig.json'),config=path.join(work,'jest.cjs'),generated=path.join(example,'generated',profile,'src'); + fs.writeFileSync(tsconfig,JSON.stringify({extends:path.join(runtime,'tsconfig.json'),compilerOptions:{types:['node','jest'],typeRoots:[path.join(runtime,'node_modules/@types')],baseUrl:runtime,paths:{'teaql-ts':[path.join(runtime,'src/index.ts')],'teaql-ts/*':[path.join(runtime,'src/*')],'scalar-lib/*':[path.join(generated,'*')]}}})); + fs.writeFileSync(config,'module.exports='+JSON.stringify({rootDir:runtime,roots:[example],testEnvironment:'node',testMatch:['**/examples/expression-profiles/main.test.ts'],modulePathIgnorePatterns:PROFILES.filter(p=>p!==profile).map(p=>path.join(example,'generated',p)), + moduleNameMapper:{'^teaql-ts$':path.join(runtime,'src/index.ts'),'^teaql-ts/(.*)$':path.join(runtime,'src/$1'),'^scalar-lib/(.*)$':path.join(generated,'$1')}, + transform:{'^.+\\.tsx?$':['ts-jest',{tsconfig}]}})+';\n'); + for(const round of[1,2]){env.TEAQL_EXPRESSION_ROUND=String(round);const log=await run(profile,'round-'+round,[process.execPath,path.join(runtime,'node_modules/jest/bin/jest.js'),'--config',config,'--runInBand','--cacheDirectory',path.join(scratch,'jest')],runtime); + const rows=[...log.matchAll(/^GENERATED_E_MODEL_PROFILE=(.+)$/gm)].map(m=>JSON.parse(m[1]));assert.equal(rows.length,1);const v=rows[0]; + assert.equal(v.passed,true);assert.equal(v.profile,profile);assert.equal(v.round,round);assert.equal(v.providerEntries,0);assert(v.queryCalibration>0); + assert.equal(v.runtimeOrigin,path.join(runtime,'src/index.ts'));state.rounds.push(v); + } + + state.databaseSha256=digest(env.TEAQL_EXPRESSION_DB);assert.deepEqual(fixture(),report.fixture);assert.equal(sourceHash(),report.sourceBefore.sourceContentsSha256);assert.equal(sourceHash(runtime),report.sourceBefore.sourceContentsSha256); + } + assert.deepEqual(sourceIdentity(),report.sourceBefore);report.passed=true; + }catch(error){report.error=error.stack;console.error(error.stack);process.exitCode=1;} + finally{ + const safe=!runner||runner.safeToClean;report.cleanup={scratchRemoved:false,disposedOwnedBytes:safe&&scratch?ownedBytes(scratch):0,sharedCachesDeleted:false,databasesDeleted:false}; + if(safe&&scratch){fs.rmSync(scratch,{recursive:true});report.cleanup.scratchRemoved=true;}else if(scratch)report.unsafeRetention=scratch; + runner?.dispose();report.sourceAfter=sourceHash();fs.writeFileSync(path.join(output,'report.json'),JSON.stringify(report,null,2)+'\n',{flag:'wx'});console.log(JSON.stringify({output,passed:report.passed,cleanup:report.cleanup})); + } +} +if(require.main===module)main().catch(e=>{console.error(e.stack);process.exitCode=1;}); +module.exports={sourceHash,sourceIdentity,ORIGIN,REPO}; diff --git a/source/teaql-ts/examples/facet-trace/consumer.ts b/source/teaql-ts/examples/facet-trace/consumer.ts index f8d1ae26df1ea3009b54f4f38d81deba13d96bee..87a099ec253affdbde7b317faf5051f8ba859ab4 100644 --- a/source/teaql-ts/examples/facet-trace/consumer.ts +++ b/source/teaql-ts/examples/facet-trace/consumer.ts @@ -91,7 +91,7 @@ async function main() { const existing = await Q.schools().withNameIs(name).limit(1) .comment('find retained fixture').purpose('idempotent seed').executeForList(context); if (!existing.length) { - const school = Q.schools().comment('initialize fixture').purpose('idempotent seed').newEntity(context); + const school = (await Q.schools().comment('initialize fixture').purpose('idempotent seed').newEntity(context)); school.updatePlatform('1').updateSchoolType('1001').updateName(name) .updateAddress('12 River Road').updateEstablishedDate('1995-09-01') .updateStudentCapacity(800).updateActive(true); diff --git a/source/teaql-ts/examples/facet-trace/lib/current-generator-fixture.json b/source/teaql-ts/examples/facet-trace/lib/current-generator-fixture.json new file mode 100644 index 0000000000000000000000000000000000000000..32e80985b1d33e60d9b55096c0ec89b8b0cdb946 --- /dev/null +++ b/source/teaql-ts/examples/facet-trace/lib/current-generator-fixture.json @@ -0,0 +1,32 @@ +{ + "schema": "teaql.typescript-current-example-fixture/v1", + "modelSha256": "9fc6724c828e10aca8cea9f53b65460f26577f74ba5396f04376ad4f20ddc30e", + "scope": "typescript-lib-core", + "producerReceiptSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "files": { + "src/generated/Q.ts": "96e150775a079420a4afb57d5be8e9b7696d2b8d8bef6eee3727c2b530b3dd33", + "src/generated/requests/PlatformRequest.ts": "9688521d546f907faeefb35b76dda49247ccaef6dca034ae9624036766cdbb60", + "src/generated/requests/SchoolTypeRequest.ts": "98ebdc64f9889386dc835f5dd1c1c76854b2c2a653221cd06f5c34521c50d118", + "src/generated/requests/SchoolRequest.ts": "ce09fa5542c811f68fe58fde72367c298c8b46a190e26b7c96594a01c787bdb5", + "src/generated/E.ts": "79a54bc6bf0470b6f62c4b00b45ee27d8b23c706bc39365c138dc1eeab0f7d53", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "3d596870c683b14ea9ca4cc930216cec647e6b216b1b7a073b573626293ce4a5", + "src/teaql-schemas.ts": "fd40553b01ce0165ae02f315e16b4aeeb7ee78a688f40a55f04e52f8547fb9a9", + "src/runtime-module.ts": "3bdea1228818d5e81c888cb61426c6688c9bd510449a25d2032bdee07a95c6ae", + "src/generated-bootstrap.ts": "75c847ca2b29ca42a4520a6cf83d5d72df1ecc15a56fff00bc6e8f44953486c5", + "src/generated/models/Platform.ts": "1424aff7c56193ee94d3ef2ade6e48268a06234b830eca23e5e6401d069eb09d", + "src/generated/models/SchoolType.ts": "c0ae70c638ddc08f2ad1347a12c53013e5ac969ff07834c9b8c648a344784f08", + "src/generated/models/School.ts": "8e104213e38082dc700eabbae024172d61fd00cf1ccb5d36484042ca811337b7" + }, + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "previousFixtureManifestSha256": "47cb1cd593ec571f6fe9f26d08d4a72f4873e91e8a8d5a7e5542dfb65568d1a6", + "previousSourceGuard": { + "accepted": true, + "sourceCommit": "dda8add95e6e5402fe1155ecbd68ad8427d7ac29", + "differences": [] + } +} diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts index d3da68070cb03b66985d084711a3d4e417fb6d5a..d52b51f063d2e55d6b28c5187bdeceeb2b71aa9a 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated-bootstrap.ts @@ -1,4 +1,4 @@ -import { UserContext } from './teaql-ts'; +import { UserContext, decimal, long, localTime } from './teaql-ts'; import { Q } from './generated/Q'; import { Platform } from './generated/models/Platform'; import { SchoolType } from './generated/models/SchoolType'; @@ -7,7 +7,7 @@ import { SchoolType } from './generated/models/SchoolType'; export async function ensureGeneratedBootstrap(context: UserContext): Promise { let domainRoot = (await Q.platforms().withIdIs('1').comment('what: locate generated Domain Root').purpose('why: idempotent runtime bootstrap').executeForList(context))[0]; if (!domainRoot) { - domainRoot = Platform.teaqlBootstrapNew('1'); + domainRoot = Platform.teaqlBootstrapNew(context, '1'); domainRoot.updateName("Campus Learning Platform"); domainRoot.updateBaseUrl("https://campus.example.com"); await domainRoot.auditAs('create generated Domain Root Platform').save(context); @@ -15,34 +15,34 @@ export async function ensureGeneratedBootstrap(context: UserContext): Promise; - - constructor( - readonly root: string, - readonly accessPath: string, - readonly breakPoint: string, - ) { - const suggestedFix = `select${breakPoint.charAt(0).toUpperCase()}${breakPoint.slice(1)}(...)`; - const details = { - error: 'TeaQLNotLoadedError', - root, - accessPath: accessPath.split('.'), - breakPoint, - missingPreload: [breakPoint], - suggestedFix, - severity: 'error', - humanMessage: `访问 ${root}.${accessPath} 时缺少预加载。请在查询中加入 ${suggestedFix}`, - }; - super(JSON.stringify(details)); - this.name = 'TeaQLNotLoadedError'; - this.details = details; - } -} - -function expressionPath(prefix: string, field: string): string { - return prefix ? `${prefix}.${field}` : field; -} +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; export class ValueExpression { constructor( private readonly value: T | null | undefined, private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, ) {} static missing(): ValueExpression { @@ -46,18 +21,26 @@ export class ValueExpression { return new ValueExpression(undefined, false, error); } + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + eval(): T | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; return this.present ? this.value : undefined; } isPresent(): boolean { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; return this.present; } orElse(fallback: T): T { - const value = this.eval(); + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; return this.present && value != null ? value : fallback; } } @@ -66,98 +49,98 @@ export class PlatformExpression { constructor( private readonly value: Platform | null | undefined, private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.platform()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): Platform | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } baseUrl(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('base_url', 'baseUrl'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'baseUrl'); if (!this.value.isLoaded('baseUrl')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'baseUrl'), + new TeaQLNotLoadedError(path.markMissing(), 'base_url'), ); } return new ValueExpression(this.value.baseUrl); } createTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'createTime'); if (!this.value.isLoaded('createTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'createTime'), + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), ); } return new ValueExpression(this.value.createTime); } updateTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'updateTime'); if (!this.value.isLoaded('updateTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'updateTime'), + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), ); } return new ValueExpression(this.value.updateTime); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } schoolTypeList(): SchoolTypeListExpression { - const path = expressionPath(this.path, 'schoolTypeList'); + const path = this.path.member('school_type_list', 'schoolTypeList'); if (this.notLoaded) { - return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded); + return new SchoolTypeListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolTypeListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolTypeList')) { return new SchoolTypeListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolTypeList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_type_list')); } return new SchoolTypeListExpression( this.value.schoolTypeList(), this.root, path, @@ -165,14 +148,14 @@ export class PlatformExpression { } schoolList(): SchoolListExpression { - const path = expressionPath(this.path, 'schoolList'); + const path = this.path.member('school_list', 'schoolList'); if (this.notLoaded) { - return new SchoolListExpression([], this.root, path, false, this.notLoaded); + return new SchoolListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolList')) { return new SchoolListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_list')); } return new SchoolListExpression( this.value.schoolList(), this.root, path, @@ -184,82 +167,82 @@ export class SchoolTypeExpression { constructor( private readonly value: SchoolType | null | undefined, private readonly root = 'SchoolType(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.schoolType()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): SchoolType | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } code(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('code', 'code'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'code'); if (!this.value.isLoaded('code')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'code'), + new TeaQLNotLoadedError(path.markMissing(), 'code'), ); } return new ValueExpression(this.value.code); } - displayOrder(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'displayOrder'); + displayOrder(): ValueExpression { + const path = this.path.member('display_order', 'displayOrder'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('displayOrder')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'displayOrder'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'display_order'), ); } - return new ValueExpression(this.value.displayOrder); + return new ValueExpression(this.value.displayOrder); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -270,33 +253,35 @@ export class SchoolTypeExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } schoolList(): SchoolListExpression { - const path = expressionPath(this.path, 'schoolList'); + const path = this.path.member('school_list', 'schoolList'); if (this.notLoaded) { - return new SchoolListExpression([], this.root, path, false, this.notLoaded); + return new SchoolListExpression([], this.root, path, false, this.notLoaded.withPath(path)); } if (!this.value) return SchoolListExpression.missing(this.root, path); if (!this.value.isLoaded('schoolList')) { return new SchoolListExpression([], this.root, path, false, - new TeaQLNotLoadedError(this.root, path, 'schoolList')); + new TeaQLNotLoadedError(path.markMissing(), 'school_list')); } return new SchoolListExpression( this.value.schoolList(), this.root, path, @@ -308,130 +293,132 @@ export class SchoolExpression { constructor( private readonly value: School | null | undefined, private readonly root = 'School(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.school()', 'camelCase'), private readonly notLoaded?: TeaQLNotLoadedError, ) {} eval(): School | null | undefined { - if (this.notLoaded) throw this.notLoaded; + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); return this.value; } id(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'id'); if (!this.value.isLoaded('id')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'id'), + new TeaQLNotLoadedError(path.markMissing(), 'id'), ); } return new ValueExpression(this.value.id); } name(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'name'); if (!this.value.isLoaded('name')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'name'), + new TeaQLNotLoadedError(path.markMissing(), 'name'), ); } return new ValueExpression(this.value.name); } address(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('address', 'address'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'address'); if (!this.value.isLoaded('address')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'address'), + new TeaQLNotLoadedError(path.markMissing(), 'address'), ); } return new ValueExpression(this.value.address); } establishedDate(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('established_date', 'establishedDate'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'establishedDate'); if (!this.value.isLoaded('establishedDate')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'establishedDate'), + new TeaQLNotLoadedError(path.markMissing(), 'established_date'), ); } return new ValueExpression(this.value.establishedDate); } studentCapacity(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('student_capacity', 'studentCapacity'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'studentCapacity'); if (!this.value.isLoaded('studentCapacity')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'studentCapacity'), + new TeaQLNotLoadedError(path.markMissing(), 'student_capacity'), ); } + const error = integer32Error(this.value.studentCapacity, 'School', 'student_capacity'); + if (error) return ValueExpression.invalid(error); return new ValueExpression(this.value.studentCapacity); } active(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('active', 'active'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'active'); if (!this.value.isLoaded('active')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'active'), + new TeaQLNotLoadedError(path.markMissing(), 'active'), ); } return new ValueExpression(this.value.active); } createTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'createTime'); if (!this.value.isLoaded('createTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'createTime'), + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), ); } return new ValueExpression(this.value.createTime); } updateTime(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'updateTime'); if (!this.value.isLoaded('updateTime')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'updateTime'), + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), ); } return new ValueExpression(this.value.updateTime); } - version(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); - if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'version'); + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); if (!this.value.isLoaded('version')) { - return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'version'), + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), ); } - return new ValueExpression(this.value.version); + return new ValueExpression(this.value.version); } platformId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('platform', 'platformId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'platform'); if (!this.value.isLoaded('platform')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'platform'), + new TeaQLNotLoadedError(path.markMissing(), 'platform'), ); } const reference = this.value.platform; @@ -442,12 +429,12 @@ export class SchoolExpression { } schoolTypeId(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + const path = this.path.member('school_type', 'schoolTypeId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); if (!this.value) return ValueExpression.missing(); - const path = expressionPath(this.path, 'schoolType'); if (!this.value.isLoaded('schoolType')) { return ValueExpression.notLoaded( - new TeaQLNotLoadedError(this.root, path, 'schoolType'), + new TeaQLNotLoadedError(path.markMissing(), 'school_type'), ); } const reference = this.value.schoolType; @@ -458,40 +445,44 @@ export class SchoolExpression { } platform(): PlatformExpression { - const path = expressionPath(this.path, 'platform'); + const path = this.path.member('platform', 'platform'); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, path, this.notLoaded); + return new PlatformExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new PlatformExpression(undefined, this.root, path); if (!this.value.isLoaded('platform')) { return new PlatformExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'platform')); + new TeaQLNotLoadedError(path.markMissing(), 'platform')); } const relation = this.value.platform; - const target = relation == null - ? undefined - : relation instanceof Platform - ? relation - : Platform.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Platform)) { + return new PlatformExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'platform')); + } + const target = relation instanceof Platform ? relation : undefined; return new PlatformExpression(target, this.root, path); } schoolType(): SchoolTypeExpression { - const path = expressionPath(this.path, 'schoolType'); + const path = this.path.member('school_type', 'schoolType'); if (this.notLoaded) { - return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded); + return new SchoolTypeExpression(undefined, this.root, path, this.notLoaded.withPath(path)); } if (!this.value) return new SchoolTypeExpression(undefined, this.root, path); if (!this.value.isLoaded('schoolType')) { return new SchoolTypeExpression(undefined, this.root, path, - new TeaQLNotLoadedError(this.root, path, 'schoolType')); + new TeaQLNotLoadedError(path.markMissing(), 'school_type')); } const relation = this.value.schoolType; - const target = relation == null - ? undefined - : relation instanceof SchoolType - ? relation - : SchoolType.fromRecord({ id: relation }); + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof SchoolType)) { + return new SchoolTypeExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'school_type')); + } + const target = relation instanceof SchoolType ? relation : undefined; return new SchoolTypeExpression(target, this.root, path); } @@ -501,30 +492,34 @@ export class PlatformListExpression { constructor( private readonly items: readonly Platform[], private readonly root = 'Platform(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): PlatformListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PlatformListExpression { return new PlatformListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): PlatformExpression { - return this.get(0); + return this.item(0, true); } get(index: number): PlatformExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): PlatformExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded); + return new PlatformExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new PlatformExpression(undefined, this.root, itemPath) @@ -536,30 +531,34 @@ export class SchoolTypeListExpression { constructor( private readonly items: readonly SchoolType[], private readonly root = 'SchoolType(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): SchoolTypeListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): SchoolTypeListExpression { return new SchoolTypeListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): SchoolTypeExpression { - return this.get(0); + return this.item(0, true); } get(index: number): SchoolTypeExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): SchoolTypeExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded); + return new SchoolTypeExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new SchoolTypeExpression(undefined, this.root, itemPath) @@ -571,30 +570,34 @@ export class SchoolListExpression { constructor( private readonly items: readonly School[], private readonly root = 'School(null)', - private readonly path = '', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), private readonly present = true, private readonly notLoaded?: TeaQLNotLoadedError, ) {} - static missing(root?: string, path = ''): SchoolListExpression { + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): SchoolListExpression { return new SchoolListExpression([], root, path, false); } size(): ValueExpression { - if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); return this.present ? new ValueExpression(this.items.length) : ValueExpression.missing(); } first(): SchoolExpression { - return this.get(0); + return this.item(0, true); } get(index: number): SchoolExpression { - const itemPath = expressionPath(this.path, `get(${index})`); + return this.item(index, false); + } + + private item(index: number, first: boolean): SchoolExpression { + const itemPath = this.path.index(index, first); if (this.notLoaded) { - return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded); + return new SchoolExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); } return !this.present || index < 0 || index >= this.items.length ? new SchoolExpression(undefined, this.root, itemPath) @@ -607,7 +610,7 @@ export class E { value: Platform | null | undefined, ): PlatformExpression { return new PlatformExpression( - value, `Platform(id=${value?.id ?? 'null'})`, + value, 'Platform', ExpressionPath.root('E.platform()', 'camelCase'), ); } @@ -615,7 +618,7 @@ export class E { value: SchoolType | null | undefined, ): SchoolTypeExpression { return new SchoolTypeExpression( - value, `SchoolType(id=${value?.id ?? 'null'})`, + value, 'SchoolType', ExpressionPath.root('E.schoolType()', 'camelCase'), ); } @@ -623,7 +626,7 @@ export class E { value: School | null | undefined, ): SchoolExpression { return new SchoolExpression( - value, `School(id=${value?.id ?? 'null'})`, + value, 'School', ExpressionPath.root('E.school()', 'camelCase'), ); } } \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts index 6290c60e32711869d3b5361d5553bf014d622502..e9520de760e12f353c9c66ec6176df004eafaf47 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/Platform.ts @@ -1,27 +1,33 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { SchoolType } from './SchoolType'; import { School } from './School'; +const teaqlConstruction = Symbol("managed entity construction"); + export class Platform { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Platform", + ["id", "name", "base_url", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; name?: string; baseUrl?: string; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Platform.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolTypeList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolTypeList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["schoolTypeList"]; delete fields["schoolList"]; Object.assign(this, fields); @@ -47,25 +53,34 @@ export class Platform { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "Platform", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root); - for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolTypeList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): Platform { - const entity = new Platform(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new Platform(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("schoolTypeList")) result["schoolTypeList"] = (this as any)._schoolTypeList; + if (this.isLoaded("schoolList")) result["schoolList"] = (this as any)._schoolList; + return result; } isLoaded(field: string): boolean { @@ -84,12 +99,19 @@ export class Platform { } static refer(id: string | number): Platform { - return new Platform({ id: String(id) } as Partial); + return Platform.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): Platform { - return new Platform().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): Platform { + return EntityCreation.bootstrap(context, "Platform", id, + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Platform", + reserved => new Platform({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -99,23 +121,153 @@ export class Platform { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._schoolTypeList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._schoolList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._schoolTypeList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._schoolList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "school_type_list": graph.sourceMembers((this as any)._schoolTypeList), + "school_list": graph.sourceMembers((this as any)._schoolList) + })); + for (const child of (this as any)._schoolTypeList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._schoolList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.platform; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Platform.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._schoolTypeList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_type_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._schoolList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(Platform.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "baseUrl", canonical: "base_url" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] @@ -123,6 +275,7 @@ export class Platform { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "Platform", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -133,7 +286,8 @@ export class Platform { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -142,36 +296,40 @@ export class Platform { for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -179,7 +337,7 @@ export class Platform { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -191,42 +349,42 @@ export class Platform { for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -235,12 +393,16 @@ export class Platform { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -251,38 +413,44 @@ export class Platform { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._schoolTypeList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_type_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.platform; - if (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updatePlatform(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("platform") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePlatform(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -298,6 +466,10 @@ export class Platform { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -333,7 +505,7 @@ export class Platform { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts index a0e0932d518e97acbecdeed78ef3e6749956f366..c958b9019590aa7772ade5bad19100e3dd4e825e 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/School.ts @@ -1,9 +1,13 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { SchoolType } from './SchoolType'; +const teaqlConstruction = Symbol("managed entity construction"); + export class School { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("School", + ["id", "platform", "school_type", "name", "address", "established_date", "student_capacity", "active", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); id?: string; platform?: Platform | string; schoolType?: SchoolType | string; @@ -14,17 +18,25 @@ export class School { active?: boolean; createTime?: string; updateTime?: string; - version?: number; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + { const error = integer32Error(init?.studentCapacity, "School", "student_capacity"); if (error) throw error; } + + + - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --School.teaqlTemporaryId, writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { this.platform = (init as any).platform instanceof Platform @@ -40,13 +52,15 @@ export class School { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "School", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; @@ -55,8 +69,19 @@ export class School { } static fromRecord(record: Record, root?: EntityRoot): School { - const entity = new School(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new School(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + { const error = integer32Error(this.studentCapacity, "School", "student_capacity"); if (error) throw error; } + + + + + + const result = Object.fromEntries(Object.entries(this)); + return result; } isLoaded(field: string): boolean { @@ -75,12 +100,19 @@ export class School { } static refer(id: string | number): School { - return new School({ id: String(id) } as Partial); + return School.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): School { - return new School().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): School { + return EntityCreation.bootstrap(context, "School", id, + reserved => new School({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "School", + reserved => new School({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -90,23 +122,101 @@ export class School { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform", + "school_type": "SchoolType" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + School.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "School", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(School.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "id", canonical: "id" }, { member: "platform", canonical: "platform" }, { member: "schoolType", canonical: "school_type" }, { member: "name", canonical: "name" }, { member: "address", canonical: "address" }, { member: "establishedDate", canonical: "established_date" }, { member: "studentCapacity", canonical: "student_capacity" }, { member: "active", canonical: "active" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] @@ -114,6 +224,7 @@ export class School { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "School", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -124,7 +235,8 @@ export class School { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -133,8 +245,10 @@ export class School { } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -142,7 +256,7 @@ export class School { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -154,14 +268,12 @@ export class School { return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -170,12 +282,16 @@ export class School { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -186,10 +302,14 @@ export class School { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -210,6 +330,10 @@ export class School { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -266,7 +390,7 @@ export class School { return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts index 0677cb7d71363977bb4b42d7d44bce7d089cc983..3c933c84081b6a06762ebfe3453dc4551f5b8196 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/models/SchoolType.ts @@ -1,26 +1,32 @@ -import { CheckException, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; import { Platform } from './Platform'; import { School } from './School'; +const teaqlConstruction = Symbol("managed entity construction"); + export class SchoolType { private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("SchoolType", + ["platform", "id", "name", "code", "display_order", "version"], { id: "immutable_field", version: "immutable_field" }); platform?: Platform | string; id?: string; name?: string; code?: string; - displayOrder?: number; - version?: number; + displayOrder?: Decimal; + version?: EntityVersion; - constructor(init?: Partial) { - Object.defineProperty(this, "_action", { value: init && init.id ? "Update" : "Create", writable: true, enumerable: false }); + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); - Object.defineProperty(this, "_fullyLoaded", { value: !init || !init.id, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --SchoolType.teaqlTemporaryId, writable: true, enumerable: false }); - Object.defineProperty(this, "_schoolList", { value: init?.id ? SmartList.empty() : new SmartList(), writable: true, enumerable: false }); + Object.defineProperty(this, "_schoolList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); if (init) { const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; delete fields["schoolList"]; Object.assign(this, fields); if ((init as any).platform && typeof (init as any).platform === "object") { @@ -41,24 +47,32 @@ export class SchoolType { } } const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); - else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, Number((this as any).version)); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); } private teaqlEntityKey(): EntityKey { return { entity: "SchoolType", id: (this as any)._ledgerId }; } - private teaqlAttachRoot(root: EntityRoot): this { + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { if ((this as any)._root !== root) { root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); (this as any)._root = root; } - for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root); + for (const child of (this as any)._schoolList) child.teaqlAttachRoot(root, hydration); return this; } static fromRecord(record: Record, root?: EntityRoot): SchoolType { - const entity = new SchoolType(record as Partial); - return root ? entity.teaqlAttachRoot(root) : entity; + const entity = EntityCreation.hydrated(new SchoolType(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("schoolList")) result["schoolList"] = (this as any)._schoolList; + return result; } isLoaded(field: string): boolean { @@ -77,12 +91,19 @@ export class SchoolType { } static refer(id: string | number): SchoolType { - return new SchoolType({ id: String(id) } as Partial); + return SchoolType.fromRecord({ id: String(id) }); } /** @internal Generated Runtime Module fixed-ID construction capability. */ - static teaqlBootstrapNew(id: string | number): SchoolType { - return new SchoolType().updateId(String(id)); + static teaqlBootstrapNew(context: UserContext, id: string | number): SchoolType { + return EntityCreation.bootstrap(context, "SchoolType", id, + reserved => new SchoolType({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "SchoolType", + reserved => new SchoolType({id: reserved} as Partial, teaqlConstruction, true)); } markForDeletion(): this { @@ -92,23 +113,127 @@ export class SchoolType { } auditAs(comment: string): this { - new MutationIntent(comment); - (this as any)._comment = comment; + (this as any)._comment = new MutationIntent(comment).comment; return this; } async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; const service = context.requireResource("dataService"); return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { - this.teaqlPreflightGraph(context, service, graph); return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); }); } + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._schoolList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._schoolList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._schoolList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "platform": "Platform" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "school_list": graph.sourceMembers((this as any)._schoolList) + })); + for (const child of (this as any)._schoolList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.schoolType; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + SchoolType.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "SchoolType", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._schoolList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("school_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + /** @internal Validates and fixes the complete graph before its first mutation. */ - teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): void { + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); const action = (this as any)._action; + graph.discardRestoredFields(SchoolType.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); if (action === "Update" && pending) { const notLoaded = [{ member: "platform", canonical: "platform" }, { member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "code", canonical: "code" }, { member: "displayOrder", canonical: "display_order" }, { member: "version", canonical: "version" }] @@ -116,6 +241,7 @@ export class SchoolType { if (notLoaded) { throw new CheckException([{ ruleId: "invalid_type", + entityType: "SchoolType", location: ObjectLocation.property(notLoaded.canonical), message: "Mutation requires a fully loaded entity", }]); @@ -126,7 +252,8 @@ export class SchoolType { payload: action === "Update" ? (this as any)._root.change(this.teaqlEntityKey()) : this.teaqlMutationPayload(), - id: (this as any).id, version: (this as any).version, + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment, ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); @@ -135,22 +262,25 @@ export class SchoolType { for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { child.teaqlPreflightGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } } /** @internal Used by generated relation cascades inside the root graph transaction. */ - async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope): Promise { + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); const action = (this as any)._action; const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); const mutation = { @@ -158,7 +288,7 @@ export class SchoolType { action: (this as any)._action, payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), id: (this as any).id, - version: (this as any).version, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, comment: (this as any)._comment ,ledgerKey: this.teaqlEntityKey() ,ledgerRoot: (this as any)._root @@ -170,28 +300,27 @@ export class SchoolType { for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } return this; } const result = await service.executeMutation(request); - for (const [field, value] of Object.entries(mutation.payload as Record)) { - if (field !== "id" && field !== "version") (this as any)._root.set(this.teaqlEntityKey(), field, value); - } + graph.validatePreparedSources(); if (!result.persistedRecord) { throw new Error("Mutation did not return the authoritative persisted record"); } const rollbackState = { - payload: this.teaqlMutationPayload(), + ownProperties: Object.getOwnPropertyDescriptors(this), ledgerId: (this as any)._ledgerId, action: (this as any)._action, loadedFields: new Set((this as any)._loadedFields), @@ -200,12 +329,16 @@ export class SchoolType { }; const oldKey = this.teaqlEntityKey(); Object.assign(this, result.persistedRecord); - LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload()); (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; const newKey = this.teaqlEntityKey(); (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); service.afterGraphRollback(() => { - Object.assign(this, rollbackState.payload); + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); (this as any)._ledgerId = rollbackState.ledgerId; (this as any)._action = rollbackState.action; (this as any)._loadedFields = rollbackState.loadedFields; @@ -216,24 +349,29 @@ export class SchoolType { (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); (this as any)._fullyLoaded = false; if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); const scope = request.scopeFor(newKey); for (const [index, child] of (this as any)._schoolList.entries()) { child.teaqlAttachRoot((this as any)._root); const currentParent = child.schoolType; - if (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null - ? currentParent.id : currentParent) !== this.id) child.updateSchoolType(this); - try { await child.teaqlSaveWithinGraph(context, service, graph, scope); } + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("schoolType") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updateSchoolType(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } catch (error) { if (!(error instanceof CheckException)) throw error; const prefix = ObjectLocation.property("school_list").index(index); - throw new CheckException(error.violations.map(violation => ({ + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix), - }))); + })))); } } service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); (this as any)._root.clearEntity(newKey); - if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, Number((this as any).version)); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); }); return this; } @@ -249,6 +387,10 @@ export class SchoolType { }; } + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + updateId(value: string): this { this.id = value; this.markLoaded("id"); @@ -270,14 +412,15 @@ export class SchoolType { return this; } - updateDisplayOrder(value: number): this { + updateDisplayOrder(value: Decimal): this { + if (value != null) value = decimal(value); this.displayOrder = value; this.markLoaded("displayOrder"); (this as any)._root.set(this.teaqlEntityKey(), "display_order", value); return this; } - updateVersion(value: number): this { + updateVersion(value: EntityVersion): this { this.version = value; this.markLoaded("version"); (this as any)._root.set(this.teaqlEntityKey(), "version", value); diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts index af9cf03a986e08d02115cba30825e5e6b3bbfdf6..a36d62e09bcd438cc795838878869315b4813268 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/PlatformRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { Platform } from '../models/Platform'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class PlatformRequest { else this.selectSelfFields(); } + get entityName(): "Platform" { + return "Platform"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class PlatformRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -147,13 +154,13 @@ export class PlatformRequest { - selectSchoolTypeListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolTypeListWith(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolTypeList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectSchoolTypeListWith", relation: "schoolTypeList" }); return this; } - selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolListWith(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolList", request.toQuery(), "id", "platform", true, { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); @@ -162,17 +169,19 @@ export class PlatformRequest { haveSchoolTypes(): this { return this.withSchoolTypeListMatching({ + entityName: "SchoolType", toQuery: () => new SelectQuery("SchoolType"), }); } haveNoSchoolTypes(): this { return this.withoutSchoolTypeListMatching({ + entityName: "SchoolType", toQuery: () => new SelectQuery("SchoolType"), }); } - withSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolTypeListMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -183,7 +192,7 @@ export class PlatformRequest { return this; } - withoutSchoolTypeListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolTypeListMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -195,17 +204,19 @@ export class PlatformRequest { } haveSchools(): this { return this.withSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } haveNoSchools(): this { return this.withoutSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } - withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -216,7 +227,7 @@ export class PlatformRequest { return this; } - withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -233,13 +244,13 @@ export class PlatformRequest { countSchoolTypesAs(alias: string): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); - this.countSchoolTypesWith(alias, { toQuery: () => query }); + this.countSchoolTypesWith(alias, { entityName: "SchoolType", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolTypesAs", relation: "schoolTypeList", alias }; return this; } - countSchoolTypesWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolTypesWith(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -251,10 +262,10 @@ export class PlatformRequest { minDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.minDisplayOrderOfSchoolTypesAs( - "minOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "minOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - minDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + minDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "displayOrder", alias); @@ -265,10 +276,10 @@ export class PlatformRequest { maxDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.maxDisplayOrderOfSchoolTypesAs( - "maxOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "maxOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - maxDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "displayOrder", alias); @@ -279,10 +290,10 @@ export class PlatformRequest { sumDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.sumDisplayOrderOfSchoolTypesAs( - "sumOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "sumOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - sumDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "displayOrder", alias); @@ -293,10 +304,10 @@ export class PlatformRequest { avgDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.avgDisplayOrderOfSchoolTypesAs( - "avgOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "avgOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - avgDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "displayOrder", alias); @@ -307,10 +318,10 @@ export class PlatformRequest { standardDeviationDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.standardDeviationDisplayOrderOfSchoolTypesAs( - "standardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "standardDeviationOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "displayOrder", alias); @@ -321,10 +332,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs( - "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "displayOrder", alias); @@ -335,10 +346,10 @@ export class PlatformRequest { sampleVarianceDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.sampleVarianceDisplayOrderOfSchoolTypesAs( - "sampleVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "sampleVarianceOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "displayOrder", alias); @@ -349,10 +360,10 @@ export class PlatformRequest { samplePopulationVarianceDisplayOrderOfSchoolTypes(): this { const query = new SelectQuery("SchoolType").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceDisplayOrderOfSchoolTypesAs( - "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { toQuery: () => query }); + "samplePopulationVarianceOfDisplayOrderOfSchoolTypes", { entityName: "SchoolType", toQuery: () => query }); } - samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceDisplayOrderOfSchoolTypesAs(alias: string, child: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "displayOrder", alias); @@ -366,13 +377,13 @@ export class PlatformRequest { countSchoolsAs(alias: string): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); - this.countSchoolsWith(alias, { toQuery: () => query }); + this.countSchoolsWith(alias, { entityName: "School", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; return this; } - countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolsWith(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -384,10 +395,10 @@ export class PlatformRequest { minStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.minStudentCapacityOfSchoolsAs( - "minOfStudentCapacityOfSchools", { toQuery: () => query }); + "minOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "studentCapacity", alias); @@ -398,10 +409,10 @@ export class PlatformRequest { maxStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.maxStudentCapacityOfSchoolsAs( - "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + "maxOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "studentCapacity", alias); @@ -412,10 +423,10 @@ export class PlatformRequest { sumStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sumStudentCapacityOfSchoolsAs( - "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + "sumOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "studentCapacity", alias); @@ -426,10 +437,10 @@ export class PlatformRequest { avgStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.avgStudentCapacityOfSchoolsAs( - "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + "avgOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "studentCapacity", alias); @@ -440,10 +451,10 @@ export class PlatformRequest { standardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.standardDeviationStudentCapacityOfSchoolsAs( - "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "standardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "studentCapacity", alias); @@ -454,10 +465,10 @@ export class PlatformRequest { squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( - "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "studentCapacity", alias); @@ -468,10 +479,10 @@ export class PlatformRequest { sampleVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sampleVarianceStudentCapacityOfSchoolsAs( - "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "sampleVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "studentCapacity", alias); @@ -482,10 +493,10 @@ export class PlatformRequest { samplePopulationVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( - "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "samplePopulationVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "studentCapacity", alias); @@ -494,47 +505,47 @@ export class PlatformRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -559,42 +570,42 @@ export class PlatformRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -648,42 +659,42 @@ export class PlatformRequest { return this; } - withBaseUrlIsNot(val: any): this { + withBaseUrlIsNot(val: string): this { this.filters.push({ "baseUrl": { "$ne": val } }); return this; } - withBaseUrlIn(...vals: any[]): this { + withBaseUrlIn(...vals: string[]): this { this.filters.push({ "baseUrl": { "$in": vals } }); return this; } - withBaseUrlNotIn(...vals: any[]): this { + withBaseUrlNotIn(...vals: string[]): this { this.filters.push({ "baseUrl": { "$notIn": vals } }); return this; } - withBaseUrlGreaterThan(val: any): this { + withBaseUrlGreaterThan(val: string): this { this.filters.push({ "baseUrl": { "$gt": val } }); return this; } - withBaseUrlGreaterThanOrEqualTo(val: any): this { + withBaseUrlGreaterThanOrEqualTo(val: string): this { this.filters.push({ "baseUrl": { "$gte": val } }); return this; } - withBaseUrlLessThan(val: any): this { + withBaseUrlLessThan(val: string): this { this.filters.push({ "baseUrl": { "$lt": val } }); return this; } - withBaseUrlLessThanOrEqualTo(val: any): this { + withBaseUrlLessThanOrEqualTo(val: string): this { this.filters.push({ "baseUrl": { "$lte": val } }); return this; } - withBaseUrlBetween(lower: any, upper: any): this { + withBaseUrlBetween(lower: string, upper: string): this { this.filters.push({ "baseUrl": { "$between": [lower, upper] } }); return this; } @@ -727,47 +738,47 @@ export class PlatformRequest { return this; } - withCreateTimeIs(val: any): this { + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIsNot(val: any): this { + withCreateTimeIsNot(val: unknown): this { this.filters.push({ "createTime": { "$ne": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeNotIn(...vals: any[]): this { + withCreateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$notIn": vals } }); return this; } - withCreateTimeGreaterThan(val: any): this { + withCreateTimeGreaterThan(val: unknown): this { this.filters.push({ "createTime": { "$gt": val } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThan(val: any): this { + withCreateTimeLessThan(val: unknown): this { this.filters.push({ "createTime": { "$lt": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withCreateTimeBetween(lower: any, upper: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "createTime": { "$between": [lower, upper] } }); return this; } @@ -782,47 +793,47 @@ export class PlatformRequest { return this; } - withUpdateTimeIs(val: any): this { + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIsNot(val: any): this { + withUpdateTimeIsNot(val: unknown): this { this.filters.push({ "updateTime": { "$ne": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeNotIn(...vals: any[]): this { + withUpdateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$notIn": vals } }); return this; } - withUpdateTimeGreaterThan(val: any): this { + withUpdateTimeGreaterThan(val: unknown): this { this.filters.push({ "updateTime": { "$gt": val } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThan(val: any): this { + withUpdateTimeLessThan(val: unknown): this { this.filters.push({ "updateTime": { "$lt": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withUpdateTimeBetween(lower: any, upper: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "updateTime": { "$between": [lower, upper] } }); return this; } @@ -837,47 +848,47 @@ export class PlatformRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -976,7 +987,7 @@ export class PlatformRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -985,7 +996,7 @@ export class PlatformRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByBaseUrl(): this { @@ -994,7 +1005,7 @@ export class PlatformRequest { } groupByBaseUrlAs(retName: string): this { - this.query.groupBy("baseUrl"); // In TS we don't alias group by yet natively + this.query.groupBy("baseUrl", retName); return this; } groupByCreateTime(): this { @@ -1003,7 +1014,7 @@ export class PlatformRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -1012,7 +1023,7 @@ export class PlatformRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -1021,7 +1032,7 @@ export class PlatformRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } @@ -1134,9 +1145,10 @@ export class ExecutablePlatformRequest { return this; } - newEntity(context: UserContext): Platform { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new Platform(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return Platform.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts index 394ab2a4fb412ab2b2e47194914185b0857cf66b..de1a516165f2696796a626baf893ca4140235532 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { School } from '../models/School'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class SchoolRequest { else this.selectSelfFields(); } + get entityName(): "School" { + return "School"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class SchoolRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -162,14 +169,14 @@ export class SchoolRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, { kind: "relation-select", method: "selectPlatformWith", relation: "platform" }); return this; } - selectSchoolTypeWith(request: { toQuery(): SelectQuery }): this { + selectSchoolTypeWith(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.query.select(["schoolType"]); this.query.relationQuery( "schoolType", request.toQuery(), "schoolType", "id", false, @@ -177,7 +184,7 @@ export class SchoolRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -186,7 +193,7 @@ export class SchoolRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -194,7 +201,7 @@ export class SchoolRequest { }); return this; } - withSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + withSchoolTypeMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "schoolType": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -203,7 +210,7 @@ export class SchoolRequest { return this; } - withoutSchoolTypeMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolTypeMatching(request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }): this { this.filters.push({ "schoolType": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -215,47 +222,47 @@ export class SchoolRequest { - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -328,42 +335,42 @@ export class SchoolRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -417,42 +424,42 @@ export class SchoolRequest { return this; } - withAddressIsNot(val: any): this { + withAddressIsNot(val: string): this { this.filters.push({ "address": { "$ne": val } }); return this; } - withAddressIn(...vals: any[]): this { + withAddressIn(...vals: string[]): this { this.filters.push({ "address": { "$in": vals } }); return this; } - withAddressNotIn(...vals: any[]): this { + withAddressNotIn(...vals: string[]): this { this.filters.push({ "address": { "$notIn": vals } }); return this; } - withAddressGreaterThan(val: any): this { + withAddressGreaterThan(val: string): this { this.filters.push({ "address": { "$gt": val } }); return this; } - withAddressGreaterThanOrEqualTo(val: any): this { + withAddressGreaterThanOrEqualTo(val: string): this { this.filters.push({ "address": { "$gte": val } }); return this; } - withAddressLessThan(val: any): this { + withAddressLessThan(val: string): this { this.filters.push({ "address": { "$lt": val } }); return this; } - withAddressLessThanOrEqualTo(val: any): this { + withAddressLessThanOrEqualTo(val: string): this { this.filters.push({ "address": { "$lte": val } }); return this; } - withAddressBetween(lower: any, upper: any): this { + withAddressBetween(lower: string, upper: string): this { this.filters.push({ "address": { "$between": [lower, upper] } }); return this; } @@ -496,47 +503,47 @@ export class SchoolRequest { return this; } - withEstablishedDateIs(val: any): this { + withEstablishedDateIs(val: string): this { this.filters.push({ "establishedDate": { "$eq": val } }); return this; } - withEstablishedDateIsNot(val: any): this { + withEstablishedDateIsNot(val: string): this { this.filters.push({ "establishedDate": { "$ne": val } }); return this; } - withEstablishedDateIn(...vals: any[]): this { + withEstablishedDateIn(...vals: string[]): this { this.filters.push({ "establishedDate": { "$in": vals } }); return this; } - withEstablishedDateNotIn(...vals: any[]): this { + withEstablishedDateNotIn(...vals: string[]): this { this.filters.push({ "establishedDate": { "$notIn": vals } }); return this; } - withEstablishedDateGreaterThan(val: any): this { + withEstablishedDateGreaterThan(val: string): this { this.filters.push({ "establishedDate": { "$gt": val } }); return this; } - withEstablishedDateGreaterThanOrEqualTo(val: any): this { + withEstablishedDateGreaterThanOrEqualTo(val: string): this { this.filters.push({ "establishedDate": { "$gte": val } }); return this; } - withEstablishedDateLessThan(val: any): this { + withEstablishedDateLessThan(val: string): this { this.filters.push({ "establishedDate": { "$lt": val } }); return this; } - withEstablishedDateLessThanOrEqualTo(val: any): this { + withEstablishedDateLessThanOrEqualTo(val: string): this { this.filters.push({ "establishedDate": { "$lte": val } }); return this; } - withEstablishedDateBetween(lower: any, upper: any): this { + withEstablishedDateBetween(lower: string, upper: string): this { this.filters.push({ "establishedDate": { "$between": [lower, upper] } }); return this; } @@ -551,47 +558,47 @@ export class SchoolRequest { return this; } - withStudentCapacityIs(val: any): this { + withStudentCapacityIs(val: number): this { this.filters.push({ "studentCapacity": { "$eq": val } }); return this; } - withStudentCapacityIsNot(val: any): this { + withStudentCapacityIsNot(val: number): this { this.filters.push({ "studentCapacity": { "$ne": val } }); return this; } - withStudentCapacityIn(...vals: any[]): this { + withStudentCapacityIn(...vals: number[]): this { this.filters.push({ "studentCapacity": { "$in": vals } }); return this; } - withStudentCapacityNotIn(...vals: any[]): this { + withStudentCapacityNotIn(...vals: number[]): this { this.filters.push({ "studentCapacity": { "$notIn": vals } }); return this; } - withStudentCapacityGreaterThan(val: any): this { + withStudentCapacityGreaterThan(val: number): this { this.filters.push({ "studentCapacity": { "$gt": val } }); return this; } - withStudentCapacityGreaterThanOrEqualTo(val: any): this { + withStudentCapacityGreaterThanOrEqualTo(val: number): this { this.filters.push({ "studentCapacity": { "$gte": val } }); return this; } - withStudentCapacityLessThan(val: any): this { + withStudentCapacityLessThan(val: number): this { this.filters.push({ "studentCapacity": { "$lt": val } }); return this; } - withStudentCapacityLessThanOrEqualTo(val: any): this { + withStudentCapacityLessThanOrEqualTo(val: number): this { this.filters.push({ "studentCapacity": { "$lte": val } }); return this; } - withStudentCapacityBetween(lower: any, upper: any): this { + withStudentCapacityBetween(lower: number, upper: number): this { this.filters.push({ "studentCapacity": { "$between": [lower, upper] } }); return this; } @@ -615,42 +622,42 @@ export class SchoolRequest { this.filters.push({ "active": { "$eq": false } }); return this; } - withActiveIsNot(val: any): this { + withActiveIsNot(val: boolean): this { this.filters.push({ "active": { "$ne": val } }); return this; } - withActiveIn(...vals: any[]): this { + withActiveIn(...vals: boolean[]): this { this.filters.push({ "active": { "$in": vals } }); return this; } - withActiveNotIn(...vals: any[]): this { + withActiveNotIn(...vals: boolean[]): this { this.filters.push({ "active": { "$notIn": vals } }); return this; } - withActiveGreaterThan(val: any): this { + withActiveGreaterThan(val: boolean): this { this.filters.push({ "active": { "$gt": val } }); return this; } - withActiveGreaterThanOrEqualTo(val: any): this { + withActiveGreaterThanOrEqualTo(val: boolean): this { this.filters.push({ "active": { "$gte": val } }); return this; } - withActiveLessThan(val: any): this { + withActiveLessThan(val: boolean): this { this.filters.push({ "active": { "$lt": val } }); return this; } - withActiveLessThanOrEqualTo(val: any): this { + withActiveLessThanOrEqualTo(val: boolean): this { this.filters.push({ "active": { "$lte": val } }); return this; } - withActiveBetween(lower: any, upper: any): this { + withActiveBetween(lower: boolean, upper: boolean): this { this.filters.push({ "active": { "$between": [lower, upper] } }); return this; } @@ -665,47 +672,47 @@ export class SchoolRequest { return this; } - withCreateTimeIs(val: any): this { + withCreateTimeIs(val: unknown): this { this.filters.push({ "createTime": { "$eq": val } }); return this; } - withCreateTimeIsNot(val: any): this { + withCreateTimeIsNot(val: unknown): this { this.filters.push({ "createTime": { "$ne": val } }); return this; } - withCreateTimeIn(...vals: any[]): this { + withCreateTimeIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$in": vals } }); return this; } - withCreateTimeNotIn(...vals: any[]): this { + withCreateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "createTime": { "$notIn": vals } }); return this; } - withCreateTimeGreaterThan(val: any): this { + withCreateTimeGreaterThan(val: unknown): this { this.filters.push({ "createTime": { "$gt": val } }); return this; } - withCreateTimeGreaterThanOrEqualTo(val: any): this { + withCreateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$gte": val } }); return this; } - withCreateTimeLessThan(val: any): this { + withCreateTimeLessThan(val: unknown): this { this.filters.push({ "createTime": { "$lt": val } }); return this; } - withCreateTimeLessThanOrEqualTo(val: any): this { + withCreateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "createTime": { "$lte": val } }); return this; } - withCreateTimeBetween(lower: any, upper: any): this { + withCreateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "createTime": { "$between": [lower, upper] } }); return this; } @@ -720,47 +727,47 @@ export class SchoolRequest { return this; } - withUpdateTimeIs(val: any): this { + withUpdateTimeIs(val: unknown): this { this.filters.push({ "updateTime": { "$eq": val } }); return this; } - withUpdateTimeIsNot(val: any): this { + withUpdateTimeIsNot(val: unknown): this { this.filters.push({ "updateTime": { "$ne": val } }); return this; } - withUpdateTimeIn(...vals: any[]): this { + withUpdateTimeIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$in": vals } }); return this; } - withUpdateTimeNotIn(...vals: any[]): this { + withUpdateTimeNotIn(...vals: unknown[]): this { this.filters.push({ "updateTime": { "$notIn": vals } }); return this; } - withUpdateTimeGreaterThan(val: any): this { + withUpdateTimeGreaterThan(val: unknown): this { this.filters.push({ "updateTime": { "$gt": val } }); return this; } - withUpdateTimeGreaterThanOrEqualTo(val: any): this { + withUpdateTimeGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$gte": val } }); return this; } - withUpdateTimeLessThan(val: any): this { + withUpdateTimeLessThan(val: unknown): this { this.filters.push({ "updateTime": { "$lt": val } }); return this; } - withUpdateTimeLessThanOrEqualTo(val: any): this { + withUpdateTimeLessThanOrEqualTo(val: unknown): this { this.filters.push({ "updateTime": { "$lte": val } }); return this; } - withUpdateTimeBetween(lower: any, upper: any): this { + withUpdateTimeBetween(lower: unknown, upper: unknown): this { this.filters.push({ "updateTime": { "$between": [lower, upper] } }); return this; } @@ -775,47 +782,47 @@ export class SchoolRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -1010,7 +1017,7 @@ export class SchoolRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByPlatform(): this { @@ -1019,7 +1026,7 @@ export class SchoolRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupBySchoolType(): this { @@ -1028,7 +1035,7 @@ export class SchoolRequest { } groupBySchoolTypeAs(retName: string): this { - this.query.groupBy("schoolType"); // In TS we don't alias group by yet natively + this.query.groupBy("schoolType", retName); return this; } groupByName(): this { @@ -1037,7 +1044,7 @@ export class SchoolRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByAddress(): this { @@ -1046,7 +1053,7 @@ export class SchoolRequest { } groupByAddressAs(retName: string): this { - this.query.groupBy("address"); // In TS we don't alias group by yet natively + this.query.groupBy("address", retName); return this; } groupByEstablishedDate(): this { @@ -1055,7 +1062,7 @@ export class SchoolRequest { } groupByEstablishedDateAs(retName: string): this { - this.query.groupBy("establishedDate"); // In TS we don't alias group by yet natively + this.query.groupBy("establishedDate", retName); return this; } groupByStudentCapacity(): this { @@ -1064,7 +1071,7 @@ export class SchoolRequest { } groupByStudentCapacityAs(retName: string): this { - this.query.groupBy("studentCapacity"); // In TS we don't alias group by yet natively + this.query.groupBy("studentCapacity", retName); return this; } groupByActive(): this { @@ -1073,7 +1080,7 @@ export class SchoolRequest { } groupByActiveAs(retName: string): this { - this.query.groupBy("active"); // In TS we don't alias group by yet natively + this.query.groupBy("active", retName); return this; } groupByCreateTime(): this { @@ -1082,7 +1089,7 @@ export class SchoolRequest { } groupByCreateTimeAs(retName: string): this { - this.query.groupBy("createTime"); // In TS we don't alias group by yet natively + this.query.groupBy("createTime", retName); return this; } groupByUpdateTime(): this { @@ -1091,7 +1098,7 @@ export class SchoolRequest { } groupByUpdateTimeAs(retName: string): this { - this.query.groupBy("updateTime"); // In TS we don't alias group by yet natively + this.query.groupBy("updateTime", retName); return this; } groupByVersion(): this { @@ -1100,14 +1107,14 @@ export class SchoolRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1117,7 +1124,7 @@ export class SchoolRequest { facetBySchoolTypeAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "SchoolType"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "schoolType", request, includeAllFacets, @@ -1233,9 +1240,10 @@ export class ExecutableSchoolRequest { return this; } - newEntity(context: UserContext): School { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new School(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return School.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts index 8d09b5f34a9b4b2aeee292bcfb05406959efef90..0eb932a414f079e38f575598bd0212c567b84edb 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/generated/requests/SchoolTypeRequest.ts @@ -1,6 +1,7 @@ import { EntityRoot, SelectQuery, SmartList, TeaQLDataService, UserContext, executeRelationFacets } from '../../teaql-ts'; import { SchoolType } from '../models/SchoolType'; import { mergeGeneratedScalarSearch, DynamicSearchWarning, QueryIntent } from 'teaql-ts'; +import type { Decimal, Long, LocalTime } from 'teaql-ts'; import { GENERATED_SEARCH_MODELS } from '../../generated-search-models'; @@ -24,6 +25,10 @@ export class SchoolTypeRequest { else this.selectSelfFields(); } + get entityName(): "SchoolType" { + return "SchoolType"; + } + comment(c: string): this { this.query.comment(c); this._comment = c; @@ -99,12 +104,14 @@ export class SchoolTypeRequest { } withDeletedRows(): this { + this.query.withDeletedRows(); this.filters = this.filters.filter(filter => !("version" in filter)); return this; } deletedRowsOnly(): this { this.withDeletedRows(); + this.query.deletedRowsOnly(); this.filters.push({ version: { "$lte": -1 } }); return this; } @@ -140,7 +147,7 @@ export class SchoolTypeRequest { } - selectPlatformWith(request: { toQuery(): SelectQuery }): this { + selectPlatformWith(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.query.select(["platform"]); this.query.relationQuery( "platform", request.toQuery(), "platform", "id", false, @@ -148,7 +155,7 @@ export class SchoolTypeRequest { return this; } - withPlatformMatching(request: { toQuery(): SelectQuery }): this { + withPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$inSubquery": { query: request.toQuery(), field: "id" }, @@ -157,7 +164,7 @@ export class SchoolTypeRequest { return this; } - withoutPlatformMatching(request: { toQuery(): SelectQuery }): this { + withoutPlatformMatching(request: { readonly entityName: "Platform"; toQuery(): SelectQuery }): this { this.filters.push({ "platform": { "$notInSubquery": { query: request.toQuery(), field: "id" }, @@ -166,7 +173,7 @@ export class SchoolTypeRequest { return this; } - selectSchoolListWith(request: { toQuery(): SelectQuery }): this { + selectSchoolListWith(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.query.relationQuery( "schoolList", request.toQuery(), "id", "schoolType", true, { kind: "relation-select", method: "selectSchoolListWith", relation: "schoolList" }); @@ -175,17 +182,19 @@ export class SchoolTypeRequest { haveSchools(): this { return this.withSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } haveNoSchools(): this { return this.withoutSchoolListMatching({ + entityName: "School", toQuery: () => new SelectQuery("School"), }); } - withSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$inSubquery": { @@ -196,7 +205,7 @@ export class SchoolTypeRequest { return this; } - withoutSchoolListMatching(request: { toQuery(): SelectQuery }): this { + withoutSchoolListMatching(request: { readonly entityName: "School"; toQuery(): SelectQuery }): this { this.filters.push({ "id": { "$notInSubquery": { @@ -213,13 +222,13 @@ export class SchoolTypeRequest { countSchoolsAs(alias: string): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); - this.countSchoolsWith(alias, { toQuery: () => query }); + this.countSchoolsWith(alias, { entityName: "School", toQuery: () => query }); this.query.relationAggregates[this.query.relationAggregates.length - 1].operation = { kind: "relation-count", method: "countSchoolsAs", relation: "schoolList", alias }; return this; } - countSchoolsWith(alias: string, child: { toQuery(): SelectQuery }): this { + countSchoolsWith(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("Count", "id", alias); @@ -231,10 +240,10 @@ export class SchoolTypeRequest { minStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.minStudentCapacityOfSchoolsAs( - "minOfStudentCapacityOfSchools", { toQuery: () => query }); + "minOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - minStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + minStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("min", "studentCapacity", alias); @@ -245,10 +254,10 @@ export class SchoolTypeRequest { maxStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.maxStudentCapacityOfSchoolsAs( - "maxOfStudentCapacityOfSchools", { toQuery: () => query }); + "maxOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - maxStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + maxStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("max", "studentCapacity", alias); @@ -259,10 +268,10 @@ export class SchoolTypeRequest { sumStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sumStudentCapacityOfSchoolsAs( - "sumOfStudentCapacityOfSchools", { toQuery: () => query }); + "sumOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sumStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sumStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("sum", "studentCapacity", alias); @@ -273,10 +282,10 @@ export class SchoolTypeRequest { avgStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.avgStudentCapacityOfSchoolsAs( - "avgOfStudentCapacityOfSchools", { toQuery: () => query }); + "avgOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - avgStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + avgStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("avg", "studentCapacity", alias); @@ -287,10 +296,10 @@ export class SchoolTypeRequest { standardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.standardDeviationStudentCapacityOfSchoolsAs( - "standardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "standardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + standardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev", "studentCapacity", alias); @@ -301,10 +310,10 @@ export class SchoolTypeRequest { squareRootOfPopulationStandardDeviationStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs( - "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { toQuery: () => query }); + "squareRootOfPopulationStandardDeviationOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + squareRootOfPopulationStandardDeviationStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("stddev_pop", "studentCapacity", alias); @@ -315,10 +324,10 @@ export class SchoolTypeRequest { sampleVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.sampleVarianceStudentCapacityOfSchoolsAs( - "sampleVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "sampleVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + sampleVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_samp", "studentCapacity", alias); @@ -329,10 +338,10 @@ export class SchoolTypeRequest { samplePopulationVarianceStudentCapacityOfSchools(): this { const query = new SelectQuery("School").filter({ version: { "$gte": 1 } }); return this.samplePopulationVarianceStudentCapacityOfSchoolsAs( - "samplePopulationVarianceOfStudentCapacityOfSchools", { toQuery: () => query }); + "samplePopulationVarianceOfStudentCapacityOfSchools", { entityName: "School", toQuery: () => query }); } - samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { toQuery(): SelectQuery }): this { + samplePopulationVarianceStudentCapacityOfSchoolsAs(alias: string, child: { readonly entityName: "School"; toQuery(): SelectQuery }): this { const query = child.toQuery().clone(); query.aggregateItems = []; query.aggregate("var_pop", "studentCapacity", alias); @@ -361,47 +370,47 @@ export class SchoolTypeRequest { return this; } - withIdIs(val: any): this { + withIdIs(val: string): this { this.filters.push({ "id": { "$eq": val } }); return this; } - withIdIsNot(val: any): this { + withIdIsNot(val: string): this { this.filters.push({ "id": { "$ne": val } }); return this; } - withIdIn(...vals: any[]): this { + withIdIn(...vals: string[]): this { this.filters.push({ "id": { "$in": vals } }); return this; } - withIdNotIn(...vals: any[]): this { + withIdNotIn(...vals: string[]): this { this.filters.push({ "id": { "$notIn": vals } }); return this; } - withIdGreaterThan(val: any): this { + withIdGreaterThan(val: string): this { this.filters.push({ "id": { "$gt": val } }); return this; } - withIdGreaterThanOrEqualTo(val: any): this { + withIdGreaterThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$gte": val } }); return this; } - withIdLessThan(val: any): this { + withIdLessThan(val: string): this { this.filters.push({ "id": { "$lt": val } }); return this; } - withIdLessThanOrEqualTo(val: any): this { + withIdLessThanOrEqualTo(val: string): this { this.filters.push({ "id": { "$lte": val } }); return this; } - withIdBetween(lower: any, upper: any): this { + withIdBetween(lower: string, upper: string): this { this.filters.push({ "id": { "$between": [lower, upper] } }); return this; } @@ -426,42 +435,42 @@ export class SchoolTypeRequest { return this; } - withNameIsNot(val: any): this { + withNameIsNot(val: string): this { this.filters.push({ "name": { "$ne": val } }); return this; } - withNameIn(...vals: any[]): this { + withNameIn(...vals: string[]): this { this.filters.push({ "name": { "$in": vals } }); return this; } - withNameNotIn(...vals: any[]): this { + withNameNotIn(...vals: string[]): this { this.filters.push({ "name": { "$notIn": vals } }); return this; } - withNameGreaterThan(val: any): this { + withNameGreaterThan(val: string): this { this.filters.push({ "name": { "$gt": val } }); return this; } - withNameGreaterThanOrEqualTo(val: any): this { + withNameGreaterThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$gte": val } }); return this; } - withNameLessThan(val: any): this { + withNameLessThan(val: string): this { this.filters.push({ "name": { "$lt": val } }); return this; } - withNameLessThanOrEqualTo(val: any): this { + withNameLessThanOrEqualTo(val: string): this { this.filters.push({ "name": { "$lte": val } }); return this; } - withNameBetween(lower: any, upper: any): this { + withNameBetween(lower: string, upper: string): this { this.filters.push({ "name": { "$between": [lower, upper] } }); return this; } @@ -515,42 +524,42 @@ export class SchoolTypeRequest { return this; } - withCodeIsNot(val: any): this { + withCodeIsNot(val: string): this { this.filters.push({ "code": { "$ne": val } }); return this; } - withCodeIn(...vals: any[]): this { + withCodeIn(...vals: string[]): this { this.filters.push({ "code": { "$in": vals } }); return this; } - withCodeNotIn(...vals: any[]): this { + withCodeNotIn(...vals: string[]): this { this.filters.push({ "code": { "$notIn": vals } }); return this; } - withCodeGreaterThan(val: any): this { + withCodeGreaterThan(val: string): this { this.filters.push({ "code": { "$gt": val } }); return this; } - withCodeGreaterThanOrEqualTo(val: any): this { + withCodeGreaterThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$gte": val } }); return this; } - withCodeLessThan(val: any): this { + withCodeLessThan(val: string): this { this.filters.push({ "code": { "$lt": val } }); return this; } - withCodeLessThanOrEqualTo(val: any): this { + withCodeLessThanOrEqualTo(val: string): this { this.filters.push({ "code": { "$lte": val } }); return this; } - withCodeBetween(lower: any, upper: any): this { + withCodeBetween(lower: string, upper: string): this { this.filters.push({ "code": { "$between": [lower, upper] } }); return this; } @@ -594,47 +603,47 @@ export class SchoolTypeRequest { return this; } - withDisplayOrderIs(val: any): this { + withDisplayOrderIs(val: Decimal): this { this.filters.push({ "displayOrder": { "$eq": val } }); return this; } - withDisplayOrderIsNot(val: any): this { + withDisplayOrderIsNot(val: Decimal): this { this.filters.push({ "displayOrder": { "$ne": val } }); return this; } - withDisplayOrderIn(...vals: any[]): this { + withDisplayOrderIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$in": vals } }); return this; } - withDisplayOrderNotIn(...vals: any[]): this { + withDisplayOrderNotIn(...vals: Decimal[]): this { this.filters.push({ "displayOrder": { "$notIn": vals } }); return this; } - withDisplayOrderGreaterThan(val: any): this { + withDisplayOrderGreaterThan(val: Decimal): this { this.filters.push({ "displayOrder": { "$gt": val } }); return this; } - withDisplayOrderGreaterThanOrEqualTo(val: any): this { + withDisplayOrderGreaterThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$gte": val } }); return this; } - withDisplayOrderLessThan(val: any): this { + withDisplayOrderLessThan(val: Decimal): this { this.filters.push({ "displayOrder": { "$lt": val } }); return this; } - withDisplayOrderLessThanOrEqualTo(val: any): this { + withDisplayOrderLessThanOrEqualTo(val: Decimal): this { this.filters.push({ "displayOrder": { "$lte": val } }); return this; } - withDisplayOrderBetween(lower: any, upper: any): this { + withDisplayOrderBetween(lower: Decimal, upper: Decimal): this { this.filters.push({ "displayOrder": { "$between": [lower, upper] } }); return this; } @@ -649,47 +658,47 @@ export class SchoolTypeRequest { return this; } - withVersionIs(val: any): this { + withVersionIs(val: unknown): this { this.filters.push({ "version": { "$eq": val } }); return this; } - withVersionIsNot(val: any): this { + withVersionIsNot(val: unknown): this { this.filters.push({ "version": { "$ne": val } }); return this; } - withVersionIn(...vals: any[]): this { + withVersionIn(...vals: unknown[]): this { this.filters.push({ "version": { "$in": vals } }); return this; } - withVersionNotIn(...vals: any[]): this { + withVersionNotIn(...vals: unknown[]): this { this.filters.push({ "version": { "$notIn": vals } }); return this; } - withVersionGreaterThan(val: any): this { + withVersionGreaterThan(val: unknown): this { this.filters.push({ "version": { "$gt": val } }); return this; } - withVersionGreaterThanOrEqualTo(val: any): this { + withVersionGreaterThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$gte": val } }); return this; } - withVersionLessThan(val: any): this { + withVersionLessThan(val: unknown): this { this.filters.push({ "version": { "$lt": val } }); return this; } - withVersionLessThanOrEqualTo(val: any): this { + withVersionLessThanOrEqualTo(val: unknown): this { this.filters.push({ "version": { "$lte": val } }); return this; } - withVersionBetween(lower: any, upper: any): this { + withVersionBetween(lower: unknown, upper: unknown): this { this.filters.push({ "version": { "$between": [lower, upper] } }); return this; } @@ -842,7 +851,7 @@ export class SchoolTypeRequest { } groupByPlatformAs(retName: string): this { - this.query.groupBy("platform"); // In TS we don't alias group by yet natively + this.query.groupBy("platform", retName); return this; } groupById(): this { @@ -851,7 +860,7 @@ export class SchoolTypeRequest { } groupByIdAs(retName: string): this { - this.query.groupBy("id"); // In TS we don't alias group by yet natively + this.query.groupBy("id", retName); return this; } groupByName(): this { @@ -860,7 +869,7 @@ export class SchoolTypeRequest { } groupByNameAs(retName: string): this { - this.query.groupBy("name"); // In TS we don't alias group by yet natively + this.query.groupBy("name", retName); return this; } groupByCode(): this { @@ -869,7 +878,7 @@ export class SchoolTypeRequest { } groupByCodeAs(retName: string): this { - this.query.groupBy("code"); // In TS we don't alias group by yet natively + this.query.groupBy("code", retName); return this; } groupByDisplayOrder(): this { @@ -878,7 +887,7 @@ export class SchoolTypeRequest { } groupByDisplayOrderAs(retName: string): this { - this.query.groupBy("displayOrder"); // In TS we don't alias group by yet natively + this.query.groupBy("displayOrder", retName); return this; } groupByVersion(): this { @@ -887,14 +896,14 @@ export class SchoolTypeRequest { } groupByVersionAs(retName: string): this { - this.query.groupBy("version"); // In TS we don't alias group by yet natively + this.query.groupBy("version", retName); return this; } // --- Facets --- facetByPlatformAs( facetName: string, - request: { toQuery(): SelectQuery }, + request: { readonly entityName: "Platform"; toQuery(): SelectQuery }, includeAllFacets = true, ): this { this.query.facetBy(facetName, "platform", request, includeAllFacets, @@ -1010,9 +1019,10 @@ export class ExecutableSchoolTypeRequest { return this; } - newEntity(context: UserContext): SchoolType { + async newEntity(context: UserContext): Promise { this.ensureIntent(); - return new SchoolType(); + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for creation"); + return SchoolType.teaqlCreate(context); } executeForList(context: UserContext): Promise> { diff --git a/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts b/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts index 9e03a4e5cb463203c4cf7323fbb77a4e98d2b952..2ff822eb0deb888082751850f2be8bf6d1941bd3 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/runtime-module.ts @@ -1,3 +1,4 @@ +import { compareDecimals, decimal, compareLongs, long, localTime } from './teaql-ts'; import { ObjectLocation, RuntimeModule } from "teaql-ts"; import { ENTITY_SCHEMAS } from "./teaql-schemas"; import { ensureGeneratedBootstrap } from "./generated-bootstrap"; @@ -144,7 +145,7 @@ export const GENERATED_RUNTIME_MODULE = new RuntimeModule(ENTITY_SCHEMAS, { }, { ...{ defaultDomainRoot: { entity: "Platform", id: "1", values: { "name": "Campus Learning Platform", "baseUrl": "https://campus.example.com", "createTime": "createTime()", "updateTime": "updateTime()" } }, constants: [ - { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary", "code": "PRIMARY", "displayOrder": 1 } }, - { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": 2 } } + { entity: "SchoolType", id: "1001", values: { "platform": "1", "name": "Primary", "code": "PRIMARY", "displayOrder": decimal("1") } }, + { entity: "SchoolType", id: "1002", values: { "platform": "1", "name": "Secondary", "code": "SECONDARY", "displayOrder": decimal("2") } } ] }, ensure: ensureGeneratedBootstrap }); \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts b/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts index 0db809a1f8d42c9bd27a9aa417b6bd1e8ff22274..9f6a8214932a8e5921179be30427af2a95ece424 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/teaql-schemas.ts @@ -10,13 +10,13 @@ export const ENTITY_SCHEMAS: Record = { "SchoolType": { table: "school_type_data", auditMaskFields: [], - columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "number", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "code": { columnName: "code", modelName: "code", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "displayOrder": { columnName: "display_order", modelName: "display_order", logPolicy: "plain", logicalType: "decimal", decode: "decimal", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolList": { targetEntity: "School", localKey: "id", foreignKey: "schoolType", many: true }} }, "School": { table: "school_data", auditMaskFields: ["name"], - columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, + columns: {"id": { columnName: "id", modelName: "id", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "platform": { columnName: "platform", modelName: "platform", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "schoolType": { columnName: "school_type", modelName: "school_type", logPolicy: "plain", logicalType: "integer", decode: "string", nullable: false }, "name": { columnName: "name", modelName: "name", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "address": { columnName: "address", modelName: "address", logPolicy: "plain", logicalType: "text", decode: "native", nullable: false }, "establishedDate": { columnName: "established_date", modelName: "established_date", logPolicy: "plain", logicalType: "date", decode: "date", nullable: false }, "studentCapacity": { columnName: "student_capacity", modelName: "student_capacity", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false, integer32: true }, "active": { columnName: "active", modelName: "active", logPolicy: "plain", logicalType: "boolean", decode: "native", nullable: false }, "createTime": { columnName: "create_time", modelName: "create_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "updateTime": { columnName: "update_time", modelName: "update_time", logPolicy: "plain", logicalType: "datetime", decode: "date", nullable: false }, "version": { columnName: "version", modelName: "version", logPolicy: "plain", logicalType: "integer", decode: "number", nullable: false }}, relations: {"platform": { targetEntity: "Platform", localKey: "platform", foreignKey: "id", many: false }, "schoolType": { targetEntity: "SchoolType", localKey: "schoolType", foreignKey: "id", many: false }} } }; \ No newline at end of file diff --git a/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts b/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts index b54a29ac3c12fb072cf4c292e22bb2e644b56319..9983b00b27c90dc429fca76441f2bf077f825921 100644 --- a/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts +++ b/source/teaql-ts/examples/facet-trace/lib/src/teaql-ts.ts @@ -1,14 +1,26 @@ import { - CheckException, EntityChecker, RuntimeModule, + CheckException, EntityChecker, RuntimeModule, ContextSchemaProvider, SelectQuery as RuntimeSelectQuery, UserContext, - executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, + GraphCommittedError, executeRelationFacets, QueryRequest, MutationIntent, MutationRequest, GraphMutationSession, MutationFieldLayout, + EntityVersion, entityVersion, nextEntityVersion, MutationVersionError, compareLongs, ModeledInteger32Layout, internalId, } from "teaql-ts"; export { CheckException, EntityRoot, ObjectLocation, SmartList, UserContext, executeRelationFacets, MutationIntent } from "teaql-ts"; -export { GraphMutationSession, LoadedScalarSnapshot, MutationTraceScope } from "teaql-ts"; +export { decimal, compareDecimals } from "teaql-ts"; +export type { Decimal } from "teaql-ts"; +export { long, compareLongs, localTime } from "teaql-ts"; +export type { Long, LocalTime } from "teaql-ts"; +export { entityVersion, nextEntityVersion } from "teaql-ts"; +export { internalId } from "teaql-ts"; +export { EntityCreation, EntityCreationError } from "teaql-ts"; +export { integer32Error } from "teaql-ts"; +export type { EntityVersion } from "teaql-ts"; +export { GraphCommittedError, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationTraceScope, QueryIntent, QueryRequest, RequestIntentError } from "teaql-ts"; +export { ExpressionPath, TeaQLNotLoadedError } from "teaql-ts"; export type { EntityKey } from "teaql-ts"; export type { TeaQLPage } from "teaql-ts"; import type { QueryOperation } from "teaql-ts"; +import type { EntitySchema } from "teaql-ts/sql/core"; function soundex(input: unknown): string { const text = String(input ?? "").toUpperCase().replace(/[^A-Z]/g, ""); @@ -41,7 +53,8 @@ export class SelectQuery extends RuntimeSelectQuery { } export interface TeaQLDataService { - executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise; + reserveInternalId(entity: string, context: UserContext): Promise; + executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise; preflightMutation(mutation: any): any; afterGraphCommit(work: () => void): void; afterGraphRollback(work: () => void): void; @@ -52,18 +65,24 @@ export interface TeaQLDataService { close?(): Promise; } -export class TeaQLClient implements TeaQLDataService { +export class TeaQLClient extends ContextSchemaProvider implements TeaQLDataService { private data: Record> = {}; private nextIds: Record = {}; private readonly checkers: Record = {}; + private readonly schemas: Record = {}; private userContext = new UserContext(); private graphSaveActive = false; + private activeGraph?: GraphMutationSession; private graphCommitActions: Array<() => void> = []; private graphRollbackActions: Array<() => void> = []; + private graphAuditActions: Array<() => Promise> = []; private graphSaveTail: Promise = Promise.resolve(); private readonly mutationGovernanceEvents: any[] = []; + private readonly auditEvents: Readonly>[] = []; + private auditSink?: (event: Readonly>) => void | Promise; constructor(private storagePath?: string) { + super(); if (storagePath) { const fs = require("fs"); if (fs.existsSync(storagePath)) { @@ -76,10 +95,74 @@ export class TeaQLClient implements TeaQLDataService { /** Installs passive generated metadata. It never mutates storage. */ install(module: RuntimeModule): this { + this.installBootstrap(module.bootstrap); Object.assign(this.checkers, module.checkers); + Object.assign(this.schemas, module.schemas); return this; } + protected enterSchemaContext(context: UserContext): () => void { + const previous = this.userContext; + this.userContext = context; + return () => { this.userContext = previous; }; + } + + protected async ensurePhysicalSchema(_context: UserContext): Promise { + // JSON/in-memory storage has no physical DDL. The runtime still requires + // the explicit Context invocation before running generated bootstrap. + } + + private storagePayload(entity: string, payload: Record): Record { + const values = { ...payload }; + for (const relation of Object.values(this.schemas[entity]?.relations || {})) { + if (relation.many) continue; + const modelName = this.schemas[entity]?.columns[relation.localKey]?.modelName; + const field = modelName && Object.prototype.hasOwnProperty.call(values, modelName) + ? modelName : relation.localKey; + if (!Object.prototype.hasOwnProperty.call(values, field)) continue; + const value = values[field]; + if (value === null || value === undefined || typeof value !== "object") continue; + if (value.id === null || value.id === undefined) { + throw new Error(`Unresolved relation identity: ${entity}.${field}`); + } + values[field] = String(value.id); + } + return values; + } + + /** Physical/model keys stay canonical; generated entities use native TS members. */ + private runtimeRecord(entity: string, record: Record): Record { + const columns = this.schemas[entity]?.columns; + if (!columns) return { ...record }; + const result: Record = {}; + for (const [name, column] of Object.entries(columns)) { + const key = column.modelName ?? name; + result[name] = Object.prototype.hasOwnProperty.call(record, key) ? record[key] + : Object.prototype.hasOwnProperty.call(record, name) ? record[name] : null; + } + if (result.version != null) result.version = entityVersion(result.version); + return result; + } + + private checkedMutationVersion(mutation: any): EntityVersion | undefined { + if (mutation.action === "Create") return undefined; + if (!["Update", "Delete", "Recover"].includes(mutation.action)) return undefined; + const version = entityVersion(mutation.version !== undefined ? mutation.version : mutation.expectedVersion); + if (mutation.version !== undefined && mutation.expectedVersion !== undefined + && version !== entityVersion(mutation.expectedVersion)) throw new MutationVersionError("invalid_type"); + nextEntityVersion(mutation.action, version); + return version; + } + + private sealMutationVersion(mutation: any, original: EntityVersion | undefined): any { + Object.defineProperties(mutation, { + version: { value: original, enumerable: true, writable: false, configurable: false }, + expectedVersion: { value: original, enumerable: mutation.expectedVersion !== undefined, writable: false, configurable: false }, + action: { value: mutation.action, enumerable: true, writable: false, configurable: false }, + }); + return mutation; + } + setUserContext(context: UserContext): this { this.userContext = context; return this; @@ -89,6 +172,33 @@ export class TeaQLClient implements TeaQLDataService { return [...this.mutationGovernanceEvents]; } + get auditTrace(): ReadonlyArray>> { return [...this.auditEvents]; } + setAuditSink(sink: (event: Readonly>) => void | Promise): this { + this.auditSink = sink; + return this; + } + + async reserveInternalId(entity: string, context: UserContext): Promise { + if (!(context instanceof UserContext)) throw new TypeError("UserContext is required for ID reservation"); + if (!entity || entity !== entity.trim()) throw new TypeError("Internal ID entity type is required"); + if (this.graphSaveActive) throw new Error("Internal ID reservation is not allowed inside an active graph save"); + const predecessor = this.graphSaveTail; + let release!: () => void; + this.graphSaveTail = new Promise(resolve => { release = resolve; }); + await predecessor; + const previous = this.nextIds[entity]; + try { + const id = internalId(previous ?? 1); + this.nextIds[entity] = Number(id) + 1; + this.persist(); + return id; + } catch (error) { + if (previous === undefined) delete this.nextIds[entity]; + else this.nextIds[entity] = previous; + throw error; + } finally { release(); } + } + private persist() { if (!this.storagePath) return; const fs = require("fs"); @@ -99,8 +209,15 @@ export class TeaQLClient implements TeaQLDataService { fs.renameSync(temporaryPath, this.storagePath); } - async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise): Promise { + async executeGraphSave(intent: MutationIntent, work: (graph: GraphMutationSession) => Promise, prepare?: (graph: GraphMutationSession) => void | Promise, admit?: (graph: GraphMutationSession) => boolean): Promise { const graph = new GraphMutationSession(intent); + const executionContext = this.userContext; + graph.bindExecutionReference(() => this.userContext); + graph.bindExecutionMetadata(() => ({schemas: this.schemas, checkerNames: Object.keys(this.checkers).sort()})); + for (const name of Object.keys(this.checkers)) { + graph.bindExecutionReference(() => this.checkers[name]); + graph.bindExecutionReference(() => this.checkers[name]?.checkAndFix); + } const predecessor = this.graphSaveTail; let release!: () => void; this.graphSaveTail = new Promise(resolve => { release = resolve; }); @@ -109,32 +226,57 @@ export class TeaQLClient implements TeaQLDataService { const nextIdsSnapshot = { ...this.nextIds }; let fixEvidenceStarted = false; let mutationPolicyGraphStarted = false; + let committed = false; try { + graph.validatePreparedSources(); this.graphSaveActive = true; + this.activeGraph = graph; this.graphCommitActions = []; this.graphRollbackActions = []; - this.userContext.insertResource("fixTime", new Date()); - this.userContext.beginFixEvidence(); - fixEvidenceStarted = true; - this.userContext.beginMutationPolicyGraph(); + this.graphAuditActions = []; + const pending = admit?.(graph); + if (admit && typeof pending !== "boolean") throw new Error("GRAPH_ADMISSION_RESULT_REQUIRED"); + graph.captureInputSources(); + if (pending === false) { graph.sealPreparedGraph(); return await work(graph); } + // Reject a competing Context owner before changing its Fix resources. + executionContext.beginMutationPolicyGraph(); mutationPolicyGraphStarted = true; + executionContext.insertResource("fixTime", executionContext.businessTime()); + executionContext.beginFixEvidence(); + fixEvidenceStarted = true; + await prepare?.(graph); + if (prepare && !graph.isPreparedSealed) graph.sealPreparedGraph(); + executionContext.prepareMutationPolicyGraph(graph.preparedRootEntity); + graph.validatePreparedSources(); const result = await work(graph); - this.userContext.ensureMutationPolicyGraphComplete(); - this.persist(); - for (const action of this.graphCommitActions) action(); + graph.requirePreparedComplete(); + executionContext.ensureMutationPolicyGraphComplete(); + if (!graph.isPreparedEmpty) this.persist(); + committed = true; + let failure: unknown; + let failed = false; + for (const action of [...this.graphCommitActions, ...this.graphAuditActions]) { + try { await action(); } catch (error) { if (!failed) failure = error; failed = true; } + } + if (failed) throw new GraphCommittedError(failure); return result; } catch (error) { - this.data = dataSnapshot; - this.nextIds = nextIdsSnapshot; - for (const action of [...this.graphRollbackActions].reverse()) action(); + if (!committed) { + this.data = dataSnapshot; + this.nextIds = nextIdsSnapshot; + for (const action of [...this.graphRollbackActions].reverse()) { + try { action(); } catch { /* retain the original failure */ } + } + } throw error; } finally { this.graphSaveActive = false; + this.activeGraph = undefined; this.graphCommitActions = []; this.graphRollbackActions = []; - if (mutationPolicyGraphStarted) this.userContext.endMutationPolicyGraph(); - this.userContext.removeResource("fixTime"); - if (fixEvidenceStarted) this.userContext.finishFixEvidence(); + this.graphAuditActions = []; + if (mutationPolicyGraphStarted) executionContext.endMutationPolicyGraph(); + if (fixEvidenceStarted) executionContext.removeResource("fixTime").finishFixEvidence(); release(); } } @@ -150,84 +292,145 @@ export class TeaQLClient implements TeaQLDataService { } preflightMutation(mutation: any): any { - mutation = this.checkAndFixMutation(mutation); - this.userContext.recordMutationPolicyPreflight(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.recordPreparedMutation(); + mutation = this.checkAndFixMutation(request); + if (request.graphSession) { + const values = [...Object.values(mutation.payload || {}), ...Object.values(request.loadedValues())]; + request.graphSession.captureLogBindings({ parameterizedSQL: "", sqlOrigin: "generated", + parameters: values, parameterLogPolicies: values.map(() => "unknown" as const) }); + } + const schema = this.schemas[mutation.entity]; + const references = Object.fromEntries(Object.values(schema?.relations ?? {}).filter(relation => !relation.many) + .map(relation => [schema.columns[relation.localKey]?.modelName ?? relation.localKey, relation.targetEntity])); + const policyMutation = request.graphSession ? request.graphSession.capturePreparedMutation(request, mutation, references) : mutation; + this.userContext.recordMutationPolicyPreflight(policyMutation); return mutation; } private checkAndFixMutation(mutation: any): any { - if (mutation instanceof MutationRequest) mutation = mutation.mutation; - if (!String(mutation?.comment || "").trim()) throw new Error("Security audit failure: audit reason is required before mutation"); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + if (request.graphSession !== this.activeGraph || (this.graphSaveActive && !request.graphSession)) { + throw new Error("GRAPH_MUTATION_SESSION_REQUIRED: use the explicit active graph request capability"); + } + const prepared = request.graphSession?.replayPreparedMutation(request); + if (prepared) return prepared; + mutation = request.mutation; + const schema = this.schemas[String(mutation.entity)]; + if (schema) { + const fields = new MutationFieldLayout(String(mutation.entity), Object.entries(schema.columns).map(([name, column]) => column.modelName ?? name)); + fields.validate(mutation.payload ?? {}, mutation.action === "Update"); + if (mutation.ledgerKey && mutation.ledgerRoot) { + if (mutation.ledgerKey.entity !== mutation.entity) throw new Error("MUTATION_LAYOUT_OWNER_MISMATCH"); + fields.validate(mutation.ledgerRoot.change(mutation.ledgerKey), mutation.action === "Update"); + } + } + const originalVersion = this.checkedMutationVersion(mutation); mutation = { ...mutation, payload: { ...(mutation?.payload || {}) } }; - const checker = this.checkers[String(mutation.entity)]; - if (!checker) return mutation; + request.bindCheckerLoadedValues(mutation); + Object.defineProperty(mutation, "comment", { value: request.comment, enumerable: true }); + const declaringEntityType = String(mutation.entity); + const width = new ModeledInteger32Layout(declaringEntityType, schema); + const checker = this.checkers[declaringEntityType]; + if (!checker) { + const violations = width.checkMutation(mutation.payload || {}); + if (violations.length) throw new CheckException(violations); + return this.sealMutationVersion(mutation, originalVersion); + } const results: any[] = []; const ownsFixTime = this.userContext.getResource("fixTime") === undefined; - if (ownsFixTime) this.userContext.insertResource("fixTime", new Date()).beginFixEvidence(); + if (ownsFixTime) this.userContext.insertResource("fixTime", this.userContext.businessTime()).beginFixEvidence(); try { checker.checkAndFix(this.userContext, mutation, results); - if (mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); - this.userContext.translateCheckResults(results); + if (mutation.action !== request.mutation.action || this.checkedMutationVersion(mutation) !== originalVersion) + throw new MutationVersionError("invalid_type"); + width.checkMutation(mutation.payload || {}, results); + this.userContext.translateCheckResults(results, declaringEntityType); if (results.length) throw new CheckException(results); - return mutation; + // Loaded Delete values are validation/audit input, never field-write intent. + if (mutation.action !== "Delete" && mutation.ledgerKey && mutation.ledgerRoot) for (const [field, value] of Object.entries(mutation.payload)) mutation.ledgerRoot.set(mutation.ledgerKey, field, value); + return this.sealMutationVersion(mutation, originalVersion); } finally { if (ownsFixTime) this.userContext.removeResource("fixTime").finishFixEvidence(); } } async executeMutation(mutation: any): Promise { - mutation = this.checkAndFixMutation(mutation); + const request = mutation instanceof MutationRequest ? mutation : new MutationRequest(mutation); + request.graphSession?.requireMutationAllowed(); + mutation = this.checkAndFixMutation(request); + const nextVersion = nextEntityVersion(mutation.action, mutation.version); const mutationGovernance = this.userContext.enterMutationPolicy(mutation); - this.mutationGovernanceEvents.push(mutationGovernance); const table = this.data[mutation.entity] ||= {}; + const payload = this.storagePayload(mutation.entity, mutation.payload); if (mutation.action === "Create") { const id = mutation.id ?? String(this.nextIds[mutation.entity] || 1); - this.nextIds[mutation.entity] = Number(id) + 1; - const record = { ...mutation.payload, id: String(id), version: Number(mutation.version || 0) + 1 }; + if (table[String(id)]) throw new Error(`${mutation.entity}(${id}) already exists`); + this.nextIds[mutation.entity] = Math.max(this.nextIds[mutation.entity] || 1, Number(id) + 1); + const record = { ...payload, id: String(id), version: nextVersion }; table[String(id)] = record; if (!this.graphSaveActive) this.persist(); - return { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }; - } - if (mutation.action === "Update") { - const id = String(mutation.id); - if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { - throw new Error( - `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); - } - table[id] = { ...table[id], ...mutation.payload, id, version: Number(table[id].version || 0) + 1 }; - if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id: String(id), version: record.version, persistedRecord: { ...record } }); } - if (mutation.action === "Delete") { + if (["Update", "Delete", "Recover"].includes(mutation.action)) { const id = String(mutation.id); if (!table[id]) throw new Error(`${mutation.entity}(${id}) does not exist`); - const expectedVersion = Number(mutation.version); - const currentVersion = Number(table[id].version || 0); - if (!Number.isFinite(expectedVersion) || expectedVersion !== currentVersion) { + const expectedVersion = entityVersion(mutation.version); + const currentVersion = entityVersion(table[id].version); + if (expectedVersion !== currentVersion) { throw new Error( `Optimistic lock conflict for ${mutation.entity}(${id}): expected ${expectedVersion}, current ${currentVersion}`); } - table[id] = { ...table[id], id, version: -(currentVersion + 1) }; + table[id] = { ...table[id], ...(mutation.action === "Update" ? payload : {}), id, version: nextVersion }; if (!this.graphSaveActive) this.persist(); - return { success: true, id, version: table[id].version, deleted: true, persistedRecord: { ...table[id] } }; + return this.finishMutation(request, mutation, mutationGovernance, + { success: true, id, version: table[id].version, deleted: mutation.action === "Delete", persistedRecord: { ...table[id] } }); } throw new Error(`Unsupported mutation action: ${mutation.action}`); } + private async finishMutation(request: MutationRequest, mutation: any, + mutationGovernance: unknown, result: any): Promise { + request.graphSession?.recordPreparedResult(request, result); + const event = Object.freeze({ entity: mutation.entity, action: mutation.action, + id: result.id, version: result.version, + ...request.auditProjection({ entity: mutation.entity, id: result.id }, mutation.payload), + changedFields: Object.freeze(Object.keys(mutation.payload || {}).sort()), + mutationGovernance, + actor: this.userContext.getResource("bootstrapActor"), + category: this.userContext.getResource("bootstrapCategory"), + recordedAt: (this.userContext.getResource("fixTime") ?? new Date()).toISOString() }); + const publish = async () => { + this.mutationGovernanceEvents.push(mutationGovernance); + this.auditEvents.push(event); + await this.auditSink?.(event); + }; + if (request.graphSession) this.graphAuditActions.push(publish); + else { try { await publish(); } catch (error) { throw new GraphCommittedError(error); } } + return { ...result, persistedRecord: this.runtimeRecord(mutation.entity, result.persistedRecord) }; + } async query(context: any, req: any): Promise { return { rows: [] }; } async executeQuery(query: any): Promise { + const request = query instanceof QueryRequest ? query : new QueryRequest(query); + query = request.query; if (!(query instanceof RuntimeSelectQuery)) { throw new Error("TeaQL list execution requires the formal runtime SelectQuery"); } query.prepareForList(); - let rows = Object.values(this.data[query.entity] || {}).map((row: any) => ({ ...row })); + const visibility = query.deletionVisibility ?? "live"; + if (!["live", "all", "deleted"].includes(visibility)) throw new Error("QUERY_INVALID_DELETION_VISIBILITY"); + let rows = Object.values(this.data[query.entity] || {}).map((row: any) => this.runtimeRecord(query.entity, row)); + if (this.schemas[query.entity]?.columns.version && visibility !== "all") rows = rows.filter(row => + compareLongs(String(row.version), "0") === (visibility === "deleted" ? -1 : 1)); const matches = (row: any, expression: any): boolean => { if (expression?.$and) return expression.$and.every((item: any) => matches(row, item)); return Object.entries(expression || {}).every(([field, predicate]: [string, any]) => { - if (predicate?.$eq !== undefined) return row[field] === (predicate.$eq?.id ?? predicate.$eq); - if (predicate?.$ne !== undefined) return row[field] !== (predicate.$ne?.id ?? predicate.$ne); + const compare = (value: any): number => field === "version" && value != null && row[field] != null + ? compareLongs(String(entityVersion(row[field])), String(entityVersion(value))) + : row[field] === (value?.id ?? value) ? 0 : row[field] > (value?.id ?? value) ? 1 : -1; + const equal = (value: any): boolean => field === "version" ? compare(value) === 0 : row[field] === (value?.id ?? value); + if (predicate?.$eq !== undefined) return equal(predicate.$eq); + if (predicate?.$ne !== undefined) return !equal(predicate.$ne); if (predicate?.$contains !== undefined) return String(row[field] ?? "").includes(String(predicate.$contains)); if (predicate?.$notContains !== undefined) return !String(row[field] ?? "").includes(String(predicate.$notContains)); if (predicate?.$startsWith !== undefined) return String(row[field] ?? "").startsWith(String(predicate.$startsWith)); @@ -235,15 +438,17 @@ export class TeaQLClient implements TeaQLDataService { if (predicate?.$endsWith !== undefined) return String(row[field] ?? "").endsWith(String(predicate.$endsWith)); if (predicate?.$notEndsWith !== undefined) return !String(row[field] ?? "").endsWith(String(predicate.$notEndsWith)); if (predicate?.$soundLike !== undefined) return soundex(row[field]) === soundex(predicate.$soundLike); - if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => row[field] === (value?.id ?? value)); - if (predicate?.$between !== undefined) return row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; + if (predicate?.$in !== undefined) return predicate.$in.some((value: any) => equal(value)); + if (predicate?.$notIn !== undefined) return !predicate.$notIn.some((value: any) => equal(value)); + if (predicate?.$between !== undefined) return field === "version" + ? compare(predicate.$between[0]) >= 0 && compare(predicate.$between[1]) <= 0 + : row[field] >= predicate.$between[0] && row[field] <= predicate.$between[1]; if (predicate?.$isNull === true) return row[field] === null || row[field] === undefined; if (predicate?.$isNull === false) return row[field] !== null && row[field] !== undefined; - if (predicate?.$gt !== undefined) return row[field] > predicate.$gt; - if (predicate?.$gte !== undefined) return row[field] >= predicate.$gte; - if (predicate?.$lt !== undefined) return row[field] < predicate.$lt; - if (predicate?.$lte !== undefined) return row[field] <= predicate.$lte; + if (predicate?.$gt !== undefined) return field === "version" ? compare(predicate.$gt) > 0 : row[field] > predicate.$gt; + if (predicate?.$gte !== undefined) return field === "version" ? compare(predicate.$gte) >= 0 : row[field] >= predicate.$gte; + if (predicate?.$lt !== undefined) return field === "version" ? compare(predicate.$lt) < 0 : row[field] < predicate.$lt; + if (predicate?.$lte !== undefined) return field === "version" ? compare(predicate.$lte) <= 0 : row[field] <= predicate.$lte; return true; }); }; @@ -257,17 +462,19 @@ export class TeaQLClient implements TeaQLDataService { }))]; } for (const order of [...query.orderItems].reverse()) { - rows.sort((a, b) => (a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); + rows.sort((a, b) => (order.field === "version" ? compareLongs(String(a.version), String(b.version)) + : a[order.field] === b[order.field] ? 0 : a[order.field] > b[order.field] ? 1 : -1) * (String(order.direction).toLowerCase() === "desc" ? -1 : 1)); } const start = query.offsetValue || 0; rows = rows.slice(start, start + query.limitValue); for (const relation of (query.relations || []) as any[]) { - const localValues = new Set(rows.map((row: any) => row[relation.localKey || "id"])); - const relatedRows = (await this.executeQuery(relation.query)).filter( - (row: any) => localValues.has(row[relation.foreignKey || "id"])); for (const row of rows) { - const matches = relatedRows.filter( - (related: any) => related[relation.foreignKey || "id"] === row[relation.localKey || "id"]); + // Scope before ordering/offset/limit. A nested bound belongs to + // each parent, not to unrelated children from earlier saves. + const childQuery = relation.query.clone(); + childQuery.filter({$and: [childQuery.filterCondition ?? {}, + {[relation.foreignKey || "id"]: {$eq: row[relation.localKey || "id"]}}]}); + const matches = await this.executeQuery(request.derive(childQuery, relation.name)); row[relation.name] = relation.many === false ? matches[0] : matches; } } @@ -277,6 +484,8 @@ export class TeaQLClient implements TeaQLDataService { rows = rows.map((row: any) => Object.fromEntries( Object.entries(row).filter(([field]) => selections.has(field)))); } + const width = new ModeledInteger32Layout(query.entity, this.schemas[query.entity]); + for (const row of rows) for (const field of Object.keys(row)) row[field] = width.read(field, row[field]); return rows; } async executeCount(query: any, countAlias?: string, operation?: QueryOperation): Promise { @@ -294,6 +503,7 @@ export class TeaQLClient implements TeaQLDataService { return value; } async *executeForStream(query: any, chunkSize = 1000): AsyncIterable { + query = (query instanceof QueryRequest ? query : new QueryRequest(query)).query; if (!Number.isInteger(chunkSize) || chunkSize <= 0) throw new Error("stream chunk size must be a positive integer"); const rows = await this.executeQuery(query); for (let offset = 0; offset < rows.length; offset += chunkSize) { diff --git a/source/teaql-ts/examples/facet-trace/package-lock.json b/source/teaql-ts/examples/facet-trace/package-lock.json index 6409164a882a292dd0343d2b27ba84ef81e4d2a5..d35d7f521190fa1ac051882c9c18577f0c198cd7 100644 --- a/source/teaql-ts/examples/facet-trace/package-lock.json +++ b/source/teaql-ts/examples/facet-trace/package-lock.json @@ -6,29 +6,35 @@ "": { "name": "teaql-generated-facet-trace-example", "dependencies": { - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "teaql-ts": "file:../.." }, "devDependencies": { "@types/better-sqlite3": "^7.6.12", "@types/node": "^22.0.0", "typescript": "5.4.5" + }, + "engines": { + "node": ">=22" } }, "../..": { "name": "@teaql/teaql", - "version": "0.3.0", + "version": "0.3.1", "license": "Apache-2.0", "dependencies": { "node-fetch": "^2.7.0" }, "devDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", "@opentelemetry/api-logs": "^0.221.0", "@opentelemetry/context-async-hooks": "^2.10.0", "@opentelemetry/core": "^2.10.0", "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", "@opentelemetry/resources": "^2.10.0", "@opentelemetry/sdk-logs": "^0.221.0", "@opentelemetry/sdk-metrics": "^2.10.0", @@ -38,7 +44,7 @@ "@types/jest": "^29.5.0", "@types/node-fetch": "^2.6.13", "@types/pg": "^8.11.0", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "jest": "^29.5.0", "jest-util": "^29.7.0", @@ -50,6 +56,8 @@ "typescript": "5.4.5" }, "peerDependencies": { + "@aws-sdk/client-s3": "3.1151.0", + "@aws-sdk/s3-request-presigner": "3.1151.0", "@opentelemetry/api": "^1.9.1", "@opentelemetry/api-logs": "^0.221.0", "@opentelemetry/context-async-hooks": "^2.10.0", @@ -57,18 +65,25 @@ "@opentelemetry/exporter-logs-otlp-http": "^0.221.0", "@opentelemetry/exporter-metrics-otlp-http": "^0.221.0", "@opentelemetry/exporter-trace-otlp-http": "^0.221.0", + "@opentelemetry/otlp-transformer": "0.221.0", "@opentelemetry/resources": "^2.10.0", "@opentelemetry/sdk-logs": "^0.221.0", "@opentelemetry/sdk-metrics": "^2.10.0", "@opentelemetry/sdk-trace-base": "^2.10.0", "@sqlite.org/sqlite-wasm": "3.53.0-build1", - "better-sqlite3": "^12.10.0", + "better-sqlite3": "^13.0.3", "expo-sqlite": "*", "mysql2": "^3.11.0", "pg": "^8.12.0", "pg-query-stream": "^4.7.0" }, "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/s3-request-presigner": { + "optional": true + }, "@opentelemetry/api": { "optional": true }, @@ -90,6 +105,9 @@ "@opentelemetry/exporter-trace-otlp-http": { "optional": true }, + "@opentelemetry/otlp-transformer": { + "optional": true + }, "@opentelemetry/resources": { "optional": true }, @@ -142,450 +160,31 @@ "undici-types": "~6.21.0" } }, - "node_modules/base64-js": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", - "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, "node_modules/better-sqlite3": { - "version": "12.11.1", - "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.11.1.tgz", - "integrity": "sha512-dq9AtApgg5PGFtBzPFSBl3HZQjHok5gaQCM6zh2Yk0aSmDCs1CbnVI8/HgASQkNKsWFpseIO9beg5xxpYhbIfA==", - "hasInstallScript": true, - "license": "MIT", - "dependencies": { - "bindings": "^1.5.0", - "prebuild-install": "^7.1.1" - }, - "engines": { - "node": "20.x || 22.x || 23.x || 24.x || 25.x || 26.x" - } - }, - "node_modules/bindings": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/bindings/-/bindings-1.5.0.tgz", - "integrity": "sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==", - "license": "MIT", - "dependencies": { - "file-uri-to-path": "1.0.0" - } - }, - "node_modules/bl": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/bl/-/bl-4.1.0.tgz", - "integrity": "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==", - "license": "MIT", - "dependencies": { - "buffer": "^5.5.0", - "inherits": "^2.0.4", - "readable-stream": "^3.4.0" - } - }, - "node_modules/buffer": { - "version": "5.7.1", - "resolved": "https://registry.npmjs.org/buffer/-/buffer-5.7.1.tgz", - "integrity": "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "base64-js": "^1.3.1", - "ieee754": "^1.1.13" - } - }, - "node_modules/chownr": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", - "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", - "license": "ISC" - }, - "node_modules/decompress-response": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", - "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", - "license": "MIT", - "dependencies": { - "mimic-response": "^3.1.0" - }, - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/deep-extend": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/deep-extend/-/deep-extend-0.6.0.tgz", - "integrity": "sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==", - "license": "MIT", - "engines": { - "node": ">=4.0.0" - } - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=8" - } - }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/expand-template": { - "version": "2.0.3", - "resolved": "https://registry.npmjs.org/expand-template/-/expand-template-2.0.3.tgz", - "integrity": "sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==", - "license": "(MIT OR WTFPL)", - "engines": { - "node": ">=6" - } - }, - "node_modules/file-uri-to-path": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz", - "integrity": "sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==", - "license": "MIT" - }, - "node_modules/fs-constants": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs-constants/-/fs-constants-1.0.0.tgz", - "integrity": "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==", - "license": "MIT" - }, - "node_modules/github-from-package": { - "version": "0.0.0", - "resolved": "https://registry.npmjs.org/github-from-package/-/github-from-package-0.0.0.tgz", - "integrity": "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==", - "license": "MIT" - }, - "node_modules/ieee754": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/ieee754/-/ieee754-1.2.1.tgz", - "integrity": "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC" - }, - "node_modules/ini": { - "version": "1.3.8", - "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", - "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==", - "license": "ISC" - }, - "node_modules/mimic-response": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", - "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", - "license": "MIT", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/mkdirp-classic": { - "version": "0.5.3", - "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", - "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", - "license": "MIT" - }, - "node_modules/napi-build-utils": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz", - "integrity": "sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==", - "license": "MIT" - }, - "node_modules/node-abi": { - "version": "3.96.0", - "resolved": "https://registry.npmjs.org/node-abi/-/node-abi-3.96.0.tgz", - "integrity": "sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg==", - "license": "MIT", - "dependencies": { - "semver": "^7.3.5" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/prebuild-install": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/prebuild-install/-/prebuild-install-7.1.3.tgz", - "integrity": "sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==", - "deprecated": "No longer maintained. Please contact the author of the relevant native addon; alternatives are available.", - "license": "MIT", - "dependencies": { - "detect-libc": "^2.0.0", - "expand-template": "^2.0.3", - "github-from-package": "0.0.0", - "minimist": "^1.2.3", - "mkdirp-classic": "^0.5.3", - "napi-build-utils": "^2.0.0", - "node-abi": "^3.3.0", - "pump": "^3.0.0", - "rc": "^1.2.7", - "simple-get": "^4.0.0", - "tar-fs": "^2.0.0", - "tunnel-agent": "^0.6.0" - }, - "bin": { - "prebuild-install": "bin.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", "license": "MIT", "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/rc": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/rc/-/rc-1.2.8.tgz", - "integrity": "sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==", - "license": "(BSD-2-Clause OR MIT OR Apache-2.0)", - "dependencies": { - "deep-extend": "^0.6.0", - "ini": "~1.3.0", - "minimist": "^1.2.0", - "strip-json-comments": "~2.0.1" - }, - "bin": { - "rc": "cli.js" - } - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "bin": { - "semver": "bin/semver.js" + "node-addon-api": "^8.0.0" }, "engines": { - "node": ">=10" - } - }, - "node_modules/simple-concat": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", - "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT" - }, - "node_modules/simple-get": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", - "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "dependencies": { - "decompress-response": "^6.0.0", - "once": "^1.3.1", - "simple-concat": "^1.0.0" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/strip-json-comments": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-2.0.1.tgz", - "integrity": "sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==", - "license": "MIT", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/tar-fs": { - "version": "2.1.5", - "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.5.tgz", - "integrity": "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw==", - "license": "MIT", - "dependencies": { - "chownr": "^1.1.1", - "mkdirp-classic": "^0.5.2", - "pump": "^3.0.0", - "tar-stream": "^2.1.4" + "node": ">=22" } }, - "node_modules/tar-stream": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/tar-stream/-/tar-stream-2.2.0.tgz", - "integrity": "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==", + "node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", "license": "MIT", - "dependencies": { - "bl": "^4.0.3", - "end-of-stream": "^1.4.1", - "fs-constants": "^1.0.0", - "inherits": "^2.0.3", - "readable-stream": "^3.1.1" - }, "engines": { - "node": ">=6" + "node": "^18 || ^20 || >= 21" } }, "node_modules/teaql-ts": { "resolved": "../..", "link": true }, - "node_modules/tunnel-agent": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/tunnel-agent/-/tunnel-agent-0.6.0.tgz", - "integrity": "sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==", - "license": "Apache-2.0", - "dependencies": { - "safe-buffer": "^5.0.1" - }, - "engines": { - "node": "*" - } - }, "node_modules/typescript": { "version": "5.4.5", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.4.5.tgz", @@ -606,18 +205,6 @@ "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", "dev": true, "license": "MIT" - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT" - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" } } } diff --git a/source/teaql-ts/examples/facet-trace/package.json b/source/teaql-ts/examples/facet-trace/package.json index 4dc44eeb8da5cc671c1fee80683ceb2542a65192..b79d7d4e370ecd04d83bd21cc4f23e46716ed1eb 100644 --- a/source/teaql-ts/examples/facet-trace/package.json +++ b/source/teaql-ts/examples/facet-trace/package.json @@ -2,6 +2,7 @@ "name": "teaql-generated-facet-trace-example", "private": true, "scripts": {"build": "tsc --project tsconfig.json", "start": "node dist/consumer.js"}, - "dependencies": {"teaql-ts": "file:../..", "better-sqlite3": "^12.10.0"}, + "engines": {"node": ">=22"}, + "dependencies": {"teaql-ts": "file:../..", "better-sqlite3": "^13.0.3"}, "devDependencies": {"typescript": "5.4.5", "@types/node": "^22.0.0", "@types/better-sqlite3": "^7.6.12"} } diff --git a/source/teaql-ts/examples/fix-e-alignment/README.md b/source/teaql-ts/examples/fix-e-alignment/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b0845b2daaff68e362a0597ccf592a552c54b9bd --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/README.md @@ -0,0 +1,85 @@ +# Generated Q/E, Checker and graph-save boundaries + +This example uses the repository runtime and a retained, evaluated three-entity +model. Generated implementations are hash-checked, not edited or searched for +API discovery. Use current model-aware Assist and the handwritten application +probes when adding a case. + +```sh +npm ci +node examples/fix-e-alignment/verify-local.cjs +``` + +The verifier records two rounds on the same SQLite files without resetting +them. Test caches and temporary compiler configuration are removed after the +owned test processes exit. Reports, logs and synthetic databases are retained +at the printed evidence path; shared dependency caches are not deleted. + +`partial-ancestors-probe.ts` distinguishes NotLoaded from a selected empty +relation and saves a complete modified leaf through two untouched partial +ancestors. An incomplete modified leaf is rejected without losing its intent. + +`partial-root-probe.ts` adds the managed-root boundary to that graph. It creates +another real domain root through generated mutation APIs, then changes only the +leaf's product name. Its loaded ownership is absent from the mutation delta, +but must still match the active context. Both wrong-context attempts must fail +without provider queries, transactions, ID allocation, policy lookup/review or +audit delivery. Returning to the original context saves the **same** graph: +only the leaf reaches version 2, both ancestors stay partial at version 1, and +the Business Clock supplies the update time. + +All eleven side-effect counters are positively calibrated, including actual +SQLite BEGIN/COMMIT/ROLLBACK calls. A separate read-only database connection +checks persisted values. Diagnostic access to ledger state and driver spies is +test instrumentation, not application API discovery or business SQL writes. + +The runtime does not define a tenant policy here: `Tenant` is this model's +declared root type. This save-boundary test does not establish query +authorization, untrusted-hydration authorization, full loading conformance, or +private/public package acceptance. + +`unchanged-views-probe.ts` exercises three no-op views: selected null and a +sparse forward edge; a complete owner with another independently pending view; +and an explicitly loaded empty reverse list. Eleven positively calibrated +side-effect counters must remain zero. The same default verifier also injects +two transaction faults, **after a real UPDATE** and immediately before COMMIT. +It checks the uncommitted version, the independently observed rollback, retained +view geometry and optimistic baseline, and a successful retry of the same +object without another query. A genuine commit must advance only the changed +row and use the configured Business Clock. Both rounds retain their SQLite +files; no handwritten business INSERT/UPDATE is used. + +This does not claim typed dynamic-property schemas, persistent dynamic fields, +an application-owned outer transaction, all-provider behavior or performance. + +`checker-boundaries-probe.ts` adds required parent relations, independently omitted +business fields (while ownership stays loaded), untouched partial targets, and +customer Fix values rejected or repaired before generated save. It also installs +Checkers in a separate schema-free store and exercises the public object-local +JSON normalizer with declared aliases, escaped pointers and equal/unequal +collisions in both submitted orders under three profiles. Explicit generated +setters form the input allow-list; this is not recursive HTTP/TFP acceptance. +Each round records 32 cases plus independently read physical rows. The default +verifier runs both rounds without deleting either SQLite store and checks that +generated implementations remain unchanged. + +`graph-fix-idempotence.test.ts` saves a graph with the same child instance +referenced twice. Each object is fixed and persisted once per invocation, using +one Business Clock snapshot; a later update advances both versions exactly +once. Separate contexts can overlap without sharing their Fix snapshots or +receipts. Two distinct modified views of the same ID remain a conflict and are +rejected before provider work. All three cases run twice on retained databases. + +`delete-retry.test.ts` injects a failure after a real file-backed child Delete. +The file, audit history, optimistic baseline and parent version remain unchanged; +the Delete intent survives, but loaded validation values must not become field +writes. Saving the same graph again commits one child tombstone and one audit +event, without reloading or updating the parent. Repeating Delete on the committed +tombstone is rejected before persistence, mutation execution or another audit. +Both rounds use the same retained JSON store, also checked independently. + +`fixture-manifest.json` records the unified generator revision, all 17 exported +file hashes and the previous manifest hash. The four updated generated files +are exact export bytes, including the file-client Delete guard and generated +GroupBy aliases. The prior collector qualification remains historical metadata; +it is not presented as evidence for this export. diff --git a/source/teaql-ts/examples/fix-e-alignment/checker-boundaries-probe.ts b/source/teaql-ts/examples/fix-e-alignment/checker-boundaries-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..faea222b59d122f8639e7fc06d2f0438c8e64b4f --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/checker-boundaries-probe.ts @@ -0,0 +1,253 @@ +import { CheckException, decimal, EntityChecker, FixedBusinessClock, RuntimeModule, TeaQLNotLoadedError, UserContext } from '../../src'; +import { checkResultToWire, CheckResult } from '../../src/core/i18n'; +import { JsonFieldNamingProfile } from '../../src/core/object-location'; +import { createWireEntityMetadata, normalizeWireInput, retainSubmittedPaths, WireInputError } from '../../src/core/wire-fields'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import { GENERATED_RUNTIME_MODULE } from 'generated/runtime-module'; +import Database from 'better-sqlite3'; + +const clock = new Date('2032-02-29T10:15:30Z'); +const profiles: JsonFieldNamingProfile[] = ['camelCase', 'snake_case', 'PascalCase']; + +/** Normal generated saves; private driver access is observation, never business writes. */ +export async function verifyCheckerBoundaries(filename: string): Promise { + const round = Number(process.env.TEAQL_FIX_E_ROUND); + expect([1, 2]).toContain(round); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(clock)); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const driver = (client as any).driver; + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'); + const exec = jest.spyOn(driver.database as Database.Database, 'exec'); + const allocation = jest.spyOn(driver, 'nextId'), policy = jest.spyOn(context, 'enterMutationPolicy'); + const review = jest.fn(() => undefined); + context.withMutationPolicyRegistry({resolve: review}); + let auditStart = 0, checkerCalls = 0, fix: 'none' | 'required-null' | 'min-zero' | 'repair' = 'none'; + const observations: Array> = []; + const record = (name: string, details: Record) => { + const value = {round, case: name, passed: true, ...details}; + observations.push(value); process.stdout.write('CORE_TS_CHECKER_BOUNDARY_CASE=' + JSON.stringify(value) + '\n'); + }; + const effects = () => ({queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + begins: exec.mock.calls.filter(call => /^BEGIN\b/i.test(call[0])).length, + commits: exec.mock.calls.filter(call => /^COMMIT\b/i.test(call[0])).length, + rollbacks: exec.mock.calls.filter(call => /^ROLLBACK\b/i.test(call[0])).length, + allocations: allocation.mock.calls.length, policies: policy.mock.calls.length, + reviews: review.mock.calls.length, audits: client.auditTrace.length - auditStart, + mutations: query.mock.calls.filter(call => /^\s*(?:INSERT INTO|UPDATE|DELETE FROM)\s+(?:tenant_data|purchase_order_data|order_item_data)\b/i + .test(String(call[0]).replace(/"/g, ''))).length}); + const zero = {queries: 0, transactions: 0, begins: 0, commits: 0, rollbacks: 0, + allocations: 0, policies: 0, reviews: 0, audits: 0, mutations: 0}; + const reset = () => {query.mockClear(); transaction.mockClear(); exec.mockClear(); allocation.mockClear(); + policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length; checkerCalls = 0;}; + const physical = () => { + const db = new Database(filename, {readonly: true, fileMustExist: true}); + try {return { + tenant_data: db.prepare('SELECT id,name,version FROM tenant_data ORDER BY id').all(), + purchase_order_data: db.prepare('SELECT id,tenant,contact_phone,internal_note,create_time,update_time,version FROM purchase_order_data ORDER BY id').all(), + order_item_data: db.prepare('SELECT id,purchase_order,tenant,product_name,unit_price,create_time,update_time,version FROM order_item_data ORDER BY id').all(), + };} finally {db.close();} + }; + const owner = async (phone = '5550100') => (await Q.purchaseOrders().comment('Prepare a bounded Checker fixture') + .purpose('Verify admission through generated audited graph saves').newEntity(context)).updateContactPhone(phone); + const item = async (valid = true) => { + const value = (await Q.orderItems().comment('Prepare a generated Checker child') + .purpose('Verify post-Fix business values without application SQL').newEntity(context)).updateUnitPrice(decimal(valid ? '10.00' : '0')); + if (valid) value.updateProductName('Boundary item'); + return value; + }; + const expectRejected = async (save: () => Promise, rule: string, path: string, entity: string) => { + const before = physical(); reset(); let failure: unknown; + try {await save();} catch (error) {failure = error;} + expect(failure).toBeInstanceOf(CheckException); + const results = [...(failure as CheckException).violations]; + const matching = results.find(value => value.ruleId === rule && value.location.modelPath() === path); + expect(matching).toBeDefined(); expect(matching!.entityType).toBe(entity); + expect(effects()).toEqual(zero); expect(physical()).toEqual(before); + expect(context.getResource('fixTime')).toBeUndefined(); + return {result: matching!, results, effects: effects(), checkerCalls}; + }; + try { + await context.ensureSchema(); + const delegates = GENERATED_RUNTIME_MODULE.checkers; + const wrappers: Record = {}; + for (const [name, delegate] of Object.entries(delegates)) wrappers[name] = {checkAndFix(ctx, mutation, results) { + checkerCalls++; + expect(ctx.requireResource('fixTime').getTime()).toBe(clock.getTime()); + if (name === 'OrderItem') { + if (fix === 'required-null') mutation.payload.product_name = null; + if (fix === 'min-zero') mutation.payload.unit_price = decimal('0'); + if (fix === 'repair') {mutation.payload.product_name = 'Fixed child'; mutation.payload.unit_price = decimal('12.34');} + } + const before = effects(); delegate.checkAndFix(ctx, mutation, results); expect(effects()).toEqual(before); + }}; + client.install(new RuntimeModule({}, wrappers)); + + // Module installation is independent of DDL/bootstrap; use a separate empty store. + const isolatedContext = new UserContext().withBusinessClock(new FixedBusinessClock(clock)) + .withActiveRoot({entity: 'Tenant', id: '1'}); + const isolated = new SQLiteTeaQLClient(filename + '.no-schema.sqlite').setUserContext(isolatedContext); + isolatedContext.insertResource('dataService', isolated); + const isolatedDriver = (isolated as any).driver; + const isolatedQuery = jest.spyOn(isolatedDriver, 'query'), isolatedTransaction = jest.spyOn(isolatedDriver, 'transaction'); + const isolatedSchema = jest.spyOn(isolatedContext, 'ensureSchema'); + let isolatedChecks = 0; + try { + const checkers: Record = {}; + for (const [name, delegate] of Object.entries(delegates)) checkers[name] = {checkAndFix(ctx, mutation, results) { + isolatedChecks++; delegate.checkAndFix(ctx, mutation, results); + }}; + isolated.install(new RuntimeModule({}, checkers)); + await isolatedDriver.query('SELECT 1 AS calibration'); expect(isolatedQuery).toHaveBeenCalledTimes(1); + isolatedQuery.mockClear(); + // This test intentionally has no physical schema. Select a non-storage + // allocator so the test still isolates Checker admission from ID-space I/O. + isolatedContext.withInternalIdGenerator({generateId: () => '1'}); + const missing = (await Q.purchaseOrders().comment('Prepare invalid data without installing schema') + .purpose('Require module Checkers before any database mutation').newEntity(isolatedContext)); + await expect(missing.auditAs('Reject required input in a schema-free store').save(isolatedContext)).rejects.toThrow(CheckException); + expect(isolatedChecks).toBeGreaterThan(0); expect(isolatedQuery).not.toHaveBeenCalled(); + expect(isolatedTransaction).not.toHaveBeenCalled(); expect(isolatedSchema).not.toHaveBeenCalled(); + const db = new Database(filename + '.no-schema.sqlite', {readonly: true, fileMustExist: true}); + try {expect(db.prepare("SELECT name FROM sqlite_master WHERE type='table'").all()).toEqual([]);} finally {db.close();} + record('module-checker-without-schema', {schemaCalled: false, tables: 0, providerCalls: 0, + installedCheckers: Object.keys(delegates).sort(), checkerCalls: isolatedChecks}); + } finally {isolatedQuery.mockRestore(); isolatedTransaction.mockRestore(); isolatedSchema.mockRestore(); await isolated.close();} + + const parent = (await owner()), child = (await item()); parent.orderItemList().push(child); reset(); + await parent.auditAs('Calibrate a valid generated graph through one provider transaction').save(context); + expect(effects()).toMatchObject({transactions: 1, begins: 1, commits: 1, rollbacks: 0, allocations: 0, mutations: 2, audits: 2}); + expect(effects().queries).toBeGreaterThan(0); expect(effects().policies).toBeGreaterThan(0); + expect(effects().reviews).toBeGreaterThan(0); expect(checkerCalls).toBeGreaterThan(0); + record('exact-provider-calibration', {parentID: Number(parent.id), childID: Number(child.id), effects: effects(), checkerCalls}); + + const orphan = (await item()); + const required = await expectRejected(() => orphan.auditAs('Reject an omitted required parent association').save(context), + 'required', 'purchase_order', 'OrderItem'); + record('required-relation', {wire: checkResultToWire(required.result), effects: required.effects, checkerCalls: required.checkerCalls}); + + for (const absent of ['internal_note', 'contact_phone', 'create_time', 'update_time']) { + const selected = Q.purchaseOrdersWithMinimalFields().withIdIs(parent.id!) + .selectTenantWith(Q.tenantsWithMinimalFields().limit(1).comment('Select ownership without unrelated root fields')); + if (absent !== 'internal_note') selected.selectInternalNote(); + if (absent !== 'contact_phone') selected.selectContactPhone(); + if (absent !== 'create_time') selected.selectCreateTime(); + if (absent !== 'update_time') selected.selectUpdateTime(); + const root = (await Q.tenantsWithMinimalFields().withIdIs('1') + .selectPurchaseOrderListWith(selected.limit(1).comment('Omit exactly one business field, not the managed root FK')) + .limit(1).comment('Load a partial non-root object under one untouched ancestor') + .purpose('Distinguish completeness from root ownership failure').executeForList(context))[0]; + const partial = root.purchaseOrderList()[0]; + expect(String(E.purchaseOrder(partial).tenantId().eval())).toBe('1'); + if (absent === 'contact_phone') partial.updateInternalNote('Rejected partial change'); + else partial.updateContactPhone('5550101'); + const rejected = await expectRejected(() => root.auditAs('Reject an incomplete modified descendant').save(context), + 'invalid_type', 'purchase_order_list[0].' + absent, 'PurchaseOrder'); + expect(rejected.result.location.segments).toEqual([{kind: 'property', name: 'purchase_order_list'}, {kind: 'index', index: 0}, {kind: 'property', name: absent}]); + record('nonroot-partial-' + absent, {loadedRoot: 1, absentField: absent, effects: rejected.effects, + wire: checkResultToWire(rejected.result), checkerCalls: rejected.checkerCalls}); + } + + const complete = (await Q.purchaseOrders().withIdIs(parent.id!) + .selectTenantWith(Q.tenantsWithMinimalFields().limit(1).comment('Keep the untouched associated root partial')) + .limit(1).comment('Load a complete owner with a sparse unchanged relation') + .purpose('Only actually modified objects need every modeled field').executeForList(context))[0]; + expect(() => E.purchaseOrder(complete).tenant().name().eval()).toThrow(TeaQLNotLoadedError); + complete.updateContactPhone('5550102'); reset(); + await complete.auditAs('Save the complete owner without requiring unrelated root fields').save(context); + expect(effects()).toMatchObject({transactions: 1, begins: 1, commits: 1, rollbacks: 0, allocations: 0, mutations: 1, audits: 1}); + record('untouched-partial-target', {parentID: Number(parent.id), parentVersion: complete.version, effects: effects()}); + + for (const mode of ['required-null', 'min-zero'] as const) { + const graph = (await owner()), leaf = (await item()); graph.orderItemList().push(leaf); fix = mode; + const rejected = await expectRejected(() => graph.auditAs('Validate the actual customer-Fix result').save(context), + mode === 'required-null' ? 'required' : 'min', 'order_item_list[0].' + (mode === 'required-null' ? 'product_name' : 'unit_price'), 'OrderItem'); + expect(E.orderItem(leaf).productName().eval()).toBe('Boundary item'); + expect(String(E.orderItem(leaf).unitPrice().eval())).toBe(String(decimal('10.00'))); + record('post-fix-' + mode, {effects: rejected.effects, wire: checkResultToWire(rejected.result), + originalInputRetained: true, checkerCalls: rejected.checkerCalls}); fix = 'none'; + } + const repaired = (await owner()), repairedChild = (await item(false)); + const originalChild = (repairedChild as any)._root.change({entity: 'OrderItem', id: (repairedChild as any)._ledgerId}); + expect(originalChild).not.toHaveProperty('product_name'); + expect(String(E.orderItem(repairedChild).unitPrice().eval())).toBe('0'); + repaired.orderItemList().push(repairedChild); fix = 'repair'; reset(); + await repaired.auditAs('Persist only the repaired required and range values').save(context); fix = 'none'; + expect(effects()).toMatchObject({transactions: 1, begins: 1, commits: 1, rollbacks: 0, allocations: 0, mutations: 2, audits: 2}); + const repairedEffects = effects(); + const repairedRows = (await Q.orderItems().withIdIs(repairedChild.id!).limit(1) + .comment('Read the actual repaired business values').purpose('Verify customer Fix reaches persistence').executeForList(context)); + expect(E.orderItem(repairedRows[0]).productName().eval()).toBe('Fixed child'); + expect(String(E.orderItem(repairedRows[0]).unitPrice().eval())).toBe('12.34'); + record('post-fix-repair', {parentID: Number(repaired.id), childID: Number(repairedChild.id), storedName: 'Fixed child', storedPrice: '12.34', + originalMissingRequired: true, originalPrice: '0', effects: repairedEffects}); + + // The runtime's public object-local adapter, then an explicit generated setter + // allow-list and save. This is not a recursive HTTP/TFP adapter test. + const fields = Object.values(GENERATED_RUNTIME_MODULE.schemas.PurchaseOrder.columns) + .map(column => column.modelName ?? column.columnName); + for (const [index, profile] of profiles.entries()) { + const metadata = createWireEntityMetadata('PurchaseOrder', fields, profile, {contact_phone: ['legacy/phone~']}); + const canonical = metadata.fields.contact_phone.wireName; + const inputCases: Array<[string, Record]> = [ + ['accepted-input-alias', {'legacy/phone~': null}], + ['input-unknown', {'unknown/field~': 'no'}], + ['input-equal-forward', {[canonical]: 'same', 'legacy/phone~': 'same'}], + ['input-equal-reverse', {'legacy/phone~': 'same', [canonical]: 'same'}], + ['input-unequal-forward', {[canonical]: 'first', 'legacy/phone~': 'second'}], + ['input-unequal-reverse', {'legacy/phone~': 'first', [canonical]: 'second'}], + ['wire-positive-control', {[canonical]: '55509' + round + index}], + ]; + for (const [name, input] of inputCases) { + const before = physical(); reset(); let mapperCalls = 0, saveCalls = 0, failure: unknown; + let normalized: ReturnType | undefined; + let created: Awaited> | undefined; + try { + const envelope = JSON.parse(JSON.stringify({'payload/order': input})); + normalized = normalizeWireInput(envelope['payload/order'], metadata, '/payload~1order'); + mapperCalls++; created = (await owner()); + // Creation reservation is separate from the following save-admission + // oracle. It must not mutate business rows or emit an audit. + expect(effects().allocations).toBe(1); expect(effects().mutations).toBe(0); expect(effects().audits).toBe(0); + reset(); + Reflect.apply(created.updateContactPhone, created, [normalized.values.contact_phone]); + saveCalls++; await created.auditAs('Save an admitted object-local JSON input through generated APIs').save(context); + } catch (error) {failure = error;} + if (name === 'accepted-input-alias') { + expect(failure).toBeInstanceOf(CheckException); expect(normalized).toBeDefined(); + const results = retainSubmittedPaths([...(failure as CheckException).violations], normalized!); + const result = results.find(value => value.ruleId === 'required' && value.location.modelPath() === 'contact_phone'); + expect(result).toBeDefined(); const wires: Record = {}; + for (const outputProfile of profiles) { + const wire = checkResultToWire(result!, outputProfile); + expect(wire.sourceInstancePath).toBe('/payload~1order/legacy~1phone~0'); + expect(wire.instancePath).toBe('/' + createWireEntityMetadata('PurchaseOrder', ['contact_phone'], outputProfile).fields.contact_phone.wireName); + expect(wire.inputValue).toBeUndefined(); wires[outputProfile] = wire; + } + expect(effects()).toEqual(zero); expect(physical()).toEqual(before); + record(name, {profile, wires, mapperCalls, saveCalls, checkerCalls, effects: effects()}); + } else if (name === 'wire-positive-control') { + expect(failure).toBeUndefined(); expect(effects()).toMatchObject({transactions: 1, mutations: 1, audits: 1}); + record(name, {profile, id: Number(created!.id), mapperCalls, saveCalls, checkerCalls, effects: effects()}); + } else { + expect(failure).toBeInstanceOf(WireInputError); + expect((failure as WireInputError).code).toBe(name === 'input-unknown' ? 'WIRE_UNKNOWN_FIELD' : 'WIRE_FIELD_COLLISION'); + const pointer = name === 'input-unknown' ? '/payload~1order/unknown~1field~0' + : '/payload~1order/' + (name.endsWith('forward') ? 'legacy~1phone~0' : canonical); + expect((failure as WireInputError).instancePath).toBe(pointer); + expect(mapperCalls).toBe(0); expect(saveCalls).toBe(0); expect(checkerCalls).toBe(0); + expect(effects()).toEqual(zero); expect(physical()).toEqual(before); + record(name, {profile, code: (failure as WireInputError).code, pointer, mapperCalls, saveCalls, checkerCalls, effects: effects()}); + } + } + } + expect(observations).toHaveLength(32); + process.stdout.write('CORE_TS_CHECKER_BOUNDARY_RESULT=' + JSON.stringify({language: 'typescript', passed: true, + round, observations: observations.length, physical: physical(), objectLocalWireAdapter: true, recursiveHttpOrTfpAccepted: false}) + '\n'); + } finally { + query.mockRestore(); transaction.mockRestore(); exec.mockRestore(); allocation.mockRestore(); policy.mockRestore(); + await client.close(); + } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/checker-metadata-probe.ts b/source/teaql-ts/examples/fix-e-alignment/checker-metadata-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..e6417dc311615421f82c1f7312e65d73654eea95 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/checker-metadata-probe.ts @@ -0,0 +1,165 @@ +import { CheckException, decimal, FixedBusinessClock, UserContext } from '../../src'; +import { checkResultToWire, CheckResult } from '../../src/core/i18n'; +import { JsonFieldNamingProfile } from '../../src/core/object-location'; +import { Q } from 'generated/generated/Q'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import { TeaQLClient } from 'generated/teaql-ts'; +import { GENERATED_RUNTIME_MODULE } from 'generated/runtime-module'; +import Database from 'better-sqlite3'; +import { readFileSync } from 'node:fs'; + +/** Human text uses readable labels; wire locations retain the technical identity. */ +function expectReadableDefaultMessage(violation: CheckResult): void { + if (violation.ruleId === 'invalid_type') return; // Explicit full-load policy text. + const leaf = [...violation.location.segments].reverse().find(segment => segment.kind === 'property'); + if (leaf?.kind === 'property') { + expect(violation.message).toContain(leaf.name.replace(/_/g, ' ')); + if (leaf.name.includes('_')) expect(violation.message).not.toContain(violation.location.nativePath()); + } +} + +/** Actual generated audited saves, not manually constructed validation errors. */ +export async function verifyCheckerMetadata(filename: string): Promise { + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const observations: Array<{scenario: string; violations: CheckResult[]; entityType: string}> = []; + const profiles: JsonFieldNamingProfile[] = ['camelCase', 'snake_case', 'PascalCase']; + try { + await context.ensureSchema(); + const driver = (client as any).driver; + const query = jest.spyOn(driver, 'query'); + const transaction = jest.spyOn(driver, 'transaction'); + const owner = async () => (await Q.purchaseOrders().comment('Prepare a Checker metadata regression') + .purpose('Require declaring entity types on actual generated-save errors').newEntity(context)); + const good = (await owner()).updateContactPhone('5550800'); + expect(transaction.mock.calls.length).toBe(1); // Creation reserves, but does not save. + query.mockClear(); transaction.mockClear(); + await good.auditAs('Calibrate successful Checker admission and SQLite instrumentation').save(context); + expect(query.mock.calls.length).toBeGreaterThan(0); + expect(transaction.mock.calls.length).toBe(1); + const table = (client as any).schemas.PurchaseOrder.table; + const oracle = () => { + const db = new Database(filename, {readonly: true, fileMustExist: true}); + try { return {count: db.prepare(`SELECT COUNT(*) AS n FROM "${table}"`).get(), + row: db.prepare(`SELECT contact_phone, version FROM "${table}" WHERE id = ?`).get(good.id)}; } + finally { db.close(); } + }; + const before = oracle(); + const invalid = async (scenario: string, save: () => Promise, entityType = 'PurchaseOrder', + expectedPath?: string, expectedRule?: string) => { + query.mockClear(); transaction.mockClear(); const audits = client.auditTrace.length; + let failure: CheckException | undefined; + try { await save(); } + catch (error) { if (!(error instanceof CheckException)) throw error; failure = error; } + expect(failure).toBeInstanceOf(CheckException); + const violations = [...failure!.violations]; + expect(violations.length).toBeGreaterThan(0); + const effects = {queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + audits: client.auditTrace.length - audits}; + process.stdout.write('CORE_CHECKER_METADATA_CASE=' + JSON.stringify({scenario, effects, + wire: profiles.map(profile => ({profile, results: violations.map(result => checkResultToWire(result, profile))}))}) + '\n'); + expect(effects).toEqual({queries: 0, transactions: 0, audits: 0}); + expect(oracle()).toEqual(before); + expect(context.getResource('fixTime')).toBeUndefined(); + if (expectedPath) expect(violations.some(result => result.location.modelPath() === expectedPath)).toBe(true); + if (expectedRule) expect(violations.some(result => result.ruleId === expectedRule)).toBe(true); + observations.push({scenario, violations, entityType}); + }; + const omitted = await owner(); + await invalid('create-required', () => omitted.auditAs('Reject an omitted required contact phone').save(context)); + const tooLong = (await owner()).updateContactPhone('x'.repeat(33)); + await invalid('create-max-length', () => tooLong + .auditAs('Reject a contact phone exceeding the modeled length').save(context)); + const complete = (await Q.purchaseOrders().withIdIs(good.id!).limit(1) + .comment('Load the complete owner before the invalid update').purpose('Verify explicit null is not omission') + .executeForList(context))[0]; + // TypeScript correctly rejects null statically. Simulate an untyped JS + // caller as well, without weakening the generated method's signature. + Reflect.apply(complete.updateContactPhone, complete, [null]); + await invalid('update-required-null', () => complete.auditAs('Reject null for a required contact phone').save(context)); + const partial = (await Q.purchaseOrdersWithMinimalFields().withIdIs(good.id!).limit(1) + .comment('Load an identity-only owner for admission testing').purpose('Require complete modified objects') + .executeForList(context))[0]; + partial.updateContactPhone('5550801'); + await invalid('modified-partial-owner', () => partial.auditAs('Reject changing a partially loaded owner').save(context)); + const badChild = async (scenario: string, name: string | undefined, price: string, rule: string, field: string) => { + const parent = (await owner()).updateContactPhone('5550802'); + const child = (await Q.orderItems().comment('Prepare an invalid child for indexed Checker diagnostics') + .purpose('Keep the declaring child type when prefixing an error').newEntity(context)); + if (name !== undefined) child.updateProductName(name); + child.updateUnitPrice(decimal(price)); + parent.orderItemList().push(child); + await invalid(scenario, () => parent.auditAs('Reject the complete graph before its first SQLite write').save(context), + 'OrderItem', 'order_item_list[0].' + field, rule); + }; + await badChild('nested-required', undefined, '10.00', 'required', 'product_name'); + await badChild('nested-max-length', 'x'.repeat(81), '10.00', 'max_length', 'product_name'); + context.setLocaleCode('zh-CN'); + await badChild('nested-min', 'Synthetic Widget', '0', 'min', 'unit_price'); + await badChild('nested-max', 'Synthetic Widget', '1000001', 'max', 'unit_price'); + expect(observations).toHaveLength(8); + for (const observation of observations) { + for (const violation of observation.violations) { + expect(violation.entityType).toBe(observation.entityType); + expect(violation.message).toBeTruthy(); + expectReadableDefaultMessage(violation); + for (const profile of profiles) { + const wire = checkResultToWire(violation, profile); + expect(wire.entityType).toBe(observation.entityType); + expect(wire.location).toEqual(violation.location.segments); + expect(wire.instancePath).toBe(violation.location.instancePath(profile)); + } + } + } + process.stdout.write('CORE_CHECKER_METADATA=' + JSON.stringify({language: 'typescript', passed: true, + scenarios: observations.length, wireProjections: observations.reduce((n, v) => n + v.violations.length * 3, 0), + positiveProviderCalibration: true, rejectedQueries: 0, rejectedTransactions: 0, rejectedAudits: 0}) + '\n'); + query.mockRestore(); transaction.mockRestore(); + } finally { await client.close(); } +} + +/** The generated file-backed client has its own save boundary; exercise it too. */ +export async function verifyFileCheckerMetadata(filename: string): Promise { + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))) + .withActiveRoot({entity: 'Tenant', id: '1'}); + const client = new TeaQLClient(filename).install(GENERATED_RUNTIME_MODULE).setUserContext(context); + context.insertResource('dataService', client); + const owner = async () => (await Q.purchaseOrders().comment('Prepare file-backed Checker admission') + .purpose('Verify the generated client preserves declaring entity types').newEntity(context)); + const persist = jest.spyOn(client as any, 'persist'); + try { + const good = (await owner()).updateContactPhone('5550803'); + await good.auditAs('Calibrate a successful file-backed save').save(context); + expect(persist.mock.calls.length).toBeGreaterThan(0); + const audits = client.auditTrace.length; + const invalid = async (scenario: string, save: () => Promise, entityType: string) => { + const before = readFileSync(filename); // ID reservations have already completed. + persist.mockClear(); + let failure: CheckException | undefined; + try { await save(); } + catch (error) { if (!(error instanceof CheckException)) throw error; failure = error; } + expect(failure).toBeInstanceOf(CheckException); + expect(persist.mock.calls).toHaveLength(0); + expect(client.auditTrace).toHaveLength(audits); + expect(readFileSync(filename)).toEqual(before); + expect(context.getResource('fixTime')).toBeUndefined(); + for (const violation of failure!.violations) expect(violation.entityType).toBe(entityType); + process.stdout.write('CORE_FILE_CHECKER_METADATA_CASE=' + JSON.stringify({scenario, entityType, + results: failure!.violations.map(result => checkResultToWire(result)), persistCalls: 0, auditEvents: 0}) + '\n'); + for (const violation of failure!.violations) expectReadableDefaultMessage(violation); + }; + const omitted = await owner(); + await invalid('create-required', () => omitted.auditAs('Reject a file-backed required-field omission').save(context), 'PurchaseOrder'); + const tooLong = (await owner()).updateContactPhone('x'.repeat(33)); + await invalid('create-max-length', () => tooLong + .auditAs('Reject a file-backed modeled length violation').save(context), 'PurchaseOrder'); + const parent = (await owner()).updateContactPhone('5550804'); + const child = (await Q.orderItems().comment('Prepare a file-backed invalid child') + .purpose('Verify prefixed errors retain the child type').newEntity(context)).updateUnitPrice(decimal('10')); + parent.orderItemList().push(child); + await invalid('nested-required', () => parent.auditAs('Reject an invalid file-backed child graph').save(context), 'OrderItem'); + process.stdout.write('CORE_FILE_CHECKER_METADATA=' + JSON.stringify({language: 'typescript', passed: true, + scenarios: 3, positivePersistenceCalibration: true, rejectedPersistCalls: 0, rejectedAuditEvents: 0}) + '\n'); + } finally { persist.mockRestore(); } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/concurrent-query-probe.ts b/source/teaql-ts/examples/fix-e-alignment/concurrent-query-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..afc16a914022f95cc02a3aa10f7863e23ce3f5ec --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/concurrent-query-probe.ts @@ -0,0 +1,154 @@ +import {internalId} from 'teaql-ts'; +import { decimal, FixedBusinessClock, UserContext } from '../../src'; +import { QueryRequest } from '../../src/core/request-intent'; +import { queryExecutionOwner } from '../../src/core/query-snapshot'; +import type { SQLExecutionMetadata } from '../../src/sql/core'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; + +function signal() { + let resolve!: () => void; + const promise = new Promise(done => {resolve = done;}); + return {promise, resolve}; +} + +/** Read-only test seam for Context storage; never installs request provenance. */ +function contextSnapshot(context: UserContext) { + const keys = Reflect.ownKeys(context); + const fields = keys.map(key => [key, (context as any)[key]] as const); + const maps = fields.filter(([, value]) => value instanceof Map) + .map(([key, value]) => [key, [...value.entries()]] as const); + return {fieldCount: fields.length, matches: () => { + const now = Reflect.ownKeys(context); + return now.length === keys.length && keys.every(key => now.includes(key)) + && fields.every(([key, value]) => Object.is((context as any)[key], value)) + && maps.every(([key, entries]) => { + const map = (context as any)[key] as Map; + return map.size === entries.length && entries.every(([k, v]) => map.has(k) && Object.is(map.get(k), v)); + }); + }}; +} + +export async function verifyConcurrentQuery(filename: string): Promise { + const round = Number(process.env.TEAQL_FIX_E_ROUND); + if (![1, 2].includes(round)) throw new Error('An explicit retained-example round is required'); + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const events: SQLExecutionMetadata[] = []; + client.setDiagnosticSQLLogSink({write: value => {events.push(value);}}); + const driver = (client as any).driver; + const query = jest.spyOn(driver, 'query'); + const entered = signal(), release = signal(); + const tasks: Promise[] = []; + let execute: ReturnType | undefined; + let timer: ReturnType | undefined; + try { + await context.ensureSchema(); + const prior = await Q.purchaseOrders().limit(5).comment('Determine the concurrent-query example round') + .purpose('Retain both rounds without resetting SQLite').executeForList(context); + expect(prior).toHaveLength((round - 1) * 2); + const ids: Record = {}, childIds: Record = {}; + const auditBeforeSeed = client.auditTrace.length; + query.mockClear(); + for (const label of ['alpha', 'beta']) { + const parent = (await Q.purchaseOrders().comment('Prepare the ' + label + ' query fixture') + .purpose('Use generated audited graph mutation before concurrent reads').newEntity(context)) + .updateContactPhone(label === 'alpha' ? '5550701' : '5550702').updateInternalNote(null); + const child = (await Q.orderItems().comment('Prepare the ' + label + ' query leaf') + .purpose('Read child identity through generated Q and E').newEntity(context)) + .updateProductName(label + ' child').updateUnitPrice(decimal('1.00')); + parent.orderItemList().push(child); + await parent.auditAs('Create the ' + label + ' concurrent-query graph').save(context); + if (!parent.id) throw new Error('Missing persisted parent identity'); + ids[label] = String(parent.id); + const seeded = (await Q.purchaseOrders().withIdIs(internalId(parent.id)) + .selectOrderItemListWith(Q.orderItems().limit(10).comment('Read the saved ' + label + ' child')) + .limit(1).comment('Read back the ' + label + ' graph').purpose('Never infer a child ID from allocation order') + .executeForList(context))[0]; + const childId = E.purchaseOrder(seeded).orderItemList().first().id().eval(); + if (!childId) throw new Error('Missing persisted child identity'); + childIds[label] = String(childId); + } + expect(client.auditTrace.length - auditBeforeSeed).toBe(4); + expect(query.mock.calls.filter(call => /^\s*INSERT INTO\s+"?(?:purchase_order|order_item)_data\b/i.test(String(call[0])))).toHaveLength(4); + const suppliedContexts: UserContext[] = []; + const load = async (label: string, owner: string, supplied: UserContext) => { + suppliedContexts.push(supplied); + return (await Q.purchaseOrders().withIdIs(ids[owner]) + .selectOrderItemListWith(Q.orderItems().limit(10).comment(label + ' children')) + .limit(1).comment(label + ' root').purpose(label + ' purpose').executeForList(supplied))[0]; + }; + await load('calibration', 'alpha', context); + suppliedContexts.length = 0; events.length = 0; query.mockClear(); + const auditStart = client.auditTrace.length, baseline = contextSnapshot(context); + const actual = (client as any).executeQueryWithIntent.bind(client); + const live: QueryRequest[] = []; + let providerCalls = 0, rootCalls = 0; + execute = jest.spyOn(client as any, 'executeQueryWithIntent').mockImplementation(async (...args: any[]) => { + providerCalls++; + // Observe the actual runtime-created execution owner, not a test wrapper. + const owner = queryExecutionOwner(args[0]); + if (!(owner instanceof QueryRequest)) throw new Error('Runtime query snapshot has no formal request owner'); + if (!owner.parentRequest) rootCalls++; + if (!owner.parentRequest && ['alpha root', 'beta root'].includes(owner.comment)) { + live.push(owner); if (live.length === 2) entered.resolve(); + await release.promise; + } + return actual(...args); + }); + let alphaDone = false, betaDone = false; + const alpha = load('alpha', 'alpha', context).finally(() => {alphaDone = true;}); + const beta = load('beta', 'beta', context).finally(() => {betaDone = true;}); + tasks.push(alpha, beta); + // Keep failures observed while the bounded overlap checkpoint is waiting. + void alpha.catch(() => undefined); void beta.catch(() => undefined); + await Promise.race([entered.promise, new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error('Concurrent generated requests did not reach the overlap checkpoint')), 5000); + })]); + clearTimeout(timer); timer = undefined; + const bothLive = !alphaDone && !betaDone; + const distinctRoots = live.length === 2 && live[0].rootRequest !== live[1].rootRequest; + const contextUnchangedWhileLive = baseline.matches(); + const crossInvocationErrors = [[live[0], live[1]], [live[1], live[0]]].map(([a, b]) => { + try {a.withQuery(b.query); return null;} catch (error) {return error instanceof Error ? error.message : String(error);} + }); + const checkpoints = live.map(request => ({comment: request.comment, purpose: request.purpose, + parentAbsent: request.parentRequest === undefined, rootIsSelf: request.rootRequest === request, + frozen: Object.isFrozen(request), nodes: request.traceChain})); + release.resolve(); + const [a, b] = await Promise.all([alpha, beta]); + const after = await load('after', 'alpha', context); + const beforeE = {provider: providerCalls, queries: query.mock.calls.length, logs: events.length}; + const values: Record = {}; + for (const [label, row] of [['alpha', a], ['beta', b], ['after', after]] as const) { + const owner = label === 'after' ? 'alpha' : label; + const value = {id: String(row.id), phone: E.purchaseOrder(row).contactPhone().eval(), + count: E.purchaseOrder(row).orderItemList().size().eval(), product: E.purchaseOrder(row).orderItemList().first().productName().eval()}; + expect(value).toEqual({id: ids[owner], phone: owner === 'alpha' ? '5550701' : '5550702', count: 1, product: owner + ' child'}); + values[label] = value; + } + const observation = {language: 'typescript', round, sameContext: suppliedContexts.length === 3 && suppliedContexts.every(c => c === context), + distinctRoots, bothLive, overlapEntered: live.length, checkpoints, crossInvocationErrors, + contextUnchangedWhileLive, contextUnchangedAfter: baseline.matches(), contextFieldCount: baseline.fieldCount, + providerCalls, rootCalls, physicalQueries: query.mock.calls.filter(call => /^\s*SELECT\b/i.test(String(call[0]))).length, + physicalWrites: query.mock.calls.filter(call => /^\s*(?:INSERT|UPDATE|DELETE)\b/i.test(String(call[0]))).length, + eProviderReads: providerCalls - beforeE.provider, eSqlReads: query.mock.calls.length - beforeE.queries, eLogEntries: events.length - beforeE.logs, + auditEvents: client.auditTrace.length - auditStart, ids, childIds, values, synchronousSqliteDriver: true, + events: events.map(m => ({operation: m.operation, outcome: m.executionOutcome, resultCount: m.resultCount, + comment: m.comment, purpose: m.purpose, sql: m.parameterizedSQL, parameters: m.parameters, + business: m.traceChain, physical: m.tracePath.map(({kind, name, detail}) => ({kind, name, detail}))})), + generatedImplementationsModified: false}; + process.stdout.write('TYPESCRIPT_CONCURRENT_QUERY_OBSERVATION=' + JSON.stringify(observation) + '\n'); + expect(observation).toMatchObject({sameContext: true, distinctRoots: true, bothLive: true, overlapEntered: 2, + contextUnchangedWhileLive: true, contextUnchangedAfter: true, physicalQueries: 6, physicalWrites: 0, + rootCalls: 3, providerCalls: 6, eProviderReads: 0, eSqlReads: 0, eLogEntries: 0, auditEvents: 0}); + expect(crossInvocationErrors.every(message => message?.startsWith('QUERY_SCOPE_OWNER_MISMATCH:'))).toBe(true); + expect(events).toHaveLength(6); + process.stdout.write('TYPESCRIPT_CONCURRENT_QUERY=' + JSON.stringify({passed: true, observation}) + '\n'); + } finally { + if (timer) clearTimeout(timer); release.resolve(); + await Promise.allSettled(tasks); execute?.mockRestore(); query.mockRestore(); await client.close(); + } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/context-root-probe.ts b/source/teaql-ts/examples/fix-e-alignment/context-root-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..110fb6651c193f3d4a7701443f9699ea41d6bee5 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/context-root-probe.ts @@ -0,0 +1,186 @@ +import { CheckException, decimal, FixedBusinessClock, UserContext } from '../../src'; +import { EntityChecker } from '../../src/core/checker'; +import { ContextEntityRef, ContextRootError } from '../../src/core/context'; +import { checkResultToWire } from '../../src/core/i18n'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import { TeaQLClient } from 'generated/teaql-ts'; +import { GENERATED_RUNTIME_MODULE } from 'generated/runtime-module'; +import Database from 'better-sqlite3'; +import { readFileSync } from 'node:fs'; + +/** Application-owned boundary probe; generated sources stay byte-for-byte frozen. */ +export async function verifyContextRoot(filename: string): Promise { + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + // Installing the generated metadata must not select a request's active root. + expect(context.getResource('activeRoot')).toBeUndefined(); + const driver = (client as any).driver; + try { + await context.ensureSchema(); + const active = context.requireActiveRoot('Tenant'); + expect(BigInt(active.id)).toBeGreaterThan(0n); + const schemas = (client as any).schemas; + const rootMember = Object.entries(schemas.PurchaseOrder.columns).find(([, column]) => (column as any).modelName === 'tenant')![0]; + expect(rootMember).toBeTruthy(); + const rootTable = schemas.Tenant.table as string; + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'); + const allocation = jest.spyOn(driver, 'nextId'); + const policy = jest.spyOn(context, 'enterMutationPolicy'), review = jest.fn(() => undefined); + context.withMutationPolicyRegistry({resolve: review}); + const rootLookups = () => query.mock.calls.filter(call => String(call[0]).replace(/"/g, '') + .includes('FROM ' + rootTable)).length; + let auditStart = client.auditTrace.length; + const effects = () => ({queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + allocations: allocation.mock.calls.length, policies: policy.mock.calls.length, reviews: review.mock.calls.length, + audits: client.auditTrace.length - auditStart, rootLookups: rootLookups()}); + const reset = () => { query.mockClear(); transaction.mockClear(); allocation.mockClear(); + policy.mockClear(); review.mockClear(); auditStart = client.auditTrace.length; }; + const fixObservations: Array> = []; + const checkers = (client as any).checkers as Record; + for (const entity of ['PurchaseOrder', 'OrderItem']) { + const delegate = checkers[entity]; expect(delegate).toBeDefined(); + checkers[entity] = {checkAndFix(ctx, mutation, results) { + const before = effects(); + try {delegate.checkAndFix(ctx, mutation, results);} finally { + expect(effects()).toEqual(before); + const value = mutation.payload.tenant, loaded = mutation.loadedValues?.tenant; + const descriptor = Object.getOwnPropertyDescriptor(mutation, 'loadedValues'); + fixObservations.push({entity, operation: mutation.action, rootPresent: value !== undefined && value !== null, + root: value === undefined || value === null ? null : String(value?.id ?? value), + loadedRoot: loaded == null ? null : String(loaded?.id ?? loaded), + readOnlyLoadedValues: Boolean(descriptor && !descriptor.enumerable && !descriptor.writable && Object.isFrozen(mutation.loadedValues)), + instant: ctx.getResource('fixTime')!.getTime(), ioDuringFix: 0}); + } + }}; + } + await Q.tenants().withIdIs(active.id as string).limit(1).comment('Calibrate the context-root lookup observer') + .purpose('Prove the real SQL observer detects a root SELECT').executeForList(context); + const queryCalibration = effects(); expect(queryCalibration.queries).toBeGreaterThan(0); expect(queryCalibration.rootLookups).toBeGreaterThan(0); + const owner = async () => (await Q.purchaseOrders().comment('Prepare a context-root admission boundary') + .purpose('Derive ownership from trusted runtime context').newEntity(context)).updateContactPhone('5550980'); + const parent = (await owner()), child = (await Q.orderItems().comment('Prepare a context-bound graph child') + .purpose('Verify root Fix at every modified graph node').newEntity(context)) + .updateProductName('Context root child').updateUnitPrice(decimal('10.00')); + parent.orderItemList().push(child); + expect('updateTenantId' in parent).toBe(false); expect('updateTenantId' in child).toBe(false); + reset(); await parent.auditAs('Persist the valid context-bound parent and child').save(context); + const calibration = effects(); + expect(calibration.transactions).toBe(1); expect(calibration.allocations).toBe(0); expect(calibration.audits).toBe(2); + expect(calibration.policies).toBeGreaterThan(0); expect(calibration.reviews).toBeGreaterThan(0); expect(calibration.rootLookups).toBe(0); + expect(String(E.purchaseOrder(parent).tenantId().eval())).toBe(String(active.id)); + expect(String(E.orderItem(child).tenantId().eval())).toBe(String(active.id)); + const physical = () => { + const db = new Database(filename, {readonly: true, fileMustExist: true}); + try {return {owners: db.prepare(`SELECT id,version,tenant FROM "${schemas.PurchaseOrder.table}" ORDER BY id`).all(), + children: db.prepare(`SELECT id,version,tenant,purchase_order FROM "${schemas.OrderItem.table}" ORDER BY id`).all()};} + finally {db.close();} + }; + const cases: Array> = []; + const root = (value?: ContextEntityRef) => value ? context.insertResource('activeRoot', value) : context.removeResource('activeRoot'); + const reject = async (name: string, row: Awaited>, expectedRule: string) => { + const before = physical(); reset(); let failure: unknown; + try {await row.auditAs('Reject the synthetic ' + name + ' root violation').save(context);} catch (error) {failure = error;} + const counts = effects(), violations = failure instanceof CheckException ? failure.violations : []; + const matching = violations.find(v => v.ruleId === expectedRule && v.location.modelPath() === 'tenant'); + const contextFailure = expectedRule === 'context_root' && failure instanceof ContextRootError + && failure.expectedType === 'Tenant' ? failure : undefined; + const unchanged = JSON.stringify(physical()) === JSON.stringify(before); + const passed = Boolean(matching || contextFailure) && Object.values(counts).every(v => v === 0) && unchanged; + const value = {case: name, passed, expectedRule, matchedRule: Boolean(matching || contextFailure), + errorType: failure instanceof Error ? failure.name : null, effects: counts, physicalStateUnchanged: unchanged, + ...(contextFailure ? {contextError: {reason: contextFailure.reason, expectedType: contextFailure.expectedType}} : {}), + ...(matching ? {wire: checkResultToWire(matching)} : {})}; + cases.push(value); process.stdout.write('CORE_TS_ROOT_CASE=' + JSON.stringify(value) + '\n'); + }; + root(); await reject('missing-root', (await owner()), 'context_root'); + root({entity: 'UnrelatedRoot', id: active.id}); await reject('type-mismatch', (await owner()), 'context_root'); + for (const [name, id] of [['zero-number', 0], ['zero-string', '0'], ['zero-bigint', 0n], ['negative-number', -1]] as const) { + root({entity: 'Tenant', id}); await reject(name, (await owner()), 'context_root'); + } + root(active); + const conflict = (await owner()); + Reflect.set(conflict, rootMember, String(BigInt(active.id) + 1n)); + (conflict as any)._root.set({entity: 'PurchaseOrder', id: (conflict as any)._ledgerId}, 'tenant', String(BigInt(active.id) + 1n)); + await reject('explicit-root-mismatch', conflict, 'context_root_mismatch'); + const load = async () => (await Q.purchaseOrders().withIdIs(parent.id!).limit(1) + .comment('Load the complete root-ownership baseline').purpose('Reject moving an existing owner').executeForList(context))[0]; + const loaded = await load(); expect(loaded).toBeDefined(); + (loaded as any)._root.set({entity: 'PurchaseOrder', id: (loaded as any)._ledgerId}, 'tenant', String(BigInt(active.id) + 1n)); + await reject('update-root-mismatch', loaded, 'context_root_mismatch'); + const other = (await load()).updateContactPhone('5550981'); + root({entity: 'Tenant', id: String(BigInt(active.id) + 1n)}); + await reject('update-wrong-context', other, 'context_root_mismatch'); + root(active); + const transfer = (await load()).updateContactPhone('5550982'); + Reflect.set(transfer, rootMember, String(BigInt(active.id) + 1n)); + (transfer as any)._root.set({entity: 'PurchaseOrder', id: (transfer as any)._ledgerId}, 'tenant', String(BigInt(active.id) + 1n)); + root({entity: 'Tenant', id: String(BigInt(active.id) + 1n)}); + await reject('update-context-and-root', transfer, 'context_root_mismatch'); + root(active); + const missingUpdate = (await load()).updateContactPhone('5550983'); + root(); await reject('update-missing-root', missingUpdate, 'context_root'); + root(active); + const deleted = (await load()).markForDeletion(); + root({entity: 'Tenant', id: String(BigInt(active.id) + 2n)}); + await reject('delete-wrong-context', deleted, 'context_root_mismatch'); + root(active); + const result = {language: 'typescript', passed: cases.every(v => v.passed), failures: cases.filter(v => !v.passed).map(v => v.case), + cases, parentId: parent.id, childId: child.id, activeRoot: String(active.id), calibration, queryCalibration, fixObservations, + noPublicRootUpdater: true, moduleInstallationChoosesRoot: false, queryAuthorizationInferred: false, newEntityBeforeReturnAccepted: false}; + process.stdout.write('CORE_TS_ROOT_RESULT=' + JSON.stringify(result) + '\n'); expect(result.passed).toBe(true); + query.mockRestore(); transaction.mockRestore(); allocation.mockRestore(); policy.mockRestore(); + } finally {await client.close();} +} + +/** The generated file-backed client must consume the same protected baseline. */ +export async function verifyFileContextRoot(filename: string): Promise { + const context = new UserContext().withActiveRoot({entity: 'Tenant', id: '1'}) + .withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new TeaQLClient(filename).install(GENERATED_RUNTIME_MODULE).setUserContext(context); + context.insertResource('dataService', client); + const owner = async () => (await Q.purchaseOrders().comment('Prepare file-backed root ownership admission') + .purpose('Verify both generated client implementations enforce the same context boundary') + .newEntity(context)).updateContactPhone('5550984'); + const row = (await owner()); await row.auditAs('Create the file-backed root baseline').save(context); + const persist = jest.spyOn(client as any, 'persist'); + const calibration = {persistCalls: persist.mock.calls.length}; + // The spy starts after the baseline. A second valid save calibrates it. + row.updateContactPhone('5550985'); await row.auditAs('Calibrate file-backed persistence').save(context); + calibration.persistCalls = persist.mock.calls.length; expect(calibration.persistCalls).toBeGreaterThan(0); + const cases: Array> = []; + const reject = async (name: string, target: Awaited>, expected: string) => { + const before = readFileSync(filename), audit = client.auditTrace.length; persist.mockClear(); let failure: unknown; + try {await target.auditAs('Reject file-backed ' + name).save(context);} catch (error) {failure = error;} + const typed = failure instanceof ContextRootError && failure.expectedType === 'Tenant' && expected === 'context_root'; + const violation = failure instanceof CheckException ? failure.violations.find(v => v.ruleId === expected && v.location.modelPath() === 'tenant') : undefined; + const effects = {persistCalls: persist.mock.calls.length, audits: client.auditTrace.length - audit}; + const unchanged = readFileSync(filename).equals(before), passed = Boolean(typed || violation) && !effects.persistCalls && !effects.audits && unchanged; + const result = {case: name, passed, expectedRule: expected, matchedRule: Boolean(typed || violation), effects, + physicalStateUnchanged: unchanged, errorType: failure instanceof Error ? failure.name : null}; + cases.push(result); process.stdout.write('CORE_TS_ROOT_FILE_CASE=' + JSON.stringify(result) + '\n'); + }; + try { + context.withActiveRoot({entity: 'Tenant', id: 0}); await reject('zero-root', (await owner()), 'context_root'); + const load = async () => (await Q.purchaseOrders().withIdIs(row.id!).limit(1) + .comment('Load the complete file-backed baseline').purpose('Use actual hydration provenance for ownership').executeForList(context))[0]; + context.withActiveRoot({entity: 'Tenant', id: '2'}); + await reject('update-wrong-context', (await load()).updateContactPhone('5550986'), 'context_root_mismatch'); + const transferred = (await load()).updateContactPhone('5550987'); + const schemas = (client as any).schemas; + const member = Object.entries(schemas.PurchaseOrder.columns).find(([, column]) => (column as any).modelName === 'tenant')![0]; + Reflect.set(transferred, member, '2'); + (transferred as any)._root.set({entity: 'PurchaseOrder', id: (transferred as any)._ledgerId}, 'tenant', '2'); + await reject('update-context-and-root', transferred, 'context_root_mismatch'); + const missing = (await load()).updateContactPhone('5550988'); context.removeResource('activeRoot'); + await reject('update-missing-root', missing, 'context_root'); + context.withActiveRoot({entity: 'Tenant', id: '3'}); + await reject('delete-wrong-context', (await load()).markForDeletion(), 'context_root_mismatch'); + const result = {language: 'typescript', passed: cases.every(v => v.passed), cases, + failures: cases.filter(v => !v.passed).map(v => v.case), calibration, + queryAuthorizationInferred: false, newEntityBeforeReturnAccepted: false}; + process.stdout.write('CORE_TS_ROOT_FILE_RESULT=' + JSON.stringify(result) + '\n'); expect(result.passed).toBe(true); + } finally {persist.mockRestore();} +} diff --git a/source/teaql-ts/examples/fix-e-alignment/creation-identity.test.ts b/source/teaql-ts/examples/fix-e-alignment/creation-identity.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..4624dd00c87d6d15bb18c88e16e1e1bca0cbd358 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/creation-identity.test.ts @@ -0,0 +1,117 @@ +import { UserContext, FixedBusinessClock, LoadedScalarSnapshot } from 'teaql-ts'; +import { Q } from 'generated/generated/Q'; +import { E } from 'generated/generated/E'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; +import { TeaQLClient } from 'generated/teaql-ts'; +import { GENERATED_RUNTIME_MODULE } from 'generated/runtime-module'; +import { join } from 'node:path'; + +function database(name: string) { + const directory = process.env.TEAQL_CREATION_DATABASES; + if (!directory) throw new Error('Explicit retained creation database directory required'); + return join(directory, name); +} +async function fixture(name: string) { + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new SQLiteTeaQLClient(database(name + '.sqlite')).setUserContext(context); + context.insertResource('dataService', client); await context.ensureSchema(); + const allocation = jest.spyOn((client as any).driver, 'nextId'); + const mutation = jest.spyOn(client, 'executeMutation'); + return {context, client, allocation, mutation, close: async () => { allocation.mockRestore(); mutation.mockRestore(); await client.close(); }}; +} +const create = (context: UserContext) => Q.purchaseOrders().comment('Reserve an order identity') + .purpose('Verify creation before any business persistence').newEntity(context); + +test('default SQLite factory reserves a real identity, keeps its ledger key, then saves without reallocating', async () => { + const f = await fixture('default'); + try { + const audit = f.client.auditTrace.length, owner = await create(f.context), id = owner.id!; + expect(id).toMatch(/^[1-9][0-9]*$/); expect(owner.version).toBeUndefined(); + expect(E.purchaseOrder(owner).id().eval()).toBe(id); + expect((owner as any)._ledgerId).toBe(id); expect((owner as any)._root.isNew({entity: 'PurchaseOrder', id})).toBe(true); + expect(f.allocation).toHaveBeenCalledTimes(1); expect(f.mutation).not.toHaveBeenCalled(); + expect(f.client.auditTrace.length).toBe(audit); + owner.updateContactPhone('5550199'); await owner.auditAs('Save an already allocated order').save(f.context); + expect(owner.id).toBe(id); expect(owner.version).toBe(1); expect(f.allocation).toHaveBeenCalledTimes(1); + const loaded = (await Q.purchaseOrders().withIdIs(id).limit(1).comment('Read reserved identity') + .purpose('Verify persistence keeps the original ID').executeForList(f.context))[0]; + expect(E.purchaseOrder(loaded).id().eval()).toBe(id); + expect(E.purchaseOrder(loaded).contactPhone().eval()).toBe('5550199'); + } finally { await f.close(); } +}); + +test.each(['error', 'zero'] as const)('default allocation %s returns no entity or ledger; a later call recovers', async mode => { + const f = await fixture(mode), sentinel = new Error('creation allocator unavailable'); + const construct = jest.spyOn(LoadedScalarSnapshot, 'captureFor'); + try { + if (mode === 'error') f.allocation.mockRejectedValueOnce(sentinel); + else f.allocation.mockResolvedValueOnce('0'); + if (mode === 'error') await expect(create(f.context)).rejects.toBe(sentinel); + else await expect(create(f.context)).rejects.toThrow('positive'); + expect(construct).not.toHaveBeenCalled(); expect(f.mutation).not.toHaveBeenCalled(); + const recovered = await create(f.context); expect(recovered.id).toMatch(/^[1-9][0-9]*$/); + expect(construct).toHaveBeenCalledTimes(1); expect(f.allocation).toHaveBeenCalledTimes(2); + } finally { construct.mockRestore(); await f.close(); } +}); + +test('selected provider is awaited; failures do not fall back and successful independent graphs do not leak', async () => { + const f = await fixture('custom'), sentinel = new Error('selected provider unavailable'); + const generateId = jest.fn().mockRejectedValueOnce(sentinel).mockResolvedValueOnce('0') + .mockResolvedValueOnce('41').mockResolvedValueOnce('42'); + f.context.withInternalIdGenerator({generateId}); + try { + await expect(create(f.context)).rejects.toBe(sentinel); await expect(create(f.context)).rejects.toThrow('positive'); + const first = await create(f.context), other = await create(f.context); + expect(generateId).toHaveBeenLastCalledWith('PurchaseOrder', f.context); + expect(first.id).toBe('41'); expect(other.id).toBe('42'); expect((first as any)._root).not.toBe((other as any)._root); + first.updateContactPhone('saved'); other.updateContactPhone('unsaved'); + await first.auditAs('Save only the selected independent graph').save(f.context); + const rows = await Q.purchaseOrders().limit(100).comment('Inspect independent creation graphs') + .purpose('Verify an unrelated pending entity was not saved').executeForList(f.context); + expect(rows.map(row => row.id)).toEqual(['41']); expect(other.version).toBeUndefined(); + expect((other as any)._root.hasPending({entity: 'PurchaseOrder', id: '42'})).toBe(true); + expect(f.allocation).not.toHaveBeenCalled(); + } finally { await f.close(); } +}); + +test('a pending provider cannot return an entity and missing Context fails before allocation', async () => { + let finish!: (id: string) => void; + const generateId = jest.fn(() => new Promise(resolve => { finish = resolve; })); + const context = new UserContext().withInternalIdGenerator({generateId}); + const construct = jest.spyOn(LoadedScalarSnapshot, 'captureFor'); + try { + const pending = create(context); await Promise.resolve(); expect(construct).not.toHaveBeenCalled(); + finish('61'); expect((await pending).id).toBe('61'); + await expect(create(undefined as any)).rejects.toThrow('UserContext'); expect(generateId).toHaveBeenCalledTimes(1); + } finally { construct.mockRestore(); } +}); + +test('file-backed reservations survive reopen, reserve distinct IDs and create no business rows', async () => { + const file = database('reserved.json'); + const first = new TeaQLClient(file).install(GENERATED_RUNTIME_MODULE); + const ctx = new UserContext().insertResource('dataService', first); + const rows = await Promise.all([create(ctx), create(ctx)]); + expect(rows[0].id).not.toBe(rows[1].id); + const second = new TeaQLClient(file).install(GENERATED_RUNTIME_MODULE); + const reopened = new UserContext().insertResource('dataService', second); + expect((await create(reopened)).id).not.toBe(rows[0].id); + expect((await Q.purchaseOrders().limit(100).comment('Inspect reservation-only storage') + .purpose('Confirm ID reservation is not business persistence').executeForList(reopened)).length).toBe(0); +}); + +test('actual SQLite ID exhaustion rolls back reservation without returning a rounded identity', async () => { + const f = await fixture('exhaustion'); + const construct = jest.spyOn(LoadedScalarSnapshot, 'captureFor'); + try { + await create(f.context); construct.mockClear(); + // Test-only sequence fixture, not a business-data mutation. Model writes + // still go through the generated API in the ordinary acceptance cases. + const database = (f.client as any).driver.database; + database.prepare('UPDATE teaql_id_space SET current_level = ? WHERE type_name = ?') + .run(Number.MAX_SAFE_INTEGER, 'PurchaseOrder'); + await expect(create(f.context)).rejects.toThrow('exhausted'); + expect(construct).not.toHaveBeenCalled(); expect(f.mutation).not.toHaveBeenCalled(); + expect(database.prepare('SELECT current_level AS value FROM teaql_id_space WHERE type_name = ?') + .get('PurchaseOrder').value).toBe(Number.MAX_SAFE_INTEGER); + } finally { construct.mockRestore(); await f.close(); } +}); diff --git a/source/teaql-ts/examples/fix-e-alignment/delete-retry.test.ts b/source/teaql-ts/examples/fix-e-alignment/delete-retry.test.ts new file mode 100644 index 0000000000000000000000000000000000000000..cb997fa8365e4ee2beb711339300296082386b37 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/delete-retry.test.ts @@ -0,0 +1,72 @@ +import {readFileSync} from 'node:fs'; +import {decimal, FixedBusinessClock, UserContext} from '../../src'; +import {Q} from 'generated/generated/Q'; +import {E} from 'generated/generated/E'; +import {TeaQLClient} from 'generated/teaql-ts'; +import {GENERATED_RUNTIME_MODULE} from 'generated/runtime-module'; + +test('a failed file-backed child Delete keeps its intent and retries on the same graph', async () => { + const round = Number(process.env.TEAQL_FIX_E_ROUND); + const filename = process.env.TEAQL_FIX_E_DB! + '.delete-retry.json'; + const context = new UserContext().withActiveRoot({entity: 'Tenant', id: '1'}) + .withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new TeaQLClient(filename).install(GENERATED_RUNTIME_MODULE).setUserContext(context); + context.insertResource('dataService', client); + const parent = (await Q.purchaseOrders().comment('Prepare the file-backed Delete owner') + .purpose('Verify rollback retains child intent without updating its parent') + .newEntity(context)).updateContactPhone('5550142'); + const child = (await Q.orderItems().comment('Prepare the file-backed Delete child') + .purpose('Verify loaded Delete values are not field-write intent') + .newEntity(context)).updateProductName('Delete retry round ' + round).updateUnitPrice(decimal('12.34')); + parent.orderItemList().push(child); + await parent.auditAs('Create the Delete rollback baseline').save(context); + const baseline = readFileSync(filename), audits = client.auditTrace.length; + const root = (child as any)._root, key = {entity: 'OrderItem', id: (child as any)._ledgerId}; + const execute = client.executeMutation.bind(client); + const fault = new Error('injected failure after a real file-backed child Delete'); + const mutations = jest.spyOn(client, 'executeMutation'); + const persist = jest.spyOn(client as any, 'persist'); + child.markForDeletion(); + mutations.mockImplementationOnce(async request => {await execute(request); throw fault;}); + try { + await expect(parent.auditAs('Attempt child deletion with an injected rollback').save(context)).rejects.toBe(fault); + const rollback = {fileUnchanged: readFileSync(filename).equals(baseline), + auditDelta: client.auditTrace.length - audits, persistCalls: persist.mock.calls.length, + pendingDelete: root.isDeleted(key), ledgerFields: Object.keys(root.change(key)), + parentVersion: E.purchaseOrder(parent).version().eval(), childVersion: E.orderItem(child).version().eval(), + originalVersion: root.originalVersion(key), scopeReleased: context.getResource('fixTime') === undefined}; + const reloaded = new TeaQLClient(filename).install(GENERATED_RUNTIME_MODULE).setUserContext(context); + context.insertResource('dataService', reloaded); + const rows = await Q.orderItems().withIdIs(child.id!).limit(1).comment('Independently read the rolled-back child') + .purpose('Check the file still has the live version').executeForList(context); + expect(rows).toHaveLength(1); expect(E.orderItem(rows[0]).version().eval()).toBe(1); + context.insertResource('dataService', client); + mutations.mockImplementation(execute); mutations.mockClear(); persist.mockClear(); + let retryError: unknown; + try {await parent.auditAs('Retry deletion of the same child without reloading the graph').save(context);} + catch (error) {retryError = error;} + const facts = {round, rollback, retryError: retryError instanceof Error ? retryError.message : retryError ?? null, + retryMutations: mutations.mock.calls.length, retryPersists: persist.mock.calls.length, + auditDelta: client.auditTrace.length - audits, parentVersion: E.purchaseOrder(parent).version().eval(), + childVersion: E.orderItem(child).version().eval()}; + process.stdout.write('CORE_TS_FILE_DELETE_RETRY=' + JSON.stringify(facts) + '\n'); + expect(rollback).toEqual({fileUnchanged: true, auditDelta: 0, persistCalls: 0, pendingDelete: true, + ledgerFields: [], parentVersion: 1, childVersion: 1, originalVersion: 1, scopeReleased: true}); + if (retryError) throw retryError; + expect(facts).toMatchObject({retryMutations: 1, retryPersists: 1, auditDelta: 1, parentVersion: 1, childVersion: -2}); + expect(root.hasPending(key)).toBe(false); + const stored = JSON.parse(readFileSync(filename, 'utf8')).data; + expect(stored.PurchaseOrder[parent.id!].version).toBe(1); + expect(stored.OrderItem[child.id!].version).toBe(-2); + expect(stored.OrderItem[child.id!].product_name ?? stored.OrderItem[child.id!].productName).toBe('Delete retry round ' + round); + const visible = await Q.orderItems().withIdIs(child.id!).limit(1).comment('Check committed tombstone visibility') + .purpose('Verify successful retry hides the deleted child').executeForList(context); + expect(visible).toHaveLength(0); + mutations.mockClear(); persist.mockClear(); + await expect(parent.auditAs('Reject deleting an already committed tombstone').save(context)).rejects.toMatchObject({ + violations: expect.arrayContaining([expect.objectContaining({ruleId: 'invalid_type'})]), + }); + expect(mutations).not.toHaveBeenCalled(); expect(persist).not.toHaveBeenCalled(); + expect(client.auditTrace).toHaveLength(audits + 1); + } finally {mutations.mockRestore(); persist.mockRestore();} +}); diff --git a/source/teaql-ts/examples/fix-e-alignment/expression-boundary-probe.ts b/source/teaql-ts/examples/fix-e-alignment/expression-boundary-probe.ts new file mode 100644 index 0000000000000000000000000000000000000000..709189e9e9306de62df4afc813a57de390debbc5 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/expression-boundary-probe.ts @@ -0,0 +1,145 @@ +import { createHash } from 'node:crypto'; +import { decimal, ExpressionPath, FixedBusinessClock, TeaQLNotLoadedError, UserContext } from '../../src'; +import { E } from 'generated/generated/E'; +import { Q } from 'generated/generated/Q'; +import { SQLiteTeaQLClient } from 'generated/teaql-node-sqlite'; + +// Application-owned test. Generated Q/E/entity files remain untouched. +export async function verifyExpressionBoundaries(filename: string): Promise { + const context = new UserContext().withBusinessClock(new FixedBusinessClock(new Date('2032-02-29T10:15:30Z'))); + const client = new SQLiteTeaQLClient(filename).setUserContext(context); + context.insertResource('dataService', client); + const driver = (client as any).driver; + const query = jest.spyOn(driver, 'query'), transaction = jest.spyOn(driver, 'transaction'); + const policy = jest.spyOn(context, 'enterMutationPolicy'); + const cases: Array> = []; + const record = (name: string, facts: Record) => { + const value = {case: name, ...facts}; cases.push(value); + process.stdout.write('CORE_TS_E_CASE=' + JSON.stringify(value) + '\n'); + }; + const missing = (read: () => unknown, pointer: string, attempted: string, expression: string) => { + try { read(); } catch (error) { + if (!(error instanceof TeaQLNotLoadedError)) throw error; + const wire = error.toWire(); + expect(wire.code).toBe('NOT_LOADED'); expect(wire.instancePath).toBe(pointer); + expect(wire.attemptedInstancePath).toBe(attempted); + expect(wire.expressionWithBrokenPoint).toBe(expression); + expect(expression.match(//g)).toHaveLength(1); + expect(wire.originalExpression).toBe(expression.replace('', '')); + expect(wire.suggestedFix).toEqual({action: 'preload', location: wire.location}); + expect(error.message).toContain('expression=' + expression); + expect(error.message).not.toContain('PRIVATE_TS_ROOT'); + expect(JSON.stringify(wire)).not.toContain('PRIVATE_TS_FALLBACK'); + return {wire, human: error.message}; + } + throw new Error('NotLoaded must not become loaded null, absence or fallback'); + }; + try { + await context.ensureSchema(); + const parent = (await Q.purchaseOrders().comment('Create the generated E boundary parent') + .purpose('Verify expression diagnostics against persisted rows').newEntity(context)); + parent.updateContactPhone('PRIVATE_TS_ROOT_123'); + for (let i = 0; i < 3; i++) { + const child = (await Q.orderItems().comment('Create an indexed E boundary child') + .purpose('Exercise real loaded-list positions').newEntity(context)); + child.updateProductName('Expression item ' + i).updateUnitPrice(decimal('10.00')); + parent.orderItemList().push(child); + } + await parent.auditAs('Persist the generated E boundary graph').save(context); + const empty = (await Q.purchaseOrders().comment('Create the loaded-empty E boundary parent') + .purpose('Distinguish loaded empty from NotLoaded').newEntity(context)); + empty.updateContactPhone('PRIVATE_TS_ROOT_EMPTY'); + await empty.auditAs('Persist the parent without children').save(context); + const calibration = {queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + policies: policy.mock.calls.length, audits: client.auditTrace.length}; + for (const value of Object.values(calibration)) expect(value).toBeGreaterThan(0); + + const late = (await Q.purchaseOrdersWithMinimalFields().withIdIs(parent.id!) + .selectTenantWith(Q.tenantsWithMinimalFields().limit(1).comment('Load the target identity, not its name')) + .limit(1).comment('Load a real relation with a missing late scalar') + .purpose('Keep the first missing leaf distinct from its loaded relation').executeForList(context))[0]; + const indexed = (await Q.purchaseOrders().withIdIs(parent.id!) + .selectOrderItemListWith(Q.orderItemsWithMinimalFields().selectUnitPrice().orderByIdAscending().limit(3) + .comment('Load child identities and prices without product names')) + .limit(1).comment('Load the indexed sparse child graph') + .purpose('Verify numeric E locations against actual rows').executeForList(context))[0]; + const emptyLoaded = (await Q.purchaseOrders().withIdIs(empty.id!) + .selectOrderItemListWith(Q.orderItems().limit(3).comment('Load the genuinely empty list')) + .limit(1).comment('Load a parent with no child records') + .purpose('Preserve native loaded-empty behavior').executeForList(context))[0]; + const fkOnly = (await Q.purchaseOrders().withIdIs(parent.id!).limit(1) + .comment('Load the FK without target details').purpose('Never fabricate a target from its ID') + .executeForList(context))[0]; + expect(late).toBeDefined(); expect(indexed).toBeDefined(); expect(emptyLoaded).toBeDefined(); expect(fkOnly).toBeDefined(); + expect(String(E.purchaseOrder(late).tenant().id().eval())).toBe('1'); + expect(E.purchaseOrder(indexed).orderItemList().size().eval()).toBe(3); + const childIds = [0, 1, 2].map(i => E.purchaseOrder(indexed).orderItemList().get(i).id().eval()); + expect(new Set(childIds).size).toBe(3); + const rows = [late, indexed, emptyLoaded, fkOnly]; + const snapshot = () => createHash('sha256').update(JSON.stringify({values: rows, + loaded: rows.map(row => ['id', 'version', 'tenant', 'contactPhone', 'internalNote', 'orderItemList'].map(key => row.isLoaded(key))), + ledgers: rows.map(row => (row as any)._root.change({entity: 'PurchaseOrder', id: (row as any)._ledgerId}) ?? null), + })).digest('hex'); + const before = snapshot(), audits = client.auditTrace.length; + query.mockClear(); transaction.mockClear(); policy.mockClear(); + + record('late-leaf', missing(() => E.purchaseOrder(late).tenant().name().eval(), '/tenant/name', '/tenant/name', + 'E.purchaseOrder().tenant().name().eval()')); + record('indexed-leaf', missing(() => E.purchaseOrder(indexed).orderItemList().get(2).productName().eval(), + '/orderItemList/2/productName', '/orderItemList/2/productName', + 'E.purchaseOrder().orderItemList().get(2).productName().eval()')); + const nullValue = E.purchaseOrder(fkOnly).internalNote(); + expect(nullValue.eval()).toBeNull(); expect(nullValue.isPresent()).toBe(true); + expect(nullValue.orElse('PRIVATE_TS_FALLBACK')).toBe('PRIVATE_TS_FALLBACK'); + record('loaded-null', {value: nullValue.eval(), present: nullValue.isPresent(), fallbackUsed: true}); + const emptyValue = E.purchaseOrder(emptyLoaded).orderItemList().first().productName(); + expect(E.purchaseOrder(emptyLoaded).orderItemList().size().eval()).toBe(0); + expect(emptyValue.eval()).toBeUndefined(); expect(emptyValue.isPresent()).toBe(false); + expect(emptyValue.orElse('PRIVATE_TS_FALLBACK')).toBe('PRIVATE_TS_FALLBACK'); + record('loaded-empty', {size: 0, valueKind: typeof emptyValue.eval(), present: emptyValue.isPresent(), fallbackUsed: true}); + const beyond = E.purchaseOrder(indexed).orderItemList().get(3).productName(); + expect(beyond.eval()).toBeUndefined(); expect(beyond.isPresent()).toBe(false); + expect(beyond.orElse('PRIVATE_TS_FALLBACK')).toBe('PRIVATE_TS_FALLBACK'); + expect(E.purchaseOrder(indexed).orderItemList().get(-1).productName().eval()).toBeUndefined(); + record('out-of-range', {index: 3, negativeIndex: -1, valueKind: typeof beyond.eval(), present: beyond.isPresent(), fallbackUsed: true}); + const leaf = E.purchaseOrder(fkOnly).tenant().name(); + const terminals = [ + missing(() => leaf.eval(), '/tenant', '/tenant/name', 'E.purchaseOrder().tenant().name().eval()'), + missing(() => leaf.isPresent(), '/tenant', '/tenant/name', 'E.purchaseOrder().tenant().name().isPresent()'), + missing(() => leaf.orElse('PRIVATE_TS_FALLBACK'), '/tenant', '/tenant/name', 'E.purchaseOrder().tenant().name().orElse()'), + ]; + record('terminal-not-loaded', {terminals}); + const branch = E.purchaseOrder(fkOnly).tenant(), left = branch.name(), right = branch.purchaseOrderList().first().contactPhone(); + const leftExpression = 'E.purchaseOrder().tenant().name().eval()'; + const leftBefore = missing(() => left.eval(), '/tenant', '/tenant/name', leftExpression); + const rightFailure = missing(() => right.eval(), '/tenant', '/tenant/purchaseOrderList/0/contactPhone', + 'E.purchaseOrder().tenant().purchaseOrderList().first().contactPhone().eval()'); + const leftAfter = missing(() => left.eval(), '/tenant', '/tenant/name', leftExpression); + expect(leftAfter).toEqual(leftBefore); + record('sibling-paths', {leftBefore, right: rightFailure, leftAfter}); + expect(String(E.purchaseOrder(fkOnly).tenantId().eval())).toBe('1'); + record('fk-only-not-loaded', {fk: 1, failure: missing(() => E.purchaseOrder(fkOnly).tenant().eval(), '/tenant', '/tenant', + 'E.purchaseOrder().tenant().eval()')}); + const after = snapshot(); expect(after).toBe(before); + const effects = {queries: query.mock.calls.length, transactions: transaction.mock.calls.length, + policies: policy.mock.calls.length, audits: client.auditTrace.length - audits}; + expect(effects).toEqual({queries: 0, transactions: 0, policies: 0, audits: 0}); + record('no-side-effects', {before, after, effects, calibration}); + + // Native-only location component: the fixture has no punctuation-named model field. + const profiles = (['camelCase', 'snake_case', 'PascalCase'] as const).map(profile => { + const path = ExpressionPath.root('E.native()', profile).member('a~/b.c', 'safeMethod').markMissing(); + const error = new TeaQLNotLoadedError(path, 'a~/b.c').terminal('eval()'); + expect(error.toWire().instancePath).toBe(profile === 'PascalCase' ? '/A~0~1b.c' : '/a~0~1b.c'); + expect(error.toWire().location).toEqual([{kind: 'property', name: 'a~/b.c'}]); + return {profile, wire: error.toWire()}; + }); + record('native-punctuation', {nativeOnly: true, profiles}); + process.stdout.write('CORE_TS_E_BOUNDARY_RESULT=' + JSON.stringify({language: 'typescript', passed: true, + parentId: parent.id, emptyParentId: empty.id, childIds, cases: cases.map(value => value.case), + generatedCases: 9, nativeLocationCases: 1, terminalObservations: terminals.length, + fullPunctuationGeneratedPathAccepted: false, physicalVersionsUnchanged: true, effects}) + '\n'); + } finally { + query.mockRestore(); transaction.mockRestore(); policy.mockRestore(); await client.close(); + } +} diff --git a/source/teaql-ts/examples/fix-e-alignment/fixture-manifest.json b/source/teaql-ts/examples/fix-e-alignment/fixture-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..2a96f3d1c0b43b78aebd1d4af5d4701a220f40a6 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/fixture-manifest.json @@ -0,0 +1,67 @@ +{ + "schema": "teaql.generated-example-fixture/v1", + "language": "typescript", + "modelSha256": "a2cf4c907cb084cb0946e993eeba586c8c0701a89fdc4a849808aa743be033b7", + "generatedManifestSha256": "104e28e215a041d06fd86976833a3e3ebe818eee0e326df08e16b01389911709", + "producerReceiptSha256": "59a02bea2a82739251933d54aa0d5fb287ddd286ba9ad49d6ab9f24d9d851e83", + "producerReceiptSchema": "teaql.generator-qualified-union-export/v1", + "producerSource": { + "commit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "sourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937" + }, + "evaluatedScope": "typescript-node-lib-core", + "evaluationErrors": 0, + "evaluationWarnings": 4, + "files": { + "src/generated/Q.ts": "05ce50d75c5cfb3603168bc18d8d915de16b76781d706447b7f766b20a73ed87", + "src/generated/requests/TenantRequest.ts": "ef0a19b22463fa587329c6dbac02ab0a36c1c0a028df8a55ae18ba9f3b5682d3", + "src/generated/requests/PurchaseOrderRequest.ts": "ff9abb76e676c2896aba610b7aec8d5aa59ee70bbfb4927a87f11e7de3ddf9b5", + "src/generated/requests/OrderItemRequest.ts": "d34f38b4b08026fd7037d7c6e4dd9aea3d2f9201fa5c775bc90ff849c765c17f", + "teaql-i18n.json": "c8229ce36ed92393409dd95a5e6a6bd72c9818c95520d5d2e3656ac6f7c0f014", + "src/generated/E.ts": "717cc96e91be5ed57279712fe82c4e5831d3bda037258c8597e268c50baed54b", + "package.json": "9d6bff3b787abb3c141211704048ab53cc06d366aab436790120074b7ebcb1c9", + "tsconfig.json": "cf9a9767019ac7f4035a6d16952a5ae75b964b1c10c4584822b90799e6ce2037", + "src/teaql-ts.ts": "3ddf92defac1865617a737415bbadb86ffba6f071822463440413f7c12d1b814", + "src/generated-search-models.ts": "f7be71e619617cb1ff0011791d82f0bcd6ef9e3f94ce6f8159f283d3d160aef6", + "src/teaql-node-sql.ts": "dabe21ab06bc85ee8ae2ca76440ef7fe7f8c3212fa2cd82ebdb838d549a276a3", + "src/runtime-module.ts": "d665f68c46986a5f62fcf21cf4153b99ac98e4cfe5ef2e755df0902306923e51", + "src/generated-bootstrap.ts": "71cc3c025cf32f6e05626cb661a3fedaeccc7bf3be189a9e5c6d3facb5bc6056", + "src/teaql-node-sqlite.ts": "7a984388cc13bfdc4230a85cd4b360b4e0cc63ed8f122c516a2361a5e483a91c", + "src/generated/models/Tenant.ts": "46774bc45834a3c033c1e7da26abec9af272a768f1831728313bef4f57f8fcfd", + "src/generated/models/PurchaseOrder.ts": "07159c49037a18eb9c8cedb1e0413dc6e2dc89e1ea27d08478e30d2cf29311b2", + "src/generated/models/OrderItem.ts": "f2234d0ffe17b0f2bd9a481326125d77150921f0ac312fe893a991e0613d0405" + }, + "previousFixtureManifestSha256": "a1c13ddbc77b112f5f22c96b34220ffb26f8d30d0e85b208392f94bb264659b3", + "regeneration": { + "repository": "teaql/teaql-conformance", + "receipt": "evidence/2026-10-25-core-p0-p1/generator-qualified-union-export-v2/report.json", + "qualification": "Actual evaluated export from the unified generator; all fixture bytes match the retained generated manifest.", + "changedFiles": [ + "src/teaql-ts.ts", + "src/generated/requests/TenantRequest.ts", + "src/generated/requests/PurchaseOrderRequest.ts", + "src/generated/requests/OrderItemRequest.ts" + ] + }, + "previousRegeneration": { + "repository": "teaql/teaql-conformance", + "qualifiedReceipt": "evidence/2026-10-25-core-p0-p1/generator-typescript-graph-fix-idempotence-ordered/report.json", + "rawDonor": { + "label": "generator-typescript-graph-fix-idempotence", + "reportSha256": "2a629d568ad37a9a5925df4bf94fc7c7bbcd158deee99cd2c9ceefbc29b7b2c2", + "nativeGenerationPassed": true, + "originalCollectorAccepted": false + }, + "originalCollectorAccepted": false, + "qualification": "Five native generator tests passed; ordered-file-set qualifier rejects the original collector result and independently checks every generated hash.", + "changedFiles": [ + "src/generated/models/OrderItem.ts", + "src/generated/models/PurchaseOrder.ts", + "src/generated/models/Tenant.ts", + "src/teaql-ts.ts" + ] + }, + "generatorCommit": "e6cd611ae1d5413c24c717c3650c9f5a3c301b08", + "generatorSourceContentsSha256": "2adbc3e7d627fe0a355dcc4459a244749c8bd51022576eb307efcbab49e03937", + "producerReportSha256": "a09fb7991972743b7f603f5771e321cef772583af30e3763979c190a657c8e6d" +} diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/package.json b/source/teaql-ts/examples/fix-e-alignment/generated/package.json new file mode 100644 index 0000000000000000000000000000000000000000..f8450b44f1430b0c04b794541e05532a1417d9b5 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/package.json @@ -0,0 +1,18 @@ +{ + "name": "checker-fix-advanced-lib", + "version": "1.0.0", + "description": "Generated typescript library", + "engines": { "node": ">=22" }, + "main": "src/generated/Q.ts", + "scripts": { + "build": "tsc --noEmit" + }, + "dependencies": { + "teaql-ts": "npm:@teaql/teaql@0.3.1", + "better-sqlite3": "^13.0.3"}, + "devDependencies": { + "typescript": "^5.0.0", + "ts-node": "^10.9.2", + "@types/node": "^22.0.0", + "@types/better-sqlite3": "^7.6.12"} +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/E.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/E.ts new file mode 100644 index 0000000000000000000000000000000000000000..a8e56c226aeba5470956e022238537f7c4710cee --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/E.ts @@ -0,0 +1,570 @@ +import type { Decimal, Long, LocalTime, EntityVersion } from 'teaql-ts'; +import { Tenant } from './models/Tenant'; +import { PurchaseOrder } from './models/PurchaseOrder'; +import { OrderItem } from './models/OrderItem'; +import { CheckException, integer32Error, ExpressionPath, TeaQLNotLoadedError } from '../teaql-ts'; +export { TeaQLNotLoadedError } from '../teaql-ts'; + +export class ValueExpression { + constructor( + private readonly value: T | null | undefined, + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + private readonly invalidValue?: CheckException, + ) {} + + static missing(): ValueExpression { + return new ValueExpression(undefined, false); + } + + static notLoaded(error: TeaQLNotLoadedError): ValueExpression { + return new ValueExpression(undefined, false, error); + } + + static invalid(error: CheckException): ValueExpression { + return new ValueExpression(undefined, false, undefined, error); + } + + eval(): T | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + if (this.invalidValue) throw this.invalidValue; + return this.present ? this.value : undefined; + } + + isPresent(): boolean { + if (this.notLoaded) throw this.notLoaded.terminal('isPresent()'); + if (this.invalidValue) throw this.invalidValue; + return this.present; + } + + orElse(fallback: T): T { + if (this.notLoaded) throw this.notLoaded.terminal('orElse()'); + if (this.invalidValue) throw this.invalidValue; + const value = this.value; + return this.present && value != null ? value : fallback; + } +} + +export class TenantExpression { + constructor( + private readonly value: Tenant | null | undefined, + private readonly root = 'Tenant(null)', + private readonly path = ExpressionPath.root('E.tenant()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): Tenant | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + name(): ValueExpression { + const path = this.path.member('name', 'name'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('name')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'name'), + ); + } + return new ValueExpression(this.value.name); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + + + purchaseOrderList(): PurchaseOrderListExpression { + const path = this.path.member('purchase_order_list', 'purchaseOrderList'); + if (this.notLoaded) { + return new PurchaseOrderListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return PurchaseOrderListExpression.missing(this.root, path); + if (!this.value.isLoaded('purchaseOrderList')) { + return new PurchaseOrderListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'purchase_order_list')); + } + return new PurchaseOrderListExpression( + this.value.purchaseOrderList(), this.root, path, + ); + } + + orderItemList(): OrderItemListExpression { + const path = this.path.member('order_item_list', 'orderItemList'); + if (this.notLoaded) { + return new OrderItemListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderItemListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderItemList')) { + return new OrderItemListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_item_list')); + } + return new OrderItemListExpression( + this.value.orderItemList(), this.root, path, + ); + } +} + +export class PurchaseOrderExpression { + constructor( + private readonly value: PurchaseOrder | null | undefined, + private readonly root = 'PurchaseOrder(null)', + private readonly path = ExpressionPath.root('E.purchaseOrder()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): PurchaseOrder | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + contactPhone(): ValueExpression { + const path = this.path.member('contact_phone', 'contactPhone'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('contactPhone')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'contact_phone'), + ); + } + return new ValueExpression(this.value.contactPhone); + } + + internalNote(): ValueExpression { + const path = this.path.member('internal_note', 'internalNote'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('internalNote')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'internal_note'), + ); + } + return new ValueExpression(this.value.internalNote); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + tenantId(): ValueExpression { + const path = this.path.member('tenant', 'tenantId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('tenant')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'tenant'), + ); + } + const reference = this.value.tenant; + return new ValueExpression( + reference instanceof Tenant + ? reference.id : reference as string | number | undefined, + ); + } + + tenant(): TenantExpression { + const path = this.path.member('tenant', 'tenant'); + if (this.notLoaded) { + return new TenantExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TenantExpression(undefined, this.root, path); + if (!this.value.isLoaded('tenant')) { + return new TenantExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'tenant')); + } + const relation = this.value.tenant; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Tenant)) { + return new TenantExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'tenant')); + } + const target = relation instanceof Tenant ? relation : undefined; + return new TenantExpression(target, this.root, path); + } + + orderItemList(): OrderItemListExpression { + const path = this.path.member('order_item_list', 'orderItemList'); + if (this.notLoaded) { + return new OrderItemListExpression([], this.root, path, false, this.notLoaded.withPath(path)); + } + if (!this.value) return OrderItemListExpression.missing(this.root, path); + if (!this.value.isLoaded('orderItemList')) { + return new OrderItemListExpression([], this.root, path, false, + new TeaQLNotLoadedError(path.markMissing(), 'order_item_list')); + } + return new OrderItemListExpression( + this.value.orderItemList(), this.root, path, + ); + } +} + +export class OrderItemExpression { + constructor( + private readonly value: OrderItem | null | undefined, + private readonly root = 'OrderItem(null)', + private readonly path = ExpressionPath.root('E.orderItem()', 'camelCase'), + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + eval(): OrderItem | null | undefined { + if (this.notLoaded) throw this.notLoaded.terminal('eval()'); + return this.value; + } + + id(): ValueExpression { + const path = this.path.member('id', 'id'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('id')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'id'), + ); + } + return new ValueExpression(this.value.id); + } + + productName(): ValueExpression { + const path = this.path.member('product_name', 'productName'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('productName')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'product_name'), + ); + } + return new ValueExpression(this.value.productName); + } + + unitPrice(): ValueExpression { + const path = this.path.member('unit_price', 'unitPrice'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('unitPrice')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'unit_price'), + ); + } + return new ValueExpression(this.value.unitPrice); + } + + createTime(): ValueExpression { + const path = this.path.member('create_time', 'createTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('createTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'create_time'), + ); + } + return new ValueExpression(this.value.createTime); + } + + updateTime(): ValueExpression { + const path = this.path.member('update_time', 'updateTime'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('updateTime')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'update_time'), + ); + } + return new ValueExpression(this.value.updateTime); + } + + version(): ValueExpression { + const path = this.path.member('version', 'version'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('version')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'version'), + ); + } + return new ValueExpression(this.value.version); + } + + purchaseOrderId(): ValueExpression { + const path = this.path.member('purchase_order', 'purchaseOrderId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('purchaseOrder')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'purchase_order'), + ); + } + const reference = this.value.purchaseOrder; + return new ValueExpression( + reference instanceof PurchaseOrder + ? reference.id : reference as string | number | undefined, + ); + } + + tenantId(): ValueExpression { + const path = this.path.member('tenant', 'tenantId'); + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(path)); + if (!this.value) return ValueExpression.missing(); + if (!this.value.isLoaded('tenant')) { + return ValueExpression.notLoaded( + new TeaQLNotLoadedError(path.markMissing(), 'tenant'), + ); + } + const reference = this.value.tenant; + return new ValueExpression( + reference instanceof Tenant + ? reference.id : reference as string | number | undefined, + ); + } + + purchaseOrder(): PurchaseOrderExpression { + const path = this.path.member('purchase_order', 'purchaseOrder'); + if (this.notLoaded) { + return new PurchaseOrderExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new PurchaseOrderExpression(undefined, this.root, path); + if (!this.value.isLoaded('purchaseOrder')) { + return new PurchaseOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'purchase_order')); + } + const relation = this.value.purchaseOrder; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof PurchaseOrder)) { + return new PurchaseOrderExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'purchase_order')); + } + const target = relation instanceof PurchaseOrder ? relation : undefined; + return new PurchaseOrderExpression(target, this.root, path); + } + + tenant(): TenantExpression { + const path = this.path.member('tenant', 'tenant'); + if (this.notLoaded) { + return new TenantExpression(undefined, this.root, path, this.notLoaded.withPath(path)); + } + if (!this.value) return new TenantExpression(undefined, this.root, path); + if (!this.value.isLoaded('tenant')) { + return new TenantExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'tenant')); + } + const relation = this.value.tenant; + // An available FK is not an eagerly loaded relation. Keep the FK + // readable through the Id accessor, without fabricating a child object. + if (relation != null && !(relation instanceof Tenant)) { + return new TenantExpression(undefined, this.root, path, + new TeaQLNotLoadedError(path.markMissing(), 'tenant')); + } + const target = relation instanceof Tenant ? relation : undefined; + return new TenantExpression(target, this.root, path); + } + +} + +export class TenantListExpression { + constructor( + private readonly items: readonly Tenant[], + private readonly root = 'Tenant(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): TenantListExpression { + return new TenantListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): TenantExpression { + return this.item(0, true); + } + + get(index: number): TenantExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): TenantExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new TenantExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new TenantExpression(undefined, this.root, itemPath) + : new TenantExpression(this.items[index], this.root, itemPath); + } +} + +export class PurchaseOrderListExpression { + constructor( + private readonly items: readonly PurchaseOrder[], + private readonly root = 'PurchaseOrder(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): PurchaseOrderListExpression { + return new PurchaseOrderListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): PurchaseOrderExpression { + return this.item(0, true); + } + + get(index: number): PurchaseOrderExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): PurchaseOrderExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new PurchaseOrderExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new PurchaseOrderExpression(undefined, this.root, itemPath) + : new PurchaseOrderExpression(this.items[index], this.root, itemPath); + } +} + +export class OrderItemListExpression { + constructor( + private readonly items: readonly OrderItem[], + private readonly root = 'OrderItem(null)', + private readonly path = ExpressionPath.root('E.entity()', 'camelCase'), + private readonly present = true, + private readonly notLoaded?: TeaQLNotLoadedError, + ) {} + + static missing(root?: string, path = ExpressionPath.root('E.entity()', 'camelCase')): OrderItemListExpression { + return new OrderItemListExpression([], root, path, false); + } + + size(): ValueExpression { + if (this.notLoaded) return ValueExpression.notLoaded(this.notLoaded.withPath(this.path.operation('size()'))); + return this.present + ? new ValueExpression(this.items.length) + : ValueExpression.missing(); + } + + first(): OrderItemExpression { + return this.item(0, true); + } + + get(index: number): OrderItemExpression { + return this.item(index, false); + } + + private item(index: number, first: boolean): OrderItemExpression { + const itemPath = this.path.index(index, first); + if (this.notLoaded) { + return new OrderItemExpression(undefined, this.root, itemPath, this.notLoaded.withPath(itemPath)); + } + return !this.present || index < 0 || index >= this.items.length + ? new OrderItemExpression(undefined, this.root, itemPath) + : new OrderItemExpression(this.items[index], this.root, itemPath); + } +} + +export class E { + static tenant( + value: Tenant | null | undefined, + ): TenantExpression { + return new TenantExpression( + value, 'Tenant', ExpressionPath.root('E.tenant()', 'camelCase'), + ); + } + + static purchaseOrder( + value: PurchaseOrder | null | undefined, + ): PurchaseOrderExpression { + return new PurchaseOrderExpression( + value, 'PurchaseOrder', ExpressionPath.root('E.purchaseOrder()', 'camelCase'), + ); + } + + static orderItem( + value: OrderItem | null | undefined, + ): OrderItemExpression { + return new OrderItemExpression( + value, 'OrderItem', ExpressionPath.root('E.orderItem()', 'camelCase'), + ); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/Q.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/Q.ts new file mode 100644 index 0000000000000000000000000000000000000000..64cae8b11a5c168586c2999fc4191b701edcc6ff --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/Q.ts @@ -0,0 +1,28 @@ +import { TeaQLClient } from '../teaql-ts'; +import { TenantRequest } from './requests/TenantRequest'; +import { PurchaseOrderRequest } from './requests/PurchaseOrderRequest'; +import { OrderItemRequest } from './requests/OrderItemRequest'; + +export class Q { + static tenants(): TenantRequest { + return new TenantRequest(false); + } + + static tenantsWithMinimalFields(): TenantRequest { + return new TenantRequest(true); + } + static purchaseOrders(): PurchaseOrderRequest { + return new PurchaseOrderRequest(false); + } + + static purchaseOrdersWithMinimalFields(): PurchaseOrderRequest { + return new PurchaseOrderRequest(true); + } + static orderItems(): OrderItemRequest { + return new OrderItemRequest(false); + } + + static orderItemsWithMinimalFields(): OrderItemRequest { + return new OrderItemRequest(true); + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/OrderItem.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/OrderItem.ts new file mode 100644 index 0000000000000000000000000000000000000000..15fb52c3d49c528da99b9ade1e52309f75280396 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/OrderItem.ts @@ -0,0 +1,376 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { PurchaseOrder } from './PurchaseOrder'; +import { Tenant } from './Tenant'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class OrderItem { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("OrderItem", + ["id", "purchase_order", "tenant", "product_name", "unit_price", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + purchaseOrder?: PurchaseOrder | string; + tenant?: Tenant | string; + productName?: string; + unitPrice?: Decimal; + createTime?: string; + updateTime?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --OrderItem.teaqlTemporaryId, writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + Object.assign(this, fields); + if ((init as any).purchaseOrder && typeof (init as any).purchaseOrder === "object") { + this.purchaseOrder = (init as any).purchaseOrder instanceof PurchaseOrder + ? (init as any).purchaseOrder + : PurchaseOrder.fromRecord((init as any).purchaseOrder); + this.markLoaded("purchaseOrder"); + } + if ((init as any).tenant && typeof (init as any).tenant === "object") { + this.tenant = (init as any).tenant instanceof Tenant + ? (init as any).tenant + : Tenant.fromRecord((init as any).tenant); + this.markLoaded("tenant"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "OrderItem", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): OrderItem { + const entity = EntityCreation.hydrated(new OrderItem(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): OrderItem { + return OrderItem.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): OrderItem { + return EntityCreation.bootstrap(context, "OrderItem", id, + reserved => new OrderItem({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "OrderItem", + reserved => new OrderItem({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "purchase_order": "PurchaseOrder", + "tenant": "Tenant" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + })); + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + OrderItem.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "purchaseOrder", canonical: "purchase_order" }, { member: "tenant", canonical: "tenant" }, { member: "productName", canonical: "product_name" }, { member: "unitPrice", canonical: "unit_price" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "OrderItem", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(OrderItem.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "purchaseOrder", canonical: "purchase_order" }, { member: "tenant", canonical: "tenant" }, { member: "productName", canonical: "product_name" }, { member: "unitPrice", canonical: "unit_price" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "OrderItem", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "OrderItem", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "OrderItem", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "purchase_order": this.purchaseOrder, + "tenant": this.tenant, + "product_name": this.productName, + "unit_price": this.unitPrice, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateProductName(value: string): this { + this.productName = value; + this.markLoaded("productName"); + (this as any)._root.set(this.teaqlEntityKey(), "product_name", value); + return this; + } + + updateUnitPrice(value: Decimal): this { + if (value != null) value = decimal(value); + this.unitPrice = value; + this.markLoaded("unitPrice"); + (this as any)._root.set(this.teaqlEntityKey(), "unit_price", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + updatePurchaseOrder(value: any): this { + this.purchaseOrder = value?.id ?? value; + this.markLoaded("purchaseOrder"); + (this as any)._root.set(this.teaqlEntityKey(), "purchase_order", this.purchaseOrder); + return this; + } + + + private teaqlSetTenant(value: any): this { + this.tenant = value?.id ?? value; + this.markLoaded("tenant"); + (this as any)._root.set(this.teaqlEntityKey(), "tenant", this.tenant); + return this; + } + +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/PurchaseOrder.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/PurchaseOrder.ts new file mode 100644 index 0000000000000000000000000000000000000000..85b1dfad0e2cf71822013b25097991705c9bda57 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/PurchaseOrder.ts @@ -0,0 +1,447 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { Tenant } from './Tenant'; +import { OrderItem } from './OrderItem'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class PurchaseOrder { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("PurchaseOrder", + ["id", "tenant", "contact_phone", "internal_note", "create_time", "update_time", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + tenant?: Tenant | string; + contactPhone?: string; + internalNote?: string | null; + createTime?: string; + updateTime?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --PurchaseOrder.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_orderItemList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["orderItemList"]; + Object.assign(this, fields); + if ((init as any).tenant && typeof (init as any).tenant === "object") { + this.tenant = (init as any).tenant instanceof Tenant + ? (init as any).tenant + : Tenant.fromRecord((init as any).tenant); + this.markLoaded("tenant"); + } + if (Array.isArray((init as any).orderItemList)) { + const selected = (init as any).orderItemList; + (this as any)._orderItemList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderItem + ? child + : OrderItem.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderItemList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "PurchaseOrder", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): PurchaseOrder { + const entity = EntityCreation.hydrated(new PurchaseOrder(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("orderItemList")) result["orderItemList"] = (this as any)._orderItemList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): PurchaseOrder { + return PurchaseOrder.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): PurchaseOrder { + return EntityCreation.bootstrap(context, "PurchaseOrder", id, + reserved => new PurchaseOrder({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "PurchaseOrder", + reserved => new PurchaseOrder({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._orderItemList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(PurchaseOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._orderItemList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(PurchaseOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + "tenant": "Tenant" + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "order_item_list": graph.sourceMembers((this as any)._orderItemList) + })); + for (const child of (this as any)._orderItemList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.purchaseOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("purchaseOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePurchaseOrder(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + PurchaseOrder.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "tenant", canonical: "tenant" }, { member: "contactPhone", canonical: "contact_phone" }, { member: "internalNote", canonical: "internal_note" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "PurchaseOrder", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(PurchaseOrder.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "tenant", canonical: "tenant" }, { member: "contactPhone", canonical: "contact_phone" }, { member: "internalNote", canonical: "internal_note" }, { member: "createTime", canonical: "create_time" }, { member: "updateTime", canonical: "update_time" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "PurchaseOrder", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "PurchaseOrder", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._orderItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.purchaseOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("purchaseOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePurchaseOrder(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "PurchaseOrder", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._orderItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.purchaseOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("purchaseOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePurchaseOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._orderItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.purchaseOrder; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("purchaseOrder") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.updatePurchaseOrder(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "tenant": this.tenant, + "contact_phone": this.contactPhone, + "internal_note": this.internalNote, + "create_time": this.createTime, + "update_time": this.updateTime, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateContactPhone(value: string): this { + this.contactPhone = value; + this.markLoaded("contactPhone"); + (this as any)._root.set(this.teaqlEntityKey(), "contact_phone", value); + return this; + } + + updateInternalNote(value: string | null): this { + this.internalNote = value; + this.markLoaded("internalNote"); + (this as any)._root.set(this.teaqlEntityKey(), "internal_note", value); + return this; + } + + updateCreateTime(value: string): this { + this.createTime = value; + this.markLoaded("createTime"); + (this as any)._root.set(this.teaqlEntityKey(), "create_time", value); + return this; + } + + updateUpdateTime(value: string): this { + this.updateTime = value; + this.markLoaded("updateTime"); + (this as any)._root.set(this.teaqlEntityKey(), "update_time", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + private teaqlSetTenant(value: any): this { + this.tenant = value?.id ?? value; + this.markLoaded("tenant"); + (this as any)._root.set(this.teaqlEntityKey(), "tenant", this.tenant); + return this; + } + + orderItemList(): SmartList { + return (this as any)._orderItemList; + } +} \ No newline at end of file diff --git a/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/Tenant.ts b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/Tenant.ts new file mode 100644 index 0000000000000000000000000000000000000000..26b766314cfd2b294446e1e020cf35c8124504a3 --- /dev/null +++ b/source/teaql-ts/examples/fix-e-alignment/generated/src/generated/models/Tenant.ts @@ -0,0 +1,494 @@ +import { CheckException, integer32Error, EntityCreation, EntityCreationError, Decimal, decimal, Long, long, LocalTime, localTime, EntityVersion, entityVersion, nextEntityVersion, EntityKey, EntityRoot, GraphMutationSession, LoadedScalarSnapshot, MutationFieldLayout, MutationIntent, MutationTraceScope, ObjectLocation, SmartList, TeaQLDataService, UserContext } from '../../teaql-ts'; +import { PurchaseOrder } from './PurchaseOrder'; +import { OrderItem } from './OrderItem'; + +const teaqlConstruction = Symbol("managed entity construction"); + +export class Tenant { + private static teaqlTemporaryId = 0; + private static readonly teaqlMutationFields = new MutationFieldLayout("Tenant", + ["id", "name", "version"], { id: "immutable_field", version: "immutable_field" }); + id?: string; + name?: string; + version?: EntityVersion; + + private constructor(init?: Partial, token?: symbol, creation = false) { + if (token !== teaqlConstruction) throw new EntityCreationError(); + Object.defineProperty(this, "_action", { value: creation ? "Create" : "Update", writable: true, enumerable: false }); + Object.defineProperty(this, "_comment", { value: undefined, writable: true, enumerable: false }); + Object.defineProperty(this, "_fullyLoaded", { value: creation, writable: true, enumerable: false }); + Object.defineProperty(this, "_loadedFields", { value: new Set(Object.keys(init || {})), writable: true, enumerable: false }); + Object.defineProperty(this, "_root", { value: new EntityRoot(), writable: true, enumerable: false }); + Object.defineProperty(this, "_ledgerId", { value: init?.id ?? --Tenant.teaqlTemporaryId, writable: true, enumerable: false }); + Object.defineProperty(this, "_purchaseOrderList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + Object.defineProperty(this, "_orderItemList", { value: creation ? new SmartList() : SmartList.empty(), writable: true, enumerable: false }); + if (init) { + const fields: Record = { ...(init as Record) }; + for (const key of ["_action", "_comment", "_fullyLoaded", "_loadedFields", "_root", "_ledgerId"]) delete fields[key]; + delete fields["purchaseOrderList"]; + delete fields["orderItemList"]; + Object.assign(this, fields); + if (Array.isArray((init as any).purchaseOrderList)) { + const selected = (init as any).purchaseOrderList; + (this as any)._purchaseOrderList = new SmartList(selected.map( + (child: unknown) => child instanceof PurchaseOrder + ? child + : PurchaseOrder.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("purchaseOrderList"); + } + if (Array.isArray((init as any).orderItemList)) { + const selected = (init as any).orderItemList; + (this as any)._orderItemList = new SmartList(selected.map( + (child: unknown) => child instanceof OrderItem + ? child + : OrderItem.fromRecord(child as Record), + ), { totalCount: selected.totalCount, aggregations: selected.aggregations, + summary: selected.summary, facets: selected.facets, isLoaded: selected.isLoaded ?? true }); + this.markLoaded("orderItemList"); + } + } + const key = this.teaqlEntityKey(); + if ((this as any).version !== undefined) (this as any).version = entityVersion((this as any).version); + if ((this as any)._action === "Create") (this as any)._root.markAsNew(key); + else if ((this as any).version !== undefined) (this as any)._root.setOriginalVersion(key, (this as any).version); + LoadedScalarSnapshot.captureFor(this, this.teaqlMutationPayload(), key, (this as any).version, + creation ? "creationBaseline" : "hydrated"); + } + + private teaqlEntityKey(): EntityKey { return { entity: "Tenant", id: (this as any)._ledgerId }; } + private teaqlAttachRoot(root: EntityRoot, hydration = false): this { + if ((this as any)._root !== root) { + root.mergeEntityFrom((this as any)._root, this.teaqlEntityKey()); + (this as any)._root = root; + } + for (const child of (this as any)._purchaseOrderList) child.teaqlAttachRoot(root, hydration); + for (const child of (this as any)._orderItemList) child.teaqlAttachRoot(root, hydration); + return this; + } + + static fromRecord(record: Record, root?: EntityRoot): Tenant { + const entity = EntityCreation.hydrated(new Tenant(record as Partial, teaqlConstruction)); + return root ? entity.teaqlAttachRoot(root, true) : entity; + } + + toJSON(): Record { + const result = Object.fromEntries(Object.entries(this)); + if (this.isLoaded("purchaseOrderList")) result["purchaseOrderList"] = (this as any)._purchaseOrderList; + if (this.isLoaded("orderItemList")) result["orderItemList"] = (this as any)._orderItemList; + return result; + } + + isLoaded(field: string): boolean { + return (this as any)._fullyLoaded || (this as any)._loadedFields.has(field); + } + + markLoaded(...fields: string[]): this { + for (const field of fields) (this as any)._loadedFields.add(field); + return this; + } + + markLoadedOnly(...fields: string[]): this { + (this as any)._fullyLoaded = false; + (this as any)._loadedFields = new Set(fields); + return this; + } + + static refer(id: string | number): Tenant { + return Tenant.fromRecord({ id: String(id) }); + } + + /** @internal Generated Runtime Module fixed-ID construction capability. */ + static teaqlBootstrapNew(context: UserContext, id: string | number): Tenant { + return EntityCreation.bootstrap(context, "Tenant", id, + reserved => new Tenant({id: reserved} as Partial, teaqlConstruction, true)); + } + + /** @internal Q owns the awaited public creation entry point. */ + static teaqlCreate(context: UserContext): Promise { + return EntityCreation.create(context, "Tenant", + reserved => new Tenant({id: reserved} as Partial, teaqlConstruction, true)); + } + + markForDeletion(): this { + (this as any)._action = "Delete"; + (this as any)._root.markAsDeleted(this.teaqlEntityKey()); + return this; + } + + auditAs(comment: string): this { + (this as any)._comment = new MutationIntent(comment).comment; + return this; + } + + async save(context: UserContext): Promise { + const intent = new MutationIntent((this as any)._comment); + this.teaqlValidateLoadedIdentities(); + if (!this.teaqlValidateMutationOrigins()) return this; + const service = context.requireResource("dataService"); + return service.executeGraphSave(new MutationIntent((this as any)._comment), async (graph) => { + return this.teaqlSaveWithinGraph(context, service, graph); + }, (graph) => { + this.teaqlPreflightGraph(context, service, graph); + this.teaqlValidateLoadedIdentities(); + this.teaqlAdmitGraph(); + graph.sealPreparedGraph(); + }, (graph) => { + this.teaqlValidateLoadedIdentities(); + this.teaqlDiscardRestoredGraph(graph); + this.teaqlAdmitGraph(); + this.teaqlNormalizeGraph(graph); + return this.teaqlAdmitGraph(); + }); + } + + /** @internal Pure provenance pass before resolving any Context resources. */ + private teaqlValidateMutationOrigins(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + let pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + for (const child of (this as any)._purchaseOrderList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + for (const child of (this as any)._orderItemList) pending = child.teaqlValidateMutationOrigins(seen) || pending; + return pending; + } + + /** @internal Read-only first pass: no ledger attachment, FK edits or no-op shortcut. */ + private teaqlValidateLoadedIdentities(seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + LoadedScalarSnapshot.forEntity(this)?.validateNativeIdentity(this.teaqlEntityKey(), this.id, this.version); + for (const [index, child] of (this as any)._purchaseOrderList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("purchase_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { child.teaqlValidateLoadedIdentities(seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + } + + /** @internal Cancel known no-ops across the graph before any derived FK edits. */ + private teaqlDiscardRestoredGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Tenant.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + for (const child of (this as any)._purchaseOrderList) child.teaqlDiscardRestoredGraph(graph, seen); + for (const child of (this as any)._orderItemList) child.teaqlDiscardRestoredGraph(graph, seen); + } + + /** @internal Model-key admission precedes restoration; only intended edits may normalize FKs. */ + private teaqlNormalizeGraph(graph: GraphMutationSession, seen = new Set()): void { + if (seen.has(this)) return; + seen.add(this); + graph.discardRestoredFields(Tenant.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + graph.registerSource(this, (this as any)._root, this.teaqlEntityKey(), { + }, () => ({ ...this.teaqlMutationPayload(), + __teaql_key: this.teaqlEntityKey(), __teaql_action: (this as any)._action, + __teaql_comment: (this as any)._comment, + __teaql_load: {fullyLoaded: (this as any)._fullyLoaded, fields: [...(this as any)._loadedFields].sort()}, + "purchase_order_list": graph.sourceMembers((this as any)._purchaseOrderList), + "order_item_list": graph.sourceMembers((this as any)._orderItemList) + })); + for (const child of (this as any)._purchaseOrderList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + child.teaqlNormalizeGraph(graph, seen); + } + for (const child of (this as any)._orderItemList) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + child.teaqlNormalizeGraph(graph, seen); + } + } + + /** @internal Whole-input version/completeness pass; does not use Context or Fix. */ + private teaqlAdmitGraph(seen = new Set()): boolean { + if (seen.has(this)) return false; + seen.add(this); + const action = (this as any)._action; + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + EntityCreation.requireMutation(this, this.teaqlEntityKey(), this.id, action, (this as any)._root, pending); + LoadedScalarSnapshot.forEntity(this)?.validateMutationVersion((this as any)._root, this.teaqlEntityKey()); + Tenant.teaqlMutationFields.validate((this as any)._root.change(this.teaqlEntityKey()), action === "Update"); + if (pending) { + nextEntityVersion(action, LoadedScalarSnapshot.forEntity(this)?.persistedVersion); + if (action === "Update") { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }].find(field => !this.isLoaded(field.member)); + if (notLoaded) throw new CheckException([{ruleId: "invalid_type", entityType: "Tenant", location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity"}]); + } + } + let graphPending = pending; + for (const [index, child] of (this as any)._purchaseOrderList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("purchase_order_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + for (const [index, child] of (this as any)._orderItemList.entries()) { + try { graphPending = child.teaqlAdmitGraph(seen) || graphPending; } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(error.violations.map(violation => ({ ...violation, location: violation.location.prefixedBy(prefix) }))); + } + } + return graphPending; + } + + /** @internal Validates and fixes the complete graph before its first mutation. */ + teaqlPreflightGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): void { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return; + seen.add(this); + const action = (this as any)._action; + graph.discardRestoredFields(Tenant.teaqlMutationFields, + (this as any)._root, this.teaqlEntityKey(), LoadedScalarSnapshot.forEntity(this)); + const pending = action !== "Update" || (this as any)._root.hasPending(this.teaqlEntityKey()); + if (action === "Update" && pending) { + const notLoaded = [{ member: "id", canonical: "id" }, { member: "name", canonical: "name" }, { member: "version", canonical: "version" }] + .find(field => !this.isLoaded(field.member)); + if (notLoaded) { + throw new CheckException([{ + ruleId: "invalid_type", + entityType: "Tenant", + location: ObjectLocation.property(notLoaded.canonical), + message: "Mutation requires a fully loaded entity", + }]); + } + } + const request = graph.request({ + entity: "Tenant", action, + payload: action === "Update" + ? (this as any)._root.change(this.teaqlEntityKey()) + : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment, + ledgerKey: this.teaqlEntityKey(), ledgerRoot: (this as any)._root, + }, parent, (this as any)._comment).withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (pending) service.preflightMutation(request); + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._purchaseOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("purchase_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + try { child.teaqlPreflightGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + } + + /** @internal Used by generated relation cascades inside the root graph transaction. */ + async teaqlSaveWithinGraph(context: UserContext, service: TeaQLDataService, graph: GraphMutationSession, parent?: MutationTraceScope, seen = new Set()): Promise { + if (!parent) new MutationIntent((this as any)._comment); + if (seen.has(this)) return this; + seen.add(this); + const action = (this as any)._action; + const ledgerPayload = (this as any)._root.change(this.teaqlEntityKey()); + const mutation = { + entity: "Tenant", + action: (this as any)._action, + payload: action === "Update" ? ledgerPayload : this.teaqlMutationPayload(), + id: (this as any).id, + version: LoadedScalarSnapshot.forEntity(this)?.persistedVersion, + comment: (this as any)._comment + ,ledgerKey: this.teaqlEntityKey() + ,ledgerRoot: (this as any)._root + }; + const request = graph.request(mutation, parent, (this as any)._comment) + .withLoadedSnapshot(LoadedScalarSnapshot.forEntity(this) ?? new LoadedScalarSnapshot()); + if (action === "Update" && !(this as any)._root.hasPending(this.teaqlEntityKey())) { + const scope = request.scopeFor(this.teaqlEntityKey()); + for (const [index, child] of (this as any)._purchaseOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("purchase_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + return this; + } + const result = await service.executeMutation(request); + graph.validatePreparedSources(); + if (!result.persistedRecord) { + throw new Error("Mutation did not return the authoritative persisted record"); + } + const rollbackState = { + ownProperties: Object.getOwnPropertyDescriptors(this), + ledgerId: (this as any)._ledgerId, + action: (this as any)._action, + loadedFields: new Set((this as any)._loadedFields), + fullyLoaded: (this as any)._fullyLoaded, + loadedSnapshot: LoadedScalarSnapshot.forEntity(this), + }; + const oldKey = this.teaqlEntityKey(); + Object.assign(this, result.persistedRecord); + (this as any)._ledgerId = (this as any).id ?? (this as any)._ledgerId; + const newKey = this.teaqlEntityKey(); + (this as any)._root.rekey(oldKey, newKey); + const committedSnapshot = this.teaqlScalarSnapshot(); + const activeScope = request.scopeFor(newKey); + service.afterGraphRollback(() => { + for (const name of Object.getOwnPropertyNames(this)) { + if (!Object.prototype.hasOwnProperty.call(rollbackState.ownProperties, name)) delete (this as any)[name]; + } + Object.defineProperties(this, rollbackState.ownProperties); + (this as any)._ledgerId = rollbackState.ledgerId; + (this as any)._action = rollbackState.action; + (this as any)._loadedFields = rollbackState.loadedFields; + (this as any)._fullyLoaded = rollbackState.fullyLoaded; + LoadedScalarSnapshot.restoreFor(this, rollbackState.loadedSnapshot); + (this as any)._root.rekey(newKey, oldKey); + }); + (this as any)._loadedFields = new Set(Object.keys(result.persistedRecord)); + (this as any)._fullyLoaded = false; + if (mutation.action !== "Delete") (this as any)._action = "Update"; + graph.acceptPreparedResult((this as any)._root, oldKey, newKey); + const scope = request.scopeFor(newKey); + for (const [index, child] of (this as any)._purchaseOrderList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("purchase_order_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + for (const [index, child] of (this as any)._orderItemList.entries()) { + child.teaqlAttachRoot((this as any)._root); + const currentParent = child.tenant; + if (((child as any)._action !== "Update" || (child as any)._root.hasPending(child.teaqlEntityKey())) + && (this.id === undefined || !child.isLoaded("tenant") || (typeof currentParent === "object" && currentParent !== null + ? currentParent.id : currentParent) !== this.id)) child.teaqlSetTenant(this); + try { await child.teaqlSaveWithinGraph(context, service, graph, scope, seen); } + catch (error) { + if (!(error instanceof CheckException)) throw error; + const prefix = ObjectLocation.property("order_item_list").index(index); + throw new CheckException(context.translateCheckResults(error.violations.map(violation => ({ + ...violation, location: violation.location.prefixedBy(prefix), + })))); + } + } + service.afterGraphCommit(() => { + graph.validatePreparedSources(); + LoadedScalarSnapshot.restoreFor(this, committedSnapshot); + (this as any)._root.clearEntity(newKey); + if ((this as any).version !== undefined) (this as any)._root.acceptCommittedVersion(newKey, (this as any).version); + graph.finishPreparedCommit((this as any)._root, newKey); + }); + return this; + } + + private teaqlMutationPayload(): Record { + return { + "id": this.id, + "name": this.name, + "version": this.version + }; + } + + private teaqlScalarSnapshot(): LoadedScalarSnapshot { + return new LoadedScalarSnapshot(this.teaqlMutationPayload(), this.teaqlEntityKey(), (this as any).version); + } + + updateId(value: string): this { + this.id = value; + this.markLoaded("id"); + (this as any)._root.set(this.teaqlEntityKey(), "id", value); + return this; + } + + updateName(value: string): this { + this.name = value; + this.markLoaded("name"); + (this as any)._root.set(this.teaqlEntityKey(), "name", value); + return this; + } + + updateVersion(value: EntityVersion): this { + this.version = value; + this.markLoaded("version"); + (this as any)._root.set(this.teaqlEntityKey(), "version", value); + return this; + } + purchaseOrderList(): SmartList { + return (this as any)._purchaseOrderList; + } + + orderItemList(): SmartList { + return (this as any)._orderItemList; + } +} \ No newline at end of file