@api-now/cli 1.17.0 → 1.17.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +86 -53
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var hp=Object.create;var Gn=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var gp=Object.getOwnPropertyNames;var yp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var kp=(c,e)=>()=>{try{return e||c((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ll=(c,e)=>{for(var t in e)Gn(c,t,{get:e[t],enumerable:!0})},vp=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gp(e))!bp.call(c,r)&&r!==t&&Gn(c,r,{get:()=>e[r],enumerable:!(i=fp(e,r))||i.enumerable});return c};var wp=(c,e,t)=>(t=c!=null?hp(yp(c)):{},vp(e||!c||!c.__esModule?Gn(t,"default",{value:c,enumerable:!0}):t,c));var Ad=kp((xE,Sd)=>{var Dc=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,Am=Object.getOwnPropertyNames,Em=Object.prototype.hasOwnProperty,_m=(c,e)=>{for(var t in e)Dc(c,t,{get:e[t],enumerable:!0})},xm=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Am(e))!Em.call(c,r)&&r!==t&&Dc(c,r,{get:()=>e[r],enumerable:!(i=Sm(e,r))||i.enumerable});return c},Im=c=>xm(Dc({},"__esModule",{value:!0}),c),bd={};_m(bd,{AmfModelExpander:()=>$m,JsonLd:()=>yi,JsonLdOptions:()=>vd});Sd.exports=Im(bd);var Pm=class kd{validate(e){if(e===void 0)throw new Error("Node must not be undefined");if(Array.isArray(e))throw new Error("Node must not be an array");if(e["@id"]===void 0)throw new Error("Node must have an @id")}static empty(){return new kd}withNode(e){this.validate(e);let t=e["@id"];if(this[t]!==void 0)throw new Error(`Cannot add node with duplicate id ${e["@id"]} to dictionary`);return this[t]=e,this}withNodes(e){return e.forEach(t=>this.withNode(t)),this}},Vo=class{static targetOrLink(c,e){let t=e[c["@id"]];return t!==void 0?t:c}static isLinkObject(c){let e=typeof c=="object",t=!Array.isArray(c),i=c["@id"]!==void 0,r=Object.keys(c).length===1;return e&&t&&i&&r}static isArrayOfLinks(c){return c.every(e=>this.isLinkObject(e))}},Rm=class{static embedNodeLinks(c,e,t){let r=t||(()=>!0);return Object.entries(c).filter(([s,o])=>r(s,o)).forEach(([s,o])=>{typeof o=="object"&&(Vo.isLinkObject(o)?c[s]=Vo.targetOrLink(o,e):Array.isArray(o)&&Vo.isArrayOfLinks(o)&&(c[s]=o.map(a=>Vo.targetOrLink(a,e))))}),c}},gd=class Cc{static expandIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.expandIri(i,t);e[s]=r})}static compactIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.compactIri(i,t);e[s]=r})}static compactIri(e,t){switch(typeof t){case"string":return e.replace(t,"");case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))return e;try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(o));return e.replace(r,`${i}:`)}catch{return e}default:throw new Error("Context must be either an object or a string")}}static expandIri(e,t){switch(typeof t){case"string":return`${t}${e}`;case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(s));return e.replace(`${i}:`,r)}catch{return e}else return e;default:throw new Error("Context must be either an object or a string")}}static isCompacted(e,t){let i=!0;return Object.values(t).forEach(r=>{e.startsWith(r)&&(i=!1)}),i}},yd=class{static expandStructure(c){return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.expandType(c,t);break;default:this.expandValue(c,e,t);break}}),c}static expandType(c,e){typeof e=="string"?c["@type"]=[e]:c["@type"]=e}static expandValue(c,e,t){switch(typeof t){case"string":case"number":case"boolean":c[e]=[{"@value":t}];break;case"object":Array.isArray(t)?t.map(r=>{switch(typeof r){case"string":case"number":case"boolean":return[{"@value":t}];default:return r}}):c[e]=[t]}}static compactStructure(c){if(Array.isArray(c)){let[e]=c;return this.compactStructure(e)}else return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.compactType(c,t);break;default:this.compactValue(c,e,t);break}}),c}static compactType(c,e){Array.isArray(e)&&e.length===1&&(c["@type"]=e[0])}static compactValue(c,e,t){if(t.length===1){let[i]=t;this.isWrappedScalar(i)?c[e]=i["@value"]:c[e]=i}else t.map(i=>this.isWrappedScalar(i)?i["@value"]:i)}static isWrappedScalar(c){return c["@value"]!==void 0}},yi=class{static process(c,e){let t=this.getGraph(c),i=this.getContext(c),r=Pm.empty().withNodes(t);t.forEach(o=>{e.embeddedLinks&&Rm.embedNodeLinks(o,r,e.linkEmbeddingFilter),i!==void 0&&(e.expandedIris?gd.expandIris(o,i):e.compactedIris&&gd.compactIris(o,i)),e.expandedStructure?yd.expandStructure(o):e.compactedStructure&&yd.compactStructure(o)});let s=e.rootNodeId===void 0?{"@graph":t}:this.findNode(t,e.rootNodeId);return i!==void 0&&(s["@context"]=i),e.expandedStructure?[s]:s}static getContext(c){return c["@context"]}static getGraph(c){return c["@graph"]}static findNode(c,e){return c.find(t=>t["@id"]===e)}static stringify(c,e=!1){return JSON.stringify(c,null,e?2:0)}},vd=class wd{expandedIris;expandedStructure;embeddedLinks;compactedIris;compactedStructure;rootNodeId;linkEmbeddingFilter;static apply(){return new wd}withCompactedStructure(){return this.expandedStructure=!1,this.compactedStructure=!0,this}withRootNode(e){return this.rootNodeId=e,this}withExpandedStructure(){return this.expandedStructure=!0,this.compactedStructure=!1,this}withExpandedIris(){return this.expandedIris=!0,this.compactedIris=!1,this}withCompactedIris(){return this.expandedIris=!1,this.compactedIris=!0,this}withEmbeddedLinks(e){return this.linkEmbeddingFilter=e,this.embeddedLinks=!0,this}},$m=class{static expand(c){if(this.isInExpandedForm(c))return c;{let e=(r,s)=>!r.endsWith("fixPoint");this.preprocessLegacyRootNodeId(c);let t=this.resolveRootNodeId(c),i=vd.apply().withEmbeddedLinks(e).withCompactedIris().withExpandedStructure().withRootNode(t);return yi.process(c,i)}}static isInExpandedForm(c){return c["@graph"]===void 0}static preprocessLegacyRootNodeId(c){let e=yi.getGraph(c);if(e!=null){let t=yi.findNode(e,"./");t!=null&&(t["@id"]="")}}static resolveRootNodeId(c){let e=yi.getGraph(c);if(e==null||yi.findNode(e,"")!=null)return"";let t=yi.getContext(c);if(t!=null&&t["@base"]!=null){let r=t["@base"];if(yi.findNode(e,r)!=null)return r}let i=e.find(r=>Object.entries(r).some(([s,o])=>(s==="doc:root"||s==="http://a.ml/vocabularies/document#root")&&o===!0));return i!=null?i["@id"]:""}}});import ch from"update-notifier";import{Command as lh}from"commander";var kt={name:"@api-now/cli",description:"API Now! CLI",version:"1.17.0",private:!1,publishConfig:{registry:"https://registry.npmjs.org/","@api-now:registry":"https://registry.npmjs.org/",access:"public"},files:["dist"],engines:{node:">=22.0.0"},type:"module",bin:{apinow:"dist/index.js"},scripts:{build:"node esbuild.config.js",postbuild:"node dist/index.js --help",dev:"tsx src/index.ts",typecheck:"tsc --noEmit",lint:'eslint "src/**/*.ts"',format:'prettier --write "src/**/*.ts"',test:"tsx --test tests/**/*.test.ts",prepare:"husky",prepublishOnly:"npm run build",knip:"knip"},dependencies:{"@inquirer/prompts":"^8.5.0",commander:"^15.0.0",dompurify:"^3.4.11",jsdom:"^30.0.1",nanoid:"^6.0.1",open:"^11.0.0",tslib:"^2.8.1","update-notifier":"^7.3.1",winston:"^3.19.0"},devDependencies:{"@api-now/core":"^1.55.1","@api-now/json":"^1.0.0","@commitlint/cli":"^21.0.1","@commitlint/config-conventional":"^21.0.1","@eslint/js":"^10.0.1","@semantic-release/changelog":"^7.0.0","@semantic-release/git":"^11.0.1","@types/node":"^26.2.0","@types/update-notifier":"^6.0.8",esbuild:"^0.28.0",eslint:"^10.4.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.6",globals:"^17.6.0",husky:"^9.1.7",knip:"^6.14.2",prettier:"^3.8.3","semantic-release":"^25.0.3",tsx:"^4.7.1",typescript:"^6.0.3","typescript-eslint":"^8.60.0"}};import Jn from"node:os";import Jt from"node:path";import Be from"node:fs";var _r="https://api.apinow.app",Wn="apinow-cli",Ap="config.json",Hn=class{_resolved=null;get resolved(){this._resolved||this.load();let e=this._resolved;if(!e)throw new Error("Configuration could not be loaded.");return e}configDir=this.#t();configPath=Jt.join(this.configDir,Ap);#e(e,t){if(!e.profiles&&(e.token||e.org||e.apiUrl)){let i={profiles:{default:{token:e.token||"",org:e.org,apiUrl:e.apiUrl||_r}},activeProfile:"default"};return t&&this.#o(i),i}return e}load(){let t=this.#r()??this.#s(),i=t.activeProfile,r=i&&t.profiles?t.profiles[i]:void 0,s=process.env.APINOW_API_TOKEN||process.env.APINOW_TOKEN||r?.token,o=process.env.APINOW_API_URL||r?.apiUrl||_r,a=r?.org||"";this._resolved={token:s,apiUrl:o,org:a,activeProfile:i,format:"text"}}saturate(e){this._resolved||this.load();let t=this._resolved;if(!t)throw new Error("Configuration could not be loaded.");this._resolved={token:t.token,apiUrl:t.apiUrl,org:t.org,activeProfile:t.activeProfile,format:e.format==="json"?"json":"text"}}listProfiles(){let e=this.#s();return e.profiles?{...e.profiles}:{}}getActiveProfile(){return this.#s().activeProfile}setActiveProfile(e){let t=this.#s();t.activeProfile=e,this.#o(t),this.load()}upsertProfile(e,t){let i=this.#s(),r=i.profiles?{...i.profiles}:{},s=r[e]||{token:""};r[e]={token:t.token!==void 0?t.token:s.token,org:t.org!==void 0?t.org:s.org,apiUrl:t.apiUrl!==void 0?t.apiUrl:s.apiUrl||_r},i.profiles=r,this.#o(i),this.load()}deleteProfile(e){let t=this.#s();if(t.profiles&&e in t.profiles){let i={...t.profiles};delete i[e],t.profiles=i,t.activeProfile===e&&delete t.activeProfile,this.#o(t),this.load()}}writeTokenToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,token:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}writeOrgToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,org:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}#t(){if(process.platform==="win32"){let e=process.env.APPDATA||Jt.join(Jn.homedir(),"AppData","Roaming");if(!e)throw new Error("Could not determine the configuration directory.");return Jt.join(e,Wn)}return process.platform==="darwin"?Jt.join(Jn.homedir(),"Library","Preferences",Wn):Jt.join(process.env.XDG_CONFIG_HOME||Jt.join(Jn.homedir(),".config"),Wn)}#i(){let e=process.cwd();for(;;){let t=Jt.join(e,"apinow.json");if(Be.existsSync(t))try{if(Be.statSync(t).isFile())return t}catch{}let i=Jt.join(e,".apinowrc.json");if(Be.existsSync(i))try{if(Be.statSync(i).isFile())return i}catch{}let r=Jt.dirname(e);if(r===e)break;e=r}return null}#r(){let e=this.#i();if(!e)return null;try{let t=Be.readFileSync(e,"utf8"),i=JSON.parse(t);return this.#e(i,!1)}catch{return null}}#s(){try{if(!Be.existsSync(this.configPath))return{};let e=Be.readFileSync(this.configPath,"utf8"),t=JSON.parse(e);return this.#e(t,!0)}catch{return{}}}writeProperty(e,t){let i=this.#s();e==="activeProfile"&&(i.activeProfile=t),this.#o(i),this.load()}#o(e){try{Be.existsSync(this.configDir)||Be.mkdirSync(this.configDir,{recursive:!0}),Be.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf8")}catch(t){console.error("Failed to write configuration:",t)}}clearConfigKey(e){try{let t=this.#s();delete t[e],this.#o(t),this.load()}catch(t){console.error(`Failed to clear key ${e} from configuration:`,t)}}reset(){try{Be.existsSync(this.configPath)&&Be.unlinkSync(this.configPath),Be.existsSync(this.configDir)&&Be.readdirSync(this.configDir).length===0&&Be.rmdirSync(this.configDir),this._resolved=null}catch(e){console.error("Failed to reset configuration:",e)}}},N=new Hn;import{styleText as Wi}from"node:util";import Ep from"node:path";import _p from"node:os";import xp from"node:crypto";import vt from"winston";var Ip=xp.randomBytes(4).toString("hex"),Pp=Date.now(),Ds=Ep.join(_p.tmpdir(),`apinow-cli-${Pp}-${Ip}.log`),dl=new vt.transports.Console({stderrLevels:Object.keys(vt.config.cli.levels),level:"info",format:vt.format.combine(vt.format.colorize(),vt.format.simple())}),Rp=new vt.transports.File({filename:Ds,level:"debug",format:vt.format.combine(vt.format.timestamp(),vt.format.printf(({timestamp:c,level:e,message:t})=>{let i=typeof t=="string"?t.replace(/\u001b\[\d+m/g,""):t;return`${c} [${e.toUpperCase()}]: ${i}`}))}),y=vt.createLogger({levels:vt.config.cli.levels,level:"debug",transports:[dl,Rp]});function pl(c){dl.level=c}var Yn=kt.version;var ie={green:c=>Wi("green",c),red:c=>Wi("red",c),yellow:c=>Wi("yellow",c),cyan:c=>Wi("cyan",c),dim:c=>Wi("dim",c),bold:c=>Wi("bold",c)};function $p(c,e,t){if(c.length===0)return"No data available.";let i={},r=t||e;for(let n=0;n<e.length;n++){let l=e[n],d=r[n]||l;i[l]=d.length}for(let n of c)for(let l of e){let d=typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"");d.length>(i[l]||0)&&(i[l]=d.length)}let s=e.map((n,l)=>(r[l]||n).toUpperCase().padEnd(i[n])).join(" "),o=e.map(n=>"-".repeat(i[n])).join(" "),a=c.map(n=>e.map(l=>(typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"")).padEnd(i[l])).join(" "));return[s,o,...a].join(`
|
|
2
|
+
var hp=Object.create;var Gn=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var gp=Object.getOwnPropertyNames;var yp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var kp=(c,e)=>()=>{try{return e||c((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ll=(c,e)=>{for(var t in e)Gn(c,t,{get:e[t],enumerable:!0})},vp=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gp(e))!bp.call(c,r)&&r!==t&&Gn(c,r,{get:()=>e[r],enumerable:!(i=fp(e,r))||i.enumerable});return c};var wp=(c,e,t)=>(t=c!=null?hp(yp(c)):{},vp(e||!c||!c.__esModule?Gn(t,"default",{value:c,enumerable:!0}):t,c));var Ad=kp((xE,Sd)=>{var Dc=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,Am=Object.getOwnPropertyNames,Em=Object.prototype.hasOwnProperty,_m=(c,e)=>{for(var t in e)Dc(c,t,{get:e[t],enumerable:!0})},xm=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Am(e))!Em.call(c,r)&&r!==t&&Dc(c,r,{get:()=>e[r],enumerable:!(i=Sm(e,r))||i.enumerable});return c},Im=c=>xm(Dc({},"__esModule",{value:!0}),c),bd={};_m(bd,{AmfModelExpander:()=>$m,JsonLd:()=>yi,JsonLdOptions:()=>vd});Sd.exports=Im(bd);var Pm=class kd{validate(e){if(e===void 0)throw new Error("Node must not be undefined");if(Array.isArray(e))throw new Error("Node must not be an array");if(e["@id"]===void 0)throw new Error("Node must have an @id")}static empty(){return new kd}withNode(e){this.validate(e);let t=e["@id"];if(this[t]!==void 0)throw new Error(`Cannot add node with duplicate id ${e["@id"]} to dictionary`);return this[t]=e,this}withNodes(e){return e.forEach(t=>this.withNode(t)),this}},Vo=class{static targetOrLink(c,e){let t=e[c["@id"]];return t!==void 0?t:c}static isLinkObject(c){let e=typeof c=="object",t=!Array.isArray(c),i=c["@id"]!==void 0,r=Object.keys(c).length===1;return e&&t&&i&&r}static isArrayOfLinks(c){return c.every(e=>this.isLinkObject(e))}},Rm=class{static embedNodeLinks(c,e,t){let r=t||(()=>!0);return Object.entries(c).filter(([s,o])=>r(s,o)).forEach(([s,o])=>{typeof o=="object"&&(Vo.isLinkObject(o)?c[s]=Vo.targetOrLink(o,e):Array.isArray(o)&&Vo.isArrayOfLinks(o)&&(c[s]=o.map(a=>Vo.targetOrLink(a,e))))}),c}},gd=class Cc{static expandIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.expandIri(i,t);e[s]=r})}static compactIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.compactIri(i,t);e[s]=r})}static compactIri(e,t){switch(typeof t){case"string":return e.replace(t,"");case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))return e;try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(o));return e.replace(r,`${i}:`)}catch{return e}default:throw new Error("Context must be either an object or a string")}}static expandIri(e,t){switch(typeof t){case"string":return`${t}${e}`;case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(s));return e.replace(`${i}:`,r)}catch{return e}else return e;default:throw new Error("Context must be either an object or a string")}}static isCompacted(e,t){let i=!0;return Object.values(t).forEach(r=>{e.startsWith(r)&&(i=!1)}),i}},yd=class{static expandStructure(c){return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.expandType(c,t);break;default:this.expandValue(c,e,t);break}}),c}static expandType(c,e){typeof e=="string"?c["@type"]=[e]:c["@type"]=e}static expandValue(c,e,t){switch(typeof t){case"string":case"number":case"boolean":c[e]=[{"@value":t}];break;case"object":Array.isArray(t)?t.map(r=>{switch(typeof r){case"string":case"number":case"boolean":return[{"@value":t}];default:return r}}):c[e]=[t]}}static compactStructure(c){if(Array.isArray(c)){let[e]=c;return this.compactStructure(e)}else return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.compactType(c,t);break;default:this.compactValue(c,e,t);break}}),c}static compactType(c,e){Array.isArray(e)&&e.length===1&&(c["@type"]=e[0])}static compactValue(c,e,t){if(t.length===1){let[i]=t;this.isWrappedScalar(i)?c[e]=i["@value"]:c[e]=i}else t.map(i=>this.isWrappedScalar(i)?i["@value"]:i)}static isWrappedScalar(c){return c["@value"]!==void 0}},yi=class{static process(c,e){let t=this.getGraph(c),i=this.getContext(c),r=Pm.empty().withNodes(t);t.forEach(o=>{e.embeddedLinks&&Rm.embedNodeLinks(o,r,e.linkEmbeddingFilter),i!==void 0&&(e.expandedIris?gd.expandIris(o,i):e.compactedIris&&gd.compactIris(o,i)),e.expandedStructure?yd.expandStructure(o):e.compactedStructure&&yd.compactStructure(o)});let s=e.rootNodeId===void 0?{"@graph":t}:this.findNode(t,e.rootNodeId);return i!==void 0&&(s["@context"]=i),e.expandedStructure?[s]:s}static getContext(c){return c["@context"]}static getGraph(c){return c["@graph"]}static findNode(c,e){return c.find(t=>t["@id"]===e)}static stringify(c,e=!1){return JSON.stringify(c,null,e?2:0)}},vd=class wd{expandedIris;expandedStructure;embeddedLinks;compactedIris;compactedStructure;rootNodeId;linkEmbeddingFilter;static apply(){return new wd}withCompactedStructure(){return this.expandedStructure=!1,this.compactedStructure=!0,this}withRootNode(e){return this.rootNodeId=e,this}withExpandedStructure(){return this.expandedStructure=!0,this.compactedStructure=!1,this}withExpandedIris(){return this.expandedIris=!0,this.compactedIris=!1,this}withCompactedIris(){return this.expandedIris=!1,this.compactedIris=!0,this}withEmbeddedLinks(e){return this.linkEmbeddingFilter=e,this.embeddedLinks=!0,this}},$m=class{static expand(c){if(this.isInExpandedForm(c))return c;{let e=(r,s)=>!r.endsWith("fixPoint");this.preprocessLegacyRootNodeId(c);let t=this.resolveRootNodeId(c),i=vd.apply().withEmbeddedLinks(e).withCompactedIris().withExpandedStructure().withRootNode(t);return yi.process(c,i)}}static isInExpandedForm(c){return c["@graph"]===void 0}static preprocessLegacyRootNodeId(c){let e=yi.getGraph(c);if(e!=null){let t=yi.findNode(e,"./");t!=null&&(t["@id"]="")}}static resolveRootNodeId(c){let e=yi.getGraph(c);if(e==null||yi.findNode(e,"")!=null)return"";let t=yi.getContext(c);if(t!=null&&t["@base"]!=null){let r=t["@base"];if(yi.findNode(e,r)!=null)return r}let i=e.find(r=>Object.entries(r).some(([s,o])=>(s==="doc:root"||s==="http://a.ml/vocabularies/document#root")&&o===!0));return i!=null?i["@id"]:""}}});import ch from"update-notifier";import{Command as lh}from"commander";var kt={name:"@api-now/cli",description:"API Now! CLI",version:"1.17.1",private:!1,publishConfig:{registry:"https://registry.npmjs.org/","@api-now:registry":"https://registry.npmjs.org/",access:"public"},files:["dist"],engines:{node:">=22.0.0"},type:"module",bin:{apinow:"dist/index.js"},scripts:{build:"node esbuild.config.js",postbuild:"node dist/index.js --help",dev:"tsx src/index.ts",typecheck:"tsc --noEmit",lint:'eslint "src/**/*.ts"',format:'prettier --write "src/**/*.ts"',test:"tsx --test tests/**/*.test.ts",prepare:"husky",prepublishOnly:"npm run build",knip:"knip"},dependencies:{"@inquirer/prompts":"^8.5.0",commander:"^15.0.0",dompurify:"^3.4.11",jsdom:"^30.0.1",nanoid:"^6.0.1",open:"^11.0.0",tslib:"^2.8.1","update-notifier":"^7.3.1",winston:"^3.19.0"},devDependencies:{"@api-now/core":"^1.55.1","@api-now/json":"^1.0.0","@commitlint/cli":"^21.0.1","@commitlint/config-conventional":"^21.0.1","@eslint/js":"^10.0.1","@semantic-release/changelog":"^7.0.0","@semantic-release/git":"^11.0.1","@types/node":"^26.2.0","@types/update-notifier":"^6.0.8",esbuild:"^0.28.0",eslint:"^10.4.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.6",globals:"^17.6.0",husky:"^9.1.7",knip:"^6.14.2",prettier:"^3.8.3","semantic-release":"^25.0.3",tsx:"^4.7.1",typescript:"^6.0.3","typescript-eslint":"^8.60.0"}};import Jn from"node:os";import Jt from"node:path";import Be from"node:fs";var _r="https://api.apinow.app",Wn="apinow-cli",Ap="config.json",Hn=class{_resolved=null;get resolved(){this._resolved||this.load();let e=this._resolved;if(!e)throw new Error("Configuration could not be loaded.");return e}configDir=this.#t();configPath=Jt.join(this.configDir,Ap);#e(e,t){if(!e.profiles&&(e.token||e.org||e.apiUrl)){let i={profiles:{default:{token:e.token||"",org:e.org,apiUrl:e.apiUrl||_r}},activeProfile:"default"};return t&&this.#o(i),i}return e}load(){let t=this.#r()??this.#s(),i=t.activeProfile,r=i&&t.profiles?t.profiles[i]:void 0,s=process.env.APINOW_API_TOKEN||process.env.APINOW_TOKEN||r?.token,o=process.env.APINOW_API_URL||r?.apiUrl||_r,a=r?.org||"";this._resolved={token:s,apiUrl:o,org:a,activeProfile:i,format:"text"}}saturate(e){this._resolved||this.load();let t=this._resolved;if(!t)throw new Error("Configuration could not be loaded.");this._resolved={token:t.token,apiUrl:t.apiUrl,org:t.org,activeProfile:t.activeProfile,format:e.format==="json"?"json":"text"}}listProfiles(){let e=this.#s();return e.profiles?{...e.profiles}:{}}getActiveProfile(){return this.#s().activeProfile}setActiveProfile(e){let t=this.#s();t.activeProfile=e,this.#o(t),this.load()}upsertProfile(e,t){let i=this.#s(),r=i.profiles?{...i.profiles}:{},s=r[e]||{token:""};r[e]={token:t.token!==void 0?t.token:s.token,org:t.org!==void 0?t.org:s.org,apiUrl:t.apiUrl!==void 0?t.apiUrl:s.apiUrl||_r},i.profiles=r,this.#o(i),this.load()}deleteProfile(e){let t=this.#s();if(t.profiles&&e in t.profiles){let i={...t.profiles};delete i[e],t.profiles=i,t.activeProfile===e&&delete t.activeProfile,this.#o(t),this.load()}}writeTokenToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,token:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}writeOrgToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,org:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}#t(){if(process.platform==="win32"){let e=process.env.APPDATA||Jt.join(Jn.homedir(),"AppData","Roaming");if(!e)throw new Error("Could not determine the configuration directory.");return Jt.join(e,Wn)}return process.platform==="darwin"?Jt.join(Jn.homedir(),"Library","Preferences",Wn):Jt.join(process.env.XDG_CONFIG_HOME||Jt.join(Jn.homedir(),".config"),Wn)}#i(){let e=process.cwd();for(;;){let t=Jt.join(e,"apinow.json");if(Be.existsSync(t))try{if(Be.statSync(t).isFile())return t}catch{}let i=Jt.join(e,".apinowrc.json");if(Be.existsSync(i))try{if(Be.statSync(i).isFile())return i}catch{}let r=Jt.dirname(e);if(r===e)break;e=r}return null}#r(){let e=this.#i();if(!e)return null;try{let t=Be.readFileSync(e,"utf8"),i=JSON.parse(t);return this.#e(i,!1)}catch{return null}}#s(){try{if(!Be.existsSync(this.configPath))return{};let e=Be.readFileSync(this.configPath,"utf8"),t=JSON.parse(e);return this.#e(t,!0)}catch{return{}}}writeProperty(e,t){let i=this.#s();e==="activeProfile"&&(i.activeProfile=t),this.#o(i),this.load()}#o(e){try{Be.existsSync(this.configDir)||Be.mkdirSync(this.configDir,{recursive:!0}),Be.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf8")}catch(t){console.error("Failed to write configuration:",t)}}clearConfigKey(e){try{let t=this.#s();delete t[e],this.#o(t),this.load()}catch(t){console.error(`Failed to clear key ${e} from configuration:`,t)}}reset(){try{Be.existsSync(this.configPath)&&Be.unlinkSync(this.configPath),Be.existsSync(this.configDir)&&Be.readdirSync(this.configDir).length===0&&Be.rmdirSync(this.configDir),this._resolved=null}catch(e){console.error("Failed to reset configuration:",e)}}},N=new Hn;import{styleText as Wi}from"node:util";import Ep from"node:path";import _p from"node:os";import xp from"node:crypto";import vt from"winston";var Ip=xp.randomBytes(4).toString("hex"),Pp=Date.now(),Ds=Ep.join(_p.tmpdir(),`apinow-cli-${Pp}-${Ip}.log`),dl=new vt.transports.Console({stderrLevels:Object.keys(vt.config.cli.levels),level:"info",format:vt.format.combine(vt.format.colorize(),vt.format.simple())}),Rp=new vt.transports.File({filename:Ds,level:"debug",format:vt.format.combine(vt.format.timestamp(),vt.format.printf(({timestamp:c,level:e,message:t})=>{let i=typeof t=="string"?t.replace(/\u001b\[\d+m/g,""):t;return`${c} [${e.toUpperCase()}]: ${i}`}))}),y=vt.createLogger({levels:vt.config.cli.levels,level:"debug",transports:[dl,Rp]});function pl(c){dl.level=c}var Yn=kt.version;var ie={green:c=>Wi("green",c),red:c=>Wi("red",c),yellow:c=>Wi("yellow",c),cyan:c=>Wi("cyan",c),dim:c=>Wi("dim",c),bold:c=>Wi("bold",c)};function $p(c,e,t){if(c.length===0)return"No data available.";let i={},r=t||e;for(let n=0;n<e.length;n++){let l=e[n],d=r[n]||l;i[l]=d.length}for(let n of c)for(let l of e){let d=typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"");d.length>(i[l]||0)&&(i[l]=d.length)}let s=e.map((n,l)=>(r[l]||n).toUpperCase().padEnd(i[n])).join(" "),o=e.map(n=>"-".repeat(i[n])).join(" "),a=c.map(n=>e.map(l=>(typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"")).padEnd(i[l])).join(" "));return[s,o,...a].join(`
|
|
3
3
|
`)}var K=class{format;constructor(e={}){this.format=e.format||"text"}success(e,t){this.format==="json"?console.log(JSON.stringify({success:!0,message:e,data:t},null,2)):(console.log(ie.green(`\u2714 ${e}`)),t!==void 0&&(typeof t=="object"&&t!==null?this.object(t):console.log(t)))}error(e){let t=e.code||"CLI_ERR_UNKNOWN";if(this.format==="json")console.error(JSON.stringify({success:!1,code:t,cliVersion:Yn,logFile:Ds,...e},null,2));else{if(console.error(ie.red(`\u2716 Error [${t}]: ${e.message}`)),e.detail&&console.error(ie.dim(e.detail)),e.errors&&e.errors.length>0){console.error(`
|
|
4
4
|
Validation errors:`);for(let i of e.errors)console.error(` - ${ie.yellow(i.field)}: ${i.message}`)}if(console.error(ie.dim(`(cli v${Yn})`)),console.error(ie.dim(`Log file: ${Ds}`)),t==="CLI_ERR_UNKNOWN"){let i="https://github.com/api-now/cli",r=encodeURIComponent(`[BUG] CLI Crash: ${e.message}`),s=encodeURIComponent(`**CLI Version:** ${Yn}
|
|
5
5
|
**Error Code:** ${t}
|
|
@@ -13,10 +13,10 @@ ${e.detail||"No stack trace available"}
|
|
|
13
13
|
\`\`\`
|
|
14
14
|
`),o=`${i}/issues/new?title=${r}&body=${s}`;console.error(`
|
|
15
15
|
Please report this bug: ${o}`)}}}list(e,t,i={}){if(this.format==="json")console.log(JSON.stringify(e,null,2));else{if(e.length===0){console.log("No records found.");return}console.log($p(e,t,i.headers))}}object(e){let t=e;if(this.format==="json")console.log(JSON.stringify(t,null,2));else for(let[i,r]of Object.entries(t)){let s=typeof r=="object"&&r!==null?JSON.stringify(r):String(r);console.log(`${ie.bold(i)}: ${s}`)}}};var Ae=class{options;formatter;constructor(e,t){this.options=e,this.formatter=t}resolveOrgId(e="Organization ID is required.",t="Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."){let i=this.options.org||N.resolved.org;return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:e,detail:t}),process.exit(1)),i}};var Ot=class c extends Ae{static ALLOWED_KEYS=["activeProfile"];configManager;constructor(e,t,i=N){super(e,t),this.configManager=i}isAllowedKey(e){return c.ALLOWED_KEYS.includes(e)}};var Ls=class extends Ot{key;constructor(e,t,i,r=N){super(t,i,r),this.key=e}execute(){y.debug(`[config:get] Retrieving configuration key '${this.key}'...`);let e=this.configManager.resolved;if(this.key in e){let t=e[this.key];y.debug(`[config:get] Key found. Value: ${this.key==="token"?"**********":String(t)}`),this.configManager.resolved.format==="json"?this.formatter.object({[this.key]:t}):console.log(t??"")}else y.debug(`[config:get] Configuration key '${this.key}' not found.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Configuration key '${this.key}' not found.`,detail:"Run `apinow config get <key>` to inspect configured properties."}),process.exit(1)}};var Ms=class extends Ot{key;value;constructor(e,t,i,r,s=N){super(i,r,s),this.key=e,this.value=t}execute(){y.debug(`[config:set] Setting configuration key '${this.key}' to '${this.key==="token"?"**********":this.value}'...`),this.isAllowedKey(this.key)||(y.debug(`[config:set] Invalid configuration key '${this.key}' rejected.`),this.key==="token"?this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"'token' is no longer a direct configuration setting.",detail:"Use `apinow auth login` to authenticate and configure profiles."}):this.key==="org"?this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"'org' is no longer a direct configuration setting.",detail:"Use `apinow orgs set-default <oid>` to configure the default organization for your active profile."}):this.key==="apiUrl"?this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"'apiUrl' is no longer a global configuration setting.",detail:"Use `apinow auth login --api-url <url>` to configure the API URL for an authentication profile."}):this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid configuration key '${this.key}'.`,detail:Ot.ALLOWED_KEYS.length>0?`Allowed keys: ${Ot.ALLOWED_KEYS.join(", ")}`:"Direct configuration editing is not supported. Use auth and orgs commands."}),process.exit(1)),this.configManager.writeProperty(this.key,this.value),y.debug("[config:set] Configuration property written successfully."),this.formatter.success(`Configuration '${this.key}' set to '${this.value}'.`)}};var Us=class extends Ot{constructor(e,t,i=N){super(e,t,i)}execute(){y.debug("[config:reset] Resetting CLI configuration..."),this.configManager.reset(),y.debug("[config:reset] Configuration reset completed successfully."),this.formatter.success("Configuration has been reset successfully.")}};function ul(c){let e=c.command("config").description("Manage CLI configuration settings");e.command("get <key>").description("Get a configuration value").action((t,i)=>{let r=new K({format:N.resolved.format});new Ls(t,i,r).execute()}),e.command("set <key> <value>").description("Set a configuration value").action((t,i,r)=>{let s=new K({format:N.resolved.format});new Ms(t,i,r,s).execute()}),e.command("reset").description("Reset all configuration settings and remove stored files").action(t=>{let i=new K({format:N.resolved.format});new Us(t,i).execute()})}import{Argument as Vp}from"commander";import hl from"http";import fl from"https";function xr(c){return typeof c!="string"&&(c=String(c)),c.toLowerCase()}function ml(c){return typeof c!="string"&&(c=String(c)),c}function*Op(c){if(!c||c.trim()==="")return[];let e=c.split(/\n(?=[^ \t]+)/gim);for(let t=0,i=e.length;t<i;t++){let r=e[t].trim();if(r==="")continue;let s=r.startsWith("#");s&&(r=r.replace("#","").trim());let o=r.indexOf(":");if(o===-1)yield{name:r,value:"",enabled:!s};else{let a=r.substring(0,o),n=r.substring(o+1).trim();yield{name:a,value:n,enabled:!s}}}}var Ir=class c{_map={};constructor(e){if(e instanceof c)e.forEach((t,i)=>this.append(i,t));else if(typeof e=="string")for(let t of Op(e))this.append(t.name,t.value,t.enabled);else e&&Object.keys(e).forEach(t=>this.append(t,e[t]))}append(e,t,i=!0){if(Array.isArray(t)){t.forEach(o=>this.append(e,o));return}let r=xr(e);t=t?ml(t):"";let s=this._map[r];if(s){let o=s.value;s.value=o?`${o},${t}`:t}else s={name:e,value:t,enabled:i};this._map[r]=s}delete(e){delete this._map[xr(e)]}get(e){if(e=xr(e),!!this.has(e)&&this._map[e].enabled)return this._map[e].value}has(e){let t=xr(e);return Object.prototype.hasOwnProperty.call(this._map,t)&&this._map[t].enabled}set(e,t,i=!0){let r=xr(e);this._map[r]={value:ml(t),name:e,enabled:i}}forEach(e,t){Object.keys(this._map).forEach(r=>{let s=this._map[r];e.call(t,s.value,s.name,s.enabled,this)})}map(e,t){let i=Object.keys(this._map),r=[];for(let s of i){let o=this._map[s],a=e.call(t,o.value,o.name,o.enabled);r.push(a)}return r}toString(){return this._generateString()}toRawString(){return this._generateString(!0)}toJSON(){let e={};for(let[t,i]of this.entries())e[t]=i;return e}_generateString(e=!1){let t=[],i=Object.keys(this._map);for(let r of i){let s=this._map[r],o="";if(!s.enabled)if(e)o+="# ";else continue;o+=`${s.name}: `,s.value&&(o+=s.value),t.push(o)}return t.join(`
|
|
16
|
-
`)}*keys(){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield this._map[t].name)}*values(){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield this._map[t].value)}*entries(){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield[this._map[t].name,this._map[t].value])}*[Symbol.iterator](){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield[this._map[t].name,this._map[t].value])}};function Zn(c,e){let t=c.toLowerCase();return t==="authorization"||t==="proxy-authorization"?e.toLowerCase().startsWith("bearer ")?"Bearer **********":"**********":t==="cookie"||t==="set-cookie"||t==="x-api-key"||t==="api-key"?"**********":e}function Xn(c){if(c==null)return c;if(Array.isArray(c))return c.map(e=>Xn(e));if(typeof c=="object"){let e={};for(let[t,i]of Object.entries(c)){let r=t.toLowerCase();r.includes("token")||r.includes("password")||r.includes("secret")||r.includes("key")?e[t]="**********":e[t]=Xn(i)}return e}return c}function Qn(c){if(!c)return c;try{let e=JSON.parse(c),t=Xn(e);return JSON.stringify(t,null,2)}catch{return c}}var b=class extends Error{name;status;static fromRawException(e,t){let i=e,r={};if(i.code!==void 0&&(r.code=String(i.code)),i.status!==void 0){let a=Number(i.status);isNaN(a)||(r.status=a)}i.help!==void 0&&(r.help=String(i.help));let s=i.message!==void 0?String(i.message):t,o=new this(s,r);return i.name!==void 0&&(o.name=String(i.name)),o}constructor(e,t){super(e,t);let i=this.constructor;this.name=i.name,this.message=e??i.message??"",this.status=t?.status??i.status??500;let r=t?.code??i.code;r!==void 0&&(this.code=r);let s=t?.help??i.help;s!==void 0&&(this.help=s),Error.captureStackTrace(this,i)}setHelp(e){return this.help=e,this}setCode(e){return this.code=e,this}setStatus(e){return this.status=e,this}get[Symbol.toStringTag](){return this.constructor.name}toString(){return this.code?`${this.name} [${this.code}]: ${this.message}`:`${this.name}: ${this.message}`}toJSON(){let e={name:this.name,message:this.message};return this.status&&(e.status=this.status),this.code&&(e.code=this.code),this.help&&(e.help=this.help),e}};var G="Invalid JSON response.",B="The response has no value.",C="Invalid response status: ",X="Unknown response from the server.";var me=class{sdk;constructor(e){this.sdk=e}logInvalidResponse(e){if(!this.sdk.silent&&e.body)try{let t=JSON.parse(e.body);t.message&&console.warn(`[Store message]: ${t.message}`)}catch{}}inspectCommonStatusCodes(e){let{status:t,body:i}=e;if(t===404){let r=this.createApiError("Not found",i);throw r.status!==404&&r.setStatus(404),r.code!=="E_NOT_FOUND"&&r.setCode("E_NOT_FOUND"),r}if(t===403){let r=this.createApiError("You have no access to this resource",i);throw r.status!==403&&r.setStatus(403),r.code!=="E_FORBIDDEN"&&r.setCode("E_FORBIDDEN"),r}if(t===401){this.sdk.dispatchEvent(new Event("unauthorized"));let r=this.createApiError("Not authorized",i);throw r.status!==401&&r.setStatus(401),r.code!=="E_UNAUTHORIZED"&&r.setCode("E_UNAUTHORIZED"),r}}createApiError(e,t){if(!t)return new b(e);let i;try{i=JSON.parse(t)}catch{return new b(e)}return!i||typeof i!="object"||!i.message?new b(e):b.fromRawException(i,e)}async genericBatchDelete(e,t,i={}){let{token:r}=i,s=await this.sdk.http.post(e.toString(),{token:r,body:JSON.stringify(t)});this.inspectCommonStatusCodes(s);let o="Unable to delete in batch. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async genericDelete(e,t={}){let{token:i}=t,r=await this.sdk.http.delete(e.toString(),{token:i});this.inspectCommonStatusCodes(r);let s="Unable to delete the object. ";if(r.status!==204)throw this.logInvalidResponse(r),this.createApiError(`${s}${C}${r.status}`,r.body)}async genericList(e,t,i={}){let{token:r}=i;this.sdk.appendListOptions(e,t);let s=await this.sdk.http.get(e.toString(),{token:r});this.inspectCommonStatusCodes(s);let o="Unable to list revisions for a file. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}readResponseBody(e,t){if(![200,202].includes(e.status))throw this.logInvalidResponse(e),this.createApiError(`${t}${C}${e.status}`,e.body);if(!e.body)throw new b(`${t}${B}`,{code:"E_RESPONSE_NO_VALUE",status:e.status});return e.body}readResponseJSON(e,t){let i=this.readResponseBody(e,t),r;try{r=JSON.parse(i)}catch{throw new b(`${t}${G}`,{code:"E_INVALID_JSON",status:e.status})}return r}processListResponse(e,t){this.inspectCommonStatusCodes(e);let i=this.readResponseJSON(e,t);if(!Array.isArray(i.data))throw new b(`${t}${X}`,{code:"E_RESPONSE_UNKNOWN",status:e.status});return i}assertObjectKind(e,t,i){if(t!==i)throw new b(`${e}${X}`,{code:"E_RESPONSE_UNKNOWN",status:500})}};var Pi=class extends Error{status;response;constructor(e,t){super(`HTTP Error: ${e}`),this.status=e,this.response=t}},zs=class extends me{logRequest(e,t,i){if(!this.sdk.logger)return;let r=i?.headers||{},s={};for(let[l,d]of Object.entries(r))s[l]=Zn(l,d);(i?.token||this.sdk.token)&&!s.authorization&&!s.Authorization&&(s.Authorization="Bearer **********");let a=i?.body,n=Qn(a);this.sdk.logger.log("debug",`--> HTTP ${e} ${t}`),Object.keys(s).length>0&&this.sdk.logger.log("debug",`Headers: ${JSON.stringify(s,null,2)}`),n&&this.sdk.logger.log("debug",`Body: ${n}`)}logResponse(e,t,i){if(!this.sdk.logger)return;let r=i.headers?i.headers.toJSON():{},s={};for(let[a,n]of Object.entries(r))s[a]=Zn(a,n);let o=Qn(i.body);this.sdk.logger.log("debug",`<-- HTTP ${i.status} ${e} ${t}`),Object.keys(s).length>0&&this.sdk.logger.log("debug",`Headers: ${JSON.stringify(s,null,2)}`),o&&this.sdk.logger.log("debug",`Body: ${o}`)}logError(e,t,i){if(!this.sdk.logger)return;let r=i instanceof Error?i.message:String(i);this.sdk.logger.log("debug",`<-- HTTP ${e} ${t} Failed: ${r}`)}};function Np(c,e=1e3){return globalThis.__MOCK_RETRY_DELAY_MS__!==void 0?globalThis.__MOCK_RETRY_DELAY_MS__:c<=0?e:e*Math.pow(2,c-1)}function Tp(c){let{status:e}=c;return!(typeof e=="number"&&e>=400&&e<500)}async function ec(c,e={}){let{retries:t=3,delayMs:i=Np,shouldRetry:r=Tp}=e,s;for(let a=0;a<t;a++)try{return await c()}catch(n){if(s=n,!r(s)||a===t-1)throw s;let l=typeof i=="function"?i(a+1):i;l>0&&await new Promise(d=>setTimeout(d,l))}throw s||new Error("Retry operation failed without a specific error.")}var Vs=class extends zs{async get(e,t={}){let i=async()=>{this.logRequest("GET",e,t);try{let r=await this._get(e,t);if(this.logResponse("GET",e,r),[301,302,308,307].includes(r.status)){let s=r.headers.get("location");if(!s)throw new Error('Expected redirection but no "location" header.');let o=new URL(s,e);return this.get(o.toString(),t)}if(t.retry&&r.status>=400)throw new Pi(r.status,r);return r}catch(r){throw this.logError("GET",e,r),r}};if(t.retry)try{let r=typeof t.retry=="object"?t.retry:{};return await ec(i,r)}catch(r){if(r instanceof Pi)return r.response;throw r}return i()}_get(e,t={}){return new Promise((i,r)=>{let{method:s="GET",headers:o={},token:a=this.sdk.token}=t,n={...o};a&&(n.authorization=`Bearer ${a}`);let p=(e.startsWith("https:")?fl:hl).request(e,{method:s,headers:n,rejectUnauthorized:!1});p.on("response",m=>{let h={status:m.statusCode,headers:new Ir(m.headers),body:""};m.on("data",f=>{h.body+=f}),m.on("end",()=>i(h))}),p.on("error",m=>r(m)),p.end()})}async post(e,t={}){let i=t.method||"POST",r=async()=>{this.logRequest(i,e,t);let s=await new Promise((o,a)=>{let{headers:n={},token:l=this.sdk.token}=t,d={...n};l&&(d.authorization=`Bearer ${l}`),t.body&&!d["content-type"]&&!d["Content-Type"]&&(d["content-type"]="application/json");let h=(e.startsWith("https:")?fl:hl).request(e,{method:i,headers:d});h.on("response",f=>{let k={status:f.statusCode,headers:new Ir(f.headers),body:""};f.on("data",w=>{k.body+=w}),f.on("end",()=>{this.logResponse(i,e,k),o(k)})}),h.on("error",f=>{this.logError(i,e,f),a(f)}),t.body&&h.write(t.body),h.end()});if(t.retry&&s.status>=400)throw new Pi(s.status,s);return s};if(t.retry)try{let s=typeof t.retry=="object"?t.retry:{};return await ec(r,s)}catch(s){if(s instanceof Pi)return s.response;throw s}return r()}patch(e,t={}){let i={...t,method:"PATCH"};return this.post(e,i)}put(e,t={}){let i={...t,method:"PUT"};return this.post(e,i)}delete(e,t={}){let i={...t,method:"DELETE"};return this.post(e,i)}};var T=class c{static folders(e){return`/v1/orgs/${e}/folders`}static files(e){return`/v1/orgs/${e}/files`}static filesSearch(e){return`${c.files(e)}/search`}static filesAccess(e,t){return`${c.file(e,t)}/access`}static filesBatch(e){return`${c.files(e)}/batch/read-meta`}static file(e,t){return`${c.files(e)}/${t}`}static fileMedia(e,t){return`${c.file(e,t)}/media`}static fileUsers(e,t){return`${c.file(e,t)}/users`}static fileRevisions(e,t){return`${c.file(e,t)}/revisions`}static fileBreadcrumbs(e,t){return`${c.file(e,t)}/breadcrumbs`}static fileRename(e,t){return`${c.file(e,t)}/rename`}static history(){return"/history"}static historyBatchCreate(){return"/history/batch/create"}static historyBatchDelete(){return"/history/batch/delete"}static historyItem(e){return`/history/${e}`}static historyClear(e,...t){return`/history/clear/${e}/${t.join("/")}`}static shared(e){return`/v1/orgs/${e}/shared`}static trash(e){return`/v1/orgs/${e}/trash`}static trashItem(e,t){return`${c.trash(e)}/${t}`}static trashRestore(e,t){return`${c.trashItem(e,t)}/restore`}static trashEmpty(e){return`${c.trash(e)}/empty`}static trashBatchRestore(e){return`${c.trash(e)}/restore`}static trashBatchDelete(e){return`${c.trash(e)}/delete`}static projectExecutions(){return"/project/execution"}static projectExecution(e){return`/project/execution/${e}`}static projectExecutionBulkDelete(){return"/project/execution/delete"}static projectExecutionClear(e){return`/project/execution/clear/${e}`}static organizations(){return"/v1/orgs"}static organization(e){return`/v1/orgs/${e}`}static organizationUsers(e){return`${this.organization(e)}/users`}static organizationUserBatch(e){return`${this.organization(e)}/users/batch/read`}static organizationUser(e,t){return`${this.organization(e)}/users/${t}`}static organizationUserDeactivate(e,t){return`${this.organization(e)}/users/${t}/deactivate`}static organizationUserActivate(e,t){return`${this.organization(e)}/users/${t}/activate`}static invitations(e){return`${this.organization(e)}/invitations`}static invitation(e,t){return`${this.invitations(e)}/${t}`}static findInvitation(){return`${this.organizations()}/find-invitation`}static declineInvitation(e,t){return`${this.invitation(e,t)}/decline`}static resendInvitation(e,t){return`${this.invitation(e,t)}/resend`}static authGoogle(){return"/auth/google"}static authLogout(){return"/auth/logout"}static usersMe(){return"/v1/users/me"}static usersMeTokens(){return`${c.usersMe()}/tokens`}static usersMeToken(e){return`${c.usersMeTokens()}/${e}`}static dataCatalog(){return"/v1/datacatalog"}static dataCatalogStatus(e){return`${c.dataCatalog()}/status/${e}`}static dataCatalogEntry(e){return`${c.dataCatalog()}/${e}`}static dataCatalogEntryVersions(e){return`${c.dataCatalogEntry(e)}/versions`}static dataCatalogDependencies(){return`${c.dataCatalog()}/dependencies`}static dataCatalogUpdates(){return`${c.dataCatalog()}/updates`}static dataCatalogVersion(e,t){return`${c.dataCatalogEntry(e)}/${t}`}static dataCatalogDeprecate(e){return`${c.dataCatalogEntry(e)}/deprecate`}static dataCatalogUnpublish(e){return`${c.dataCatalogEntry(e)}/unpublish`}static dataCatalogVersionDeprecate(e,t){return`${c.dataCatalogVersion(e,t)}/deprecate`}static dataCatalogVersionUnpublish(e,t){return`${c.dataCatalogVersion(e,t)}/unpublish`}static dataCatalogUsage(e){return`${c.dataCatalogEntry(e)}/apis`}static dataCatalogVersionUsage(e,t){return`${c.dataCatalogVersion(e,t)}/apis`}static groups(e){return`/v1/orgs/${e}/groups`}static group(e,t){return`/v1/orgs/${e}/groups/${t}`}static groupUsers(e,t){return`/v1/orgs/${e}/groups/${t}/users`}static aiModifyDomain(e,t){return`${this.organization(e)}/ai/domains/${t}/modify/stream`}static aiModifyApi(e,t){return`${this.organization(e)}/ai/apis/${t}/modify/stream`}static aiSessions(e,t){return`${this.organization(e)}/ai/sessions/${t}`}static aiSession(e,t,i){return`${c.aiSessions(e,t)}/${i}`}static aiMessages(e,t){return`${this.organization(e)}/ai/messages/${t}`}static aiMessage(e,t,i){return`${c.aiMessages(e,t)}/${i}`}static orgSlugGenerate(){return"/v1/orgs/slugs/generate"}static orgSlugValidate(){return"/v1/orgs/slugs/validate"}static deployments(e){return`/v1/orgs/${e}/deployments`}static deploymentsApis(e){return`${c.deployments(e)}/apis`}static deployment(e,t){return`${c.deployments(e)}/${t}`}static deploymentsForApi(e,t){return`${c.deploymentsApis(e)}/${t}`}static deploymentsApisByEnvLatest(e,t){return`${c.deploymentsApis(e)}/${t}/environments/latest`}static rollback(e,t){return`${c.deployment(e,t)}/rollback`}static deploymentDeactivate(e,t){return`${c.deployment(e,t)}/deactivate`}static deploymentOas(e,t){return`${c.deployment(e,t)}/oas`}static deploymentsApiRuntimeUsersUpdate(e,t){return`${c.deploymentsApis(e)}/${t}/runtime/users/update`}static job(e,t){return`/v1/orgs/${e}/jobs/${t}`}};var Fs=class extends me{oauthRedirect(e,t={}){let{redirect:i,token:r,type:s="redirect"}=t,o=new URL(this.sdk.baseUri);if(!["google","github","linkedin"].includes(e))throw new Error(`Invalid provider: ${e}`);let a=new URL(`/auth/${e}/redirect`,o);return i&&a.searchParams.set("r",i),r&&a.searchParams.set("token",r),s==="redirect"?(window.location.href=a.toString(),null):window.open(a.toString(),"_blank")}async logout(e={}){let{token:t,retry:i=!0}=e,r=this.sdk.getUrl(T.authLogout()),s=await this.sdk.http.post(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to log out. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body)}};import{customAlphabet as jp}from"nanoid";var W=jp("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var Tt="Core#Permission",Nt=["reader","commenter","writer","owner"],oi=class c{kind=Tt;key="";type="user";granteeId="";role="reader";displayName;expirationTime;addingUser="";itemId="";depth=0;sourceRule="direct_user_grant";static fromUserRole(e,t,i,r){let s={key:W(),kind:Tt,itemId:t,granteeId:i,role:e,type:"user",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new c(s)}static fromGroupRole(e,t,i,r){let s={key:W(),kind:Tt,itemId:t,granteeId:i,role:e,type:"group",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new c(s)}static fromOrganizationRole(e,t,i,r){let s={key:W(),kind:Tt,itemId:t,granteeId:i,role:e,type:"organization",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new c(s)}static fromValues(e){return new c({...e,key:W(),kind:Tt})}constructor(e){let t;typeof e=="string"?t=JSON.parse(e):typeof e=="object"?t=e:t={kind:Tt,key:W(),granteeId:"",itemId:"",role:"reader",type:"user",addingUser:"",depth:0,sourceRule:"direct_user_grant"},this.new(t)}new(e){if(!c.isPermission(e))throw new Error("Not a permission.");let{key:t=W(),granteeId:i,role:r,type:s,displayName:o,expirationTime:a,addingUser:n,itemId:l,depth:d,sourceRule:p}=e;this.kind=Tt,this.key=t,this.granteeId=i,this.itemId=l,this.role=r,this.type=s,this.addingUser=n,this.depth=d||0,this.sourceRule=p||"direct_user_grant",o?this.displayName=o:this.displayName=void 0,typeof a=="number"?this.expirationTime=a:this.expirationTime=void 0}static isPermission(e){return!(!e||e.kind!==Tt)}static hasRole(e,t){if(!t)return!1;let i=Nt.indexOf(t),r=Nt.indexOf(e);return i>=r}static isHigherRole(e,t){let i=Nt.indexOf(e),r=Nt.indexOf(t);return i>r}hasRole(e){return c.hasRole(e,this.role)}static hasRoleIn(e,t){if(!t||!t.length)return!1;let i=[...t].sort((n,l)=>n.depth-l.depth),r=i[0].depth,s=i.filter(n=>n.depth===r),o,a=s.filter(n=>n.type==="user");if(a.length)o=a.sort((n,l)=>Nt.indexOf(l.role)-Nt.indexOf(n.role))[0];else{let n=s.filter(l=>l.type==="group");if(n.length)o=n.sort((l,d)=>Nt.indexOf(d.role)-Nt.indexOf(l.role))[0];else{let l=s.filter(d=>d.type==="organization");l.length&&(o=l.sort((d,p)=>Nt.indexOf(p.role)-Nt.indexOf(d.role))[0])}}return o?c.hasRole(e,o.role):!1}toJSON(){let e={kind:Tt,key:this.key,role:this.role,type:this.type,addingUser:this.addingUser,granteeId:this.granteeId,itemId:this.itemId,depth:this.depth,sourceRule:this.sourceRule};return this.displayName&&(e.displayName=this.displayName),this.expirationTime&&(e.expirationTime=this.expirationTime),e}};var ai="Core#Thing",ot="Core#Folder";var Pr="Core#User",ni="Data#DomainFile",Ee="Data#Domain",Le="Domain#Namespace",Oe="Domain#Model",$="Domain#Entity",se="Domain#Association",be="Domain#Property",wt="Core#DataCatalog",Wt="Core#DataCatalogVersion";var Ri="Core#Deployment",ke="Core#ApiModel",Ht="Core#ExposedEntity",Yt="Core#ApiFile";var Rr="Core#AiSession",tc="Core#AiMessage",ic="Core#Job";var he=class c{kind=ai;name;displayName;description;version;static fromName(e){return new c({name:e,kind:ai})}static fromJSON(e={},t={}){let i=new c,{name:r,displayName:s,description:o,version:a}=e||{};return typeof r=="string"?i.name=r:typeof t.name=="string"&&(i.name=t.name),typeof s=="string"?i.displayName=s:typeof t.displayName=="string"&&(i.displayName=t.displayName),o?i.description=o:typeof t.description=="string"&&(i.description=t.description),a?i.version=a:typeof t.version=="string"&&(i.version=t.version),i}constructor(e){let t;typeof e=="string"?t=JSON.parse(e):typeof e=="object"?t=e:t={kind:ai},this.new(t)}new(e){if(!c.isThing(e))throw new Error("Not a thing.");let{description:t,name:i,version:r,displayName:s}=e;this.kind=ai,this.name=i,this.displayName=s,this.description=t,this.version=r}static validate(e,t={}){let{strict:i}=t;return e&&typeof e=="object"?!(i&&e.kind!==ai):!1}static isThing(e){return!!(e&&e.kind===ai)}toJSON(){let e={kind:ai};return typeof this.name=="string"&&(e.name=this.name),typeof this.displayName=="string"&&(e.displayName=this.displayName),this.description&&(e.description=this.description),this.version&&(e.version=this.version),e}getLabel(e){return this.displayName||this.name||e||"Unnamed object"}};var rc=Symbol("parents"),qs=Symbol("deleted"),Ks=Symbol("deletedInfo"),Bs=Symbol("lastModified"),sc=Symbol("capabilities"),oc=Symbol("permissions"),ac=Symbol("permissionIds"),nc=Symbol("shortcutTarget"),$r=class{kind="";key="";info=he.fromName("");iconColor;get isShortcut(){return!!this.shortcutTarget}[nc];get shortcutTarget(){return this[nc]}set shortcutTarget(e){this[nc]=e}static createSchema(e={}){let{key:t=W(),kind:i,iconColor:r,shortcutTarget:s}=e,o={key:t,kind:i||"",info:he.fromJSON(e.info,{name:"Unnamed file"}).toJSON()};return r&&(o.iconColor=r),s&&(o.isShortcut=!0,o.shortcutTarget=s),o}constructor(e){this.kind=e.kind,this.key=e.key,this.info=new he(e.info),e.iconColor&&(this.iconColor=e.iconColor),e.shortcutTarget&&(this.shortcutTarget=e.shortcutTarget)}toJSON(){let e={key:this.key,kind:this.kind,info:this.info.toJSON()};return this.iconColor&&(e.iconColor=this.iconColor),this.shortcutTarget&&(e.isShortcut=!0,e.shortcutTarget=this.shortcutTarget),e}static createFileCapabilities(e,t){let i=oi.hasRole("commenter",t),r=oi.hasRole("owner",t),s=oi.hasRole("reader",t),o=oi.hasRole("writer",t),a=e.kind===ot;return{canReadMedia:!a&&s,canListChildren:a&&s,canComment:!a&&i,canEditMedia:!a&&o,canEditMeta:o,canReadRevisions:o,canAddChildren:a&&o,canDelete:r,canTrash:r,canUntrash:r,canShare:o,canMove:o}}createFileCapabilities(e){return Xt.createFileCapabilities(this,e)}static updateByMeMeta(e,t){e.deletedInfo&&(e.deletedInfo.byMe=e.deletedInfo.user===t),e.lastModified&&(e.lastModified.byMe=e.lastModified.user===t)}static setLastModified(e,t){if(!e)throw new Error("The file is required.");if(!t)throw new Error("The user is required.");if(t.kind!==Pr)throw new Error('Invalid value for the user when setting "lastModified".');return e.lastModified={byMe:!1,time:Date.now(),user:t.key,name:t.name},e}static setDeleted(e,t){if(!e)throw new Error("The file is required.");if(!t)throw new Error("The user is required.");if(t.kind!==Pr)throw new Error('Invalid value for the user when setting "deletedInfo".');return e.deleted=!0,e.deletedInfo={byMe:!1,time:Date.now(),user:t.key,name:t.name},e}},Xt=class c extends $r{[rc]=[];get parents(){return this[rc]}[ac]=[];get permissionIds(){return this[ac]}[qs];get deleted(){return this[qs]||!1}[Ks];get deletedInfo(){return this[Ks]}[Bs]={user:"",time:0,byMe:!1};get lastModified(){return this[Bs]}labels;[sc];get capabilities(){return this[sc]}[oc]=[];get permissions(){return this[oc]}static createSchema(e={}){let t=$r.createSchema(e);return Array.isArray(e.parents)?t.parents=[...e.parents]:t.parents=[],Array.isArray(e.permissionIds)?t.permissionIds=[...e.permissionIds]:t.permissionIds=[],Array.isArray(e.permissions)?t.permissions=e.permissions.map(i=>({...i})):t.permissions=[],e.capabilities&&(t.capabilities={...e.capabilities}),e.lastModified?t.lastModified={...e.lastModified}:t.lastModified={user:"",time:0,byMe:!1},typeof e.deleted=="boolean"&&(t.deleted=e.deleted,t.deletedInfo=e.deletedInfo?{...e.deletedInfo}:void 0),Array.isArray(e.labels)&&(t.labels=[...e.labels]),typeof e.shortcutTarget=="string"&&(t.shortcutTarget=e.shortcutTarget),t}constructor(e){let t=c.createSchema(e);super(t),this[rc]=[...t.parents],this[ac]=[...t.permissionIds],this[oc]=t.permissions.map(i=>({...i})),this[sc]=t.capabilities?{...t.capabilities}:void 0,this[Bs]=Object.freeze({...t.lastModified}),typeof t.deleted=="boolean"&&(this[qs]=t.deleted,this[Ks]=t.deletedInfo?Object.freeze({...t.deletedInfo}):void 0),Array.isArray(t.labels)&&(this.labels=[...t.labels])}toJSON(){let e={...super.toJSON(),parents:[...this.parents],permissionIds:[...this.permissionIds],lastModified:{...this.lastModified},permissions:[...this.permissions]};return this.deleted&&(e.deleted=this.deleted,e.deletedInfo={...this.deletedInfo}),Array.isArray(this.labels)&&(e.labels=[...this.labels]),e}static fromName(e,t){return new c({kind:t,info:{name:e}})}shortcutTo(e){return this.shortcutTarget=e,this}setLastModified(e){if(!e)throw new Error("The user is required.");if(e.kind!==Pr)throw new Error('Invalid value for the user when setting "lastModified".');this[Bs]={byMe:!1,time:Date.now(),user:e.key,name:e.name}}addLabel(e){if(typeof e!="string")throw new Error("The label must be a string.");if(!e.trim())throw new Error("The label is required.");Array.isArray(this.labels)||(this.labels=[]),!this.labels.includes(e)&&this.labels.push(e)}setDeleted(e){if(!e)throw new Error("The user is required.");if(e.kind!==Pr)throw new Error('Invalid value for the user when setting "deletedInfo".');this[qs]=!0,this[Ks]={byMe:!1,time:Date.now(),user:e.key,name:e.name}}isFile(){return this.kind!==ot}isFolder(){return this.kind===ot}};var Or=class extends Xt{kind=ot;static fromName(e){return super.fromName(e,ot)}constructor(e){let t=Xt.createSchema(e);t.kind=ot,super(t)}static isFolder(e){return!(!e||e.kind!==ot)}toJSON(){return{...super.toJSON(),kind:ot}}};var Gs=class extends me{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o={...t},a=this.sdk.getUrl(T.files(e));this.sdk.appendListOptions(a,o);let n=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(n);let l="Unable to list files. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async search(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.filesSearch(e)),{searchParams:a}=o;if(t.cursor&&a.set("cursor",t.cursor),typeof t.limit=="number"&&a.set("limit",String(t.limit)),t.parent&&a.set("parent",t.parent),t.kind)for(let l of t.kind)a.append("kind",l);if(t.query)for(let l of t.query)a.append("query",l);let n=await this.sdk.http.get(o.toString(),{token:r,retry:s});return this.processListResponse(n,"Unable to search files. ")}async create(e,t,i,r={},s={}){let o=await this.createMeta(e,i,r,s);return await this.createMedia(t,i,o.key,r,s),o}async createMeta(e,t,i={},r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.files(t));i.parent&&a.searchParams.set("parent",i.parent);let n=JSON.stringify(e),l=await this.sdk.http.post(a.toString(),{token:s,body:n,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let d="Unable to create a file. ";if(l.status!==201)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async createMedia(e,t,i,r={},s={}){let{token:o=this.sdk.token,retry:a=!0}=s,n=T.fileMedia(t,i),l=this.sdk.getUrl(n),d=r.mime||"application/json",p;d.includes("json")?p=JSON.stringify(e):p=String(e);let m=await this.sdk.http.put(l.toString(),{token:o,body:p,retry:a,headers:{"content-type":d}});this.inspectCommonStatusCodes(m);let h="Unable to create a file. ";if(m.status!==200)throw this.logInvalidResponse(m),this.createApiError(`${h}${C}${m.status}`,m.body)}async createFolder(e,t,i={},r={}){let s=Or.fromName(e),{token:o=this.sdk.token,retry:a=!0}=r,n=this.sdk.getUrl(T.files(t));i.parent&&n.searchParams.set("parent",i.parent);let l=JSON.stringify(s),d=await this.sdk.http.post(n.toString(),{token:o,body:l,retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(d);let p="Unable to create a file. ";if(d.status!==201)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}if(!m.key)throw new b(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:d.status});return m}async read(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.file(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read a file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async readMedia(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.fileMedia(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read a file media. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l||typeof l!="object"||!("data"in l)||!("meta"in l))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});let{data:d,meta:p}=l;if(!p||typeof p!="object"||typeof p.version!="number"||typeof p.updated!="number"||isNaN(p.version)||isNaN(p.updated))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return{media:d,meta:p}}async readBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.filesBatch(e)),a=JSON.stringify({ids:t}),n=await this.sdk.http.post(o.toString(),{token:r,body:a,retry:s});this.inspectCommonStatusCodes(n);let l="Unable to read files in bulk. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async patch(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=T.file(e,t),n=this.sdk.getUrl(a),l=JSON.stringify(i),d=await this.sdk.http.patch(n.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(d);let p="Unable to patch a file. ";if(d.status!==200)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}if(!m.kind)throw new b(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:d.status});return m}async patchMedia(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=T.fileMedia(e,t),n=this.sdk.getUrl(a),l=JSON.stringify(i),d=await this.sdk.http.patch(n.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(d);let p="Unable to patch a file contents. ";if(d.status!==200)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}return m}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.file(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to trash a file. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async deleteBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.files(e)),a=await this.sdk.http.delete(o.toString(),{token:r,body:JSON.stringify({ids:t}),retry:s});this.inspectCommonStatusCodes(a);let n="Unable to trash files. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async patchUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.filesAccess(e,t)),n=JSON.stringify(i),l=await this.sdk.http.patch(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to patch the file. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async addUser(e,t,i,r,s,o){let a={op:"add",type:"user",value:r,id:i};typeof s=="number"&&(a.expirationTime=s);let n={patch:[a],id:W()};return this.patchUsers(e,t,n,o)}async removeUser(e,t,i,r){let o={patch:[{op:"remove",type:"user",id:i}],id:W()};return this.patchUsers(e,t,o,r)}async listUsers(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.fileUsers(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list users in the file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async breadcrumbs(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.fileBreadcrumbs(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read breadcrumbs. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async rename(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.fileRename(e,t)),n=await this.sdk.http.put(a.toString(),{token:s,body:JSON.stringify({name:i}),retry:o});this.inspectCommonStatusCodes(n);let l="Unable to rename file. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}return d}};var Js=class extends me{async me(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(T.usersMe()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to read a user. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!a.key)throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async listTokens(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(T.usersMeTokens()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to list tokens. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}return a}async createToken(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.usersMeTokens()),o=JSON.stringify(e),a=await this.sdk.http.post(s.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to create a token. ";if(a.status!==200&&a.status!==201)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l}async deleteToken(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.usersMeToken(e)),o=await this.sdk.http.delete(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to delete a token. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body)}};var Ws=class extends me{async list(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.shared(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list shared files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}};var Hs=class extends me{async list(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.fileRevisions(e,t));this.sdk.appendListOptions(a,i);let n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to list revisions for a file. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}};var Ys=class extends me{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.trash(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list trash. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async delete(e,t,i={}){let r=T.trashBatchDelete(e),s=this.sdk.getUrl(r),{token:o=this.sdk.token,retry:a=!0}=i,n=await this.sdk.http.delete(s.toString(),{token:o,body:JSON.stringify({ids:t}),retry:a});this.inspectCommonStatusCodes(n);let l="Unable to delete trash. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body)}async restore(e,t,i={}){let r=this.sdk.getUrl(T.trashBatchRestore(e)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,body:JSON.stringify({ids:t}),retry:o});this.inspectCommonStatusCodes(a);let n="Unable to restore from trash. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async empty(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.trashEmpty(e)),o=await this.sdk.http.delete(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to empty trash. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body)}};var Xs=class extends me{async list(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(T.organizations()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to list your organizations. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizations()),a={name:e,slug:t},n=await this.sdk.http.post(o.toString(),{body:JSON.stringify(a),token:r,headers:{"Content-Type":"application/json"},retry:s});this.inspectCommonStatusCodes(n);let l="Unable to create an organization. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.kind)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}invitations={list:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.invitations(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to list organization invitations. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);if(!o.body)throw new b(`${a}${B}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let n;try{n=JSON.parse(o.body)}catch{throw new b(`${a}${G}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(n.data))throw new b(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return n},create:async(e,t,i,r,s={})=>{let{token:o=this.sdk.token,retry:a=!0}=s,n=this.sdk.getUrl(T.invitations(e)),l={email:t,name:r,grant_type:i},d=await this.sdk.http.post(n.toString(),{body:JSON.stringify(l),token:o,headers:{"Content-Type":"application/json"},retry:a});this.inspectCommonStatusCodes(d);let p="Unable to create an invitation. ";if(d.status!==200)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}if(!m.kind)throw new b(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:d.status});return m},findByToken:async(e,t={})=>{let i=this.sdk.getUrl(T.findInvitation());i.searchParams.append("token",e);let{retry:r=!0,token:s}=t,o=await this.sdk.http.get(i.toString(),{token:s,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to find invitation by token. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);if(!o.body)throw new b(`${a}${B}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let n;try{n=JSON.parse(o.body).data}catch{throw new b(`${a}${G}`,{code:"E_INVALID_JSON",status:o.status})}if(!n.kind)throw new b(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return n},decline:async(e,t,i={})=>{let r=this.sdk.getUrl(T.declineInvitation(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to decline invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},delete:async(e,t,i={})=>{let r=this.sdk.getUrl(T.invitation(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.delete(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to delete invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},patch:async(e,t,i,r={})=>{let s=this.sdk.getUrl(T.invitation(e,t)),{token:o=this.sdk.token,retry:a=!0}=r,n=await this.sdk.http.patch(s.toString(),{body:JSON.stringify(i),token:o,headers:{"Content-Type":"application/json"},retry:a});this.inspectCommonStatusCodes(n);let l="Unable to update invitation. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.kind)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},resend:async(e,t,i={})=>{let r=this.sdk.getUrl(T.resendInvitation(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.put(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to resend invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}};users={list:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUsers(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list projects. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},read:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUser(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read the user info. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l},readBatch:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUserBatch(e)),a={ids:t},n=await this.sdk.http.post(o.toString(),{body:JSON.stringify(a),token:r,retry:s});this.inspectCommonStatusCodes(n);let l="Unable to read the user batch info. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},activate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUserActivate(e,t)),a=await this.sdk.http.post(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to activate the user. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l},deactivate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUserDeactivate(e,t)),a=await this.sdk.http.post(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to deactivate the user. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l},delete:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUser(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to delete the user. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}};slugs={generate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.orgSlugGenerate()).toString(),o={name:e},a=await this.sdk.http.post(s,{body:JSON.stringify(o),token:i,retry:r});this.inspectCommonStatusCodes(a);let n="Unable to generate the slug. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.slug)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l.slug},validate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.orgSlugValidate()).toString(),o={slug:e},a=await this.sdk.http.post(s,{body:JSON.stringify(o),token:i,retry:r});this.inspectCommonStatusCodes(a);let n="Unable to validate the slug. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(typeof l.valid!="boolean")throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}}};var Zs=class extends me{async list(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s={...e},o=this.sdk.getUrl(T.dataCatalog());this.sdk.appendListOptions(o,s),s.scope&&o.searchParams.set("scope",s.scope);let a=await this.sdk.http.get(o.toString(),{token:i,retry:r});return this.processListResponse(a,"Unable to list data domains. ")}async listVersions(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogEntryVersions(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});return this.processListResponse(o,"Unable to list data domain versions. ")}async publish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalog()),o=JSON.stringify(e),a=await this.sdk.http.post(s.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to publish data domain. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,wt,l.kind),l}async read(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogEntry(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to read data domain. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);let n=this.readResponseJSON(o,a).data;return this.assertObjectKind(a,wt,n.kind),n}async deprecate(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogDeprecate(e)),a=JSON.stringify({reason:t}),n=await this.sdk.http.put(o.toString(),{token:r,body:a,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(n);let l="Unable to deprecate data domain. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);let d=this.readResponseJSON(n,l).data;return this.assertObjectKind(l,wt,d.kind),d}async unpublish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogUnpublish(e)),o=await this.sdk.http.put(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to unpublish data domain. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);let n=this.readResponseJSON(o,a).data;return this.assertObjectKind(a,wt,n.kind),n}async publishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogEntryVersions(e)),a=JSON.stringify(t),n=await this.sdk.http.post(o.toString(),{token:r,body:a,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(n);let l="Unable to publish data domain version. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);let d=this.readResponseJSON(n,l).data;return this.assertObjectKind(l,Wt,d.kind),d}async readVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogVersion(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Wt,l.kind),l}async listDependencies(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogDependencies()),o=JSON.stringify({items:e}),a=await this.sdk.http.post(s.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(a,"Unable to list data domain dependencies. ")}async checkUpdates(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=e.map(l=>({fid:l.key,version:l.version})),o=this.sdk.getUrl(T.dataCatalogUpdates()),a=JSON.stringify({dependencies:s}),n=await this.sdk.http.post(o.toString(),{token:i,body:a,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(n,"Unable to check for data domain updates. ")}async deprecateVersion(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.dataCatalogVersionDeprecate(e,t)),n=JSON.stringify({reason:i}),l=await this.sdk.http.put(a.toString(),{token:s,body:n,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let d="Unable to deprecate data domain version. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);let p=this.readResponseJSON(l,d).data;return this.assertObjectKind(d,Wt,p.kind),p}async unpublishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogVersionUnpublish(e,t)),a=await this.sdk.http.put(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to unpublish data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Wt,l.kind),l}async checkPublicationStatus(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogStatus(e));t&&o.searchParams.set("oid",t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to check data domain publication status. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,wt,l.kind),l}async getUsageFiles(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogUsage(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to get data catalog usage files. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);return this.processListResponse(o,a)}async getVersionUsageFiles(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogVersionUsage(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to get data catalog version usage files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);return this.processListResponse(a,n)}};var Qs=class extends me{async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.groups(e)),a=JSON.stringify(t),n=await this.sdk.http.post(o.toString(),{token:r,body:a,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(n);let l="Unable to create a group. ";if(n.status!==201)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.key)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.groups(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to create a group. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(n+C+a.status,a.body);if(!a.body)throw new b(n+B,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(n+G,{code:"E_INVALID_JSON",status:a.status})}return l}async update(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.group(e,t.key)),a=JSON.stringify(t),n=await this.sdk.http.put(o.toString(),{token:r,body:a,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(n);let l="Unable to update a group. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.key)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.group(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to delete a group. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async addUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.groupUsers(e,t)),n=JSON.stringify({ids:i}),l=await this.sdk.http.post(a.toString(),{token:s,body:n,headers:{"content-type":"application/json"},retry:o});this.inspectCommonStatusCodes(l);let d="Unable to add users to a group. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async removeUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.groupUsers(e,t)),n=JSON.stringify({ids:i}),l=await this.sdk.http.delete(a.toString(),{token:s,body:n,headers:{"content-type":"application/json"},retry:o});this.inspectCommonStatusCodes(l);let d="Unable to remove users from a group. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}};var eo=class extends me{async*modifyDomain(e,t,i,r,s={}){let{token:o=this.sdk.token,signal:a}=s,n=this.sdk.getUrl(T.aiModifyDomain(e,t)),l=JSON.stringify({goal:i,sid:r}),d={method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${o}`},redirect:"follow",credentials:"include",body:l,signal:a},p=await fetch(n,d);if(!p.ok){let k=await p.text();throw new b(`Failed to modify domain: ${p.status} ${k}`)}let m=p.body?.getReader();if(!m)throw new b("Failed to get reader from response");let h=new TextDecoder,f="";for(;;){let{done:k,value:w}=await m.read();if(k)return;f+=h.decode(w,{stream:!0});let S;for(;(S=f.indexOf(`
|
|
16
|
+
`)}*keys(){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield this._map[t].name)}*values(){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield this._map[t].value)}*entries(){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield[this._map[t].name,this._map[t].value])}*[Symbol.iterator](){let e=Object.keys(this._map);for(let t of e)this._map[t].enabled&&(yield[this._map[t].name,this._map[t].value])}};function Zn(c,e){let t=c.toLowerCase();return t==="authorization"||t==="proxy-authorization"?e.toLowerCase().startsWith("bearer ")?"Bearer **********":"**********":t==="cookie"||t==="set-cookie"||t==="x-api-key"||t==="api-key"?"**********":e}function Xn(c){if(c==null)return c;if(Array.isArray(c))return c.map(e=>Xn(e));if(typeof c=="object"){let e={};for(let[t,i]of Object.entries(c)){let r=t.toLowerCase();r.includes("token")||r.includes("password")||r.includes("secret")||r.includes("key")?e[t]="**********":e[t]=Xn(i)}return e}return c}function Qn(c){if(!c)return c;try{let e=JSON.parse(c),t=Xn(e);return JSON.stringify(t,null,2)}catch{return c}}var b=class extends Error{name;status;static fromRawException(e,t){let i=e,r={};if(i.code!==void 0&&(r.code=String(i.code)),i.status!==void 0){let a=Number(i.status);isNaN(a)||(r.status=a)}i.help!==void 0&&(r.help=String(i.help));let s=i.message!==void 0?String(i.message):t,o=new this(s,r);return i.name!==void 0&&(o.name=String(i.name)),o}constructor(e,t){super(e,t);let i=this.constructor;this.name=i.name,this.message=e??i.message??"",this.status=t?.status??i.status??500;let r=t?.code??i.code;r!==void 0&&(this.code=r);let s=t?.help??i.help;s!==void 0&&(this.help=s),Error.captureStackTrace(this,i)}setHelp(e){return this.help=e,this}setCode(e){return this.code=e,this}setStatus(e){return this.status=e,this}get[Symbol.toStringTag](){return this.constructor.name}toString(){return this.code?`${this.name} [${this.code}]: ${this.message}`:`${this.name}: ${this.message}`}toJSON(){let e={name:this.name,message:this.message};return this.status&&(e.status=this.status),this.code&&(e.code=this.code),this.help&&(e.help=this.help),e}};var G="Invalid JSON response.",B="The response has no value.",C="Invalid response status: ",X="Unknown response from the server.";var me=class{sdk;constructor(e){this.sdk=e}logInvalidResponse(e){if(!this.sdk.silent&&e.body)try{let t=JSON.parse(e.body);t.message&&console.warn(`[Store message]: ${t.message}`)}catch{}}inspectCommonStatusCodes(e){let{status:t,body:i}=e;if(t===404){let r=this.createApiError("Not found",i);throw r.status!==404&&r.setStatus(404),r.code!=="E_NOT_FOUND"&&r.setCode("E_NOT_FOUND"),r}if(t===403){let r=this.createApiError("You have no access to this resource",i);throw r.status!==403&&r.setStatus(403),r.code!=="E_FORBIDDEN"&&r.setCode("E_FORBIDDEN"),r}if(t===401){this.sdk.dispatchEvent(new Event("unauthorized"));let r=this.createApiError("Not authorized",i);throw r.status!==401&&r.setStatus(401),r.code!=="E_UNAUTHORIZED"&&r.setCode("E_UNAUTHORIZED"),r}}createApiError(e,t){if(!t)return new b(e);let i;try{i=JSON.parse(t)}catch{return new b(e)}return!i||typeof i!="object"||!i.message?new b(e):b.fromRawException(i,e)}async genericBatchDelete(e,t,i={}){let{token:r}=i,s=await this.sdk.http.post(e.toString(),{token:r,body:JSON.stringify(t)});this.inspectCommonStatusCodes(s);let o="Unable to delete in batch. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async genericDelete(e,t={}){let{token:i}=t,r=await this.sdk.http.delete(e.toString(),{token:i});this.inspectCommonStatusCodes(r);let s="Unable to delete the object. ";if(r.status!==204)throw this.logInvalidResponse(r),this.createApiError(`${s}${C}${r.status}`,r.body)}async genericList(e,t,i={}){let{token:r}=i;this.sdk.appendListOptions(e,t);let s=await this.sdk.http.get(e.toString(),{token:r});this.inspectCommonStatusCodes(s);let o="Unable to list revisions for a file. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}readResponseBody(e,t){if(![200,202].includes(e.status))throw this.logInvalidResponse(e),this.createApiError(`${t}${C}${e.status}`,e.body);if(!e.body)throw new b(`${t}${B}`,{code:"E_RESPONSE_NO_VALUE",status:e.status});return e.body}readResponseJSON(e,t){let i=this.readResponseBody(e,t),r;try{r=JSON.parse(i)}catch{throw new b(`${t}${G}`,{code:"E_INVALID_JSON",status:e.status})}return r}processListResponse(e,t){this.inspectCommonStatusCodes(e);let i=this.readResponseJSON(e,t);if(!Array.isArray(i.data))throw new b(`${t}${X}`,{code:"E_RESPONSE_UNKNOWN",status:e.status});return i}assertObjectKind(e,t,i){if(t!==i)throw new b(`${e}${X}`,{code:"E_RESPONSE_UNKNOWN",status:500})}};var Pi=class extends Error{status;response;constructor(e,t){super(`HTTP Error: ${e}`),this.status=e,this.response=t}},zs=class extends me{logRequest(e,t,i){if(!this.sdk.logger)return;let r=i?.headers||{},s={};for(let[l,d]of Object.entries(r))s[l]=Zn(l,d);(i?.token||this.sdk.token)&&!s.authorization&&!s.Authorization&&(s.Authorization="Bearer **********");let a=i?.body,n=Qn(a);this.sdk.logger.log("debug",`--> HTTP ${e} ${t}`),Object.keys(s).length>0&&this.sdk.logger.log("debug",`Headers: ${JSON.stringify(s,null,2)}`),n&&this.sdk.logger.log("debug",`Body: ${n}`)}logResponse(e,t,i){if(!this.sdk.logger)return;let r=i.headers?i.headers.toJSON():{},s={};for(let[a,n]of Object.entries(r))s[a]=Zn(a,n);let o=Qn(i.body);this.sdk.logger.log("debug",`<-- HTTP ${i.status} ${e} ${t}`),Object.keys(s).length>0&&this.sdk.logger.log("debug",`Headers: ${JSON.stringify(s,null,2)}`),o&&this.sdk.logger.log("debug",`Body: ${o}`)}logError(e,t,i){if(!this.sdk.logger)return;let r=i instanceof Error?i.message:String(i);this.sdk.logger.log("debug",`<-- HTTP ${e} ${t} Failed: ${r}`)}};function Np(c,e=1e3){return globalThis.__MOCK_RETRY_DELAY_MS__!==void 0?globalThis.__MOCK_RETRY_DELAY_MS__:c<=0?e:e*Math.pow(2,c-1)}function Tp(c){let{status:e}=c;return!(typeof e=="number"&&e>=400&&e<500)}async function ec(c,e={}){let{retries:t=3,delayMs:i=Np,shouldRetry:r=Tp}=e,s;for(let a=0;a<t;a++)try{return await c()}catch(n){if(s=n,!r(s)||a===t-1)throw s;let l=typeof i=="function"?i(a+1):i;l>0&&await new Promise(d=>setTimeout(d,l))}throw s||new Error("Retry operation failed without a specific error.")}var Vs=class extends zs{async get(e,t={}){let i=async()=>{this.logRequest("GET",e,t);try{let r=await this._get(e,t);if(this.logResponse("GET",e,r),[301,302,308,307].includes(r.status)){let s=r.headers.get("location");if(!s)throw new Error('Expected redirection but no "location" header.');let o=new URL(s,e);return this.get(o.toString(),t)}if(t.retry&&r.status>=400)throw new Pi(r.status,r);return r}catch(r){throw this.logError("GET",e,r),r}};if(t.retry)try{let r=typeof t.retry=="object"?t.retry:{};return await ec(i,r)}catch(r){if(r instanceof Pi)return r.response;throw r}return i()}_get(e,t={}){return new Promise((i,r)=>{let{method:s="GET",headers:o={},token:a=this.sdk.token}=t,n={...o};a&&(n.authorization=`Bearer ${a}`);let p=(e.startsWith("https:")?fl:hl).request(e,{method:s,headers:n,rejectUnauthorized:!1});p.on("response",m=>{let h={status:m.statusCode,headers:new Ir(m.headers),body:""};m.on("data",f=>{h.body+=f}),m.on("end",()=>i(h))}),p.on("error",m=>r(m)),p.end()})}async post(e,t={}){let i=t.method||"POST",r=async()=>{this.logRequest(i,e,t);let s=await new Promise((o,a)=>{let{headers:n={},token:l=this.sdk.token}=t,d={...n};l&&(d.authorization=`Bearer ${l}`),t.body&&!d["content-type"]&&!d["Content-Type"]&&(d["content-type"]="application/json");let h=(e.startsWith("https:")?fl:hl).request(e,{method:i,headers:d});h.on("response",f=>{let k={status:f.statusCode,headers:new Ir(f.headers),body:""};f.on("data",w=>{k.body+=w}),f.on("end",()=>{this.logResponse(i,e,k),o(k)})}),h.on("error",f=>{this.logError(i,e,f),a(f)}),t.body&&h.write(t.body),h.end()});if(t.retry&&s.status>=400)throw new Pi(s.status,s);return s};if(t.retry)try{let s=typeof t.retry=="object"?t.retry:{};return await ec(r,s)}catch(s){if(s instanceof Pi)return s.response;throw s}return r()}patch(e,t={}){let i={...t,method:"PATCH"};return this.post(e,i)}put(e,t={}){let i={...t,method:"PUT"};return this.post(e,i)}delete(e,t={}){let i={...t,method:"DELETE"};return this.post(e,i)}};var T=class c{static folders(e){return`/v1/orgs/${e}/folders`}static files(e){return`/v1/orgs/${e}/files`}static filesSearch(e){return`${c.files(e)}/search`}static filesAccess(e,t){return`${c.file(e,t)}/access`}static filesBatch(e){return`${c.files(e)}/batch/read-meta`}static file(e,t){return`${c.files(e)}/${t}`}static fileMedia(e,t){return`${c.file(e,t)}/media`}static fileUsers(e,t){return`${c.file(e,t)}/users`}static fileRevisions(e,t){return`${c.file(e,t)}/revisions`}static fileBreadcrumbs(e,t){return`${c.file(e,t)}/breadcrumbs`}static fileRename(e,t){return`${c.file(e,t)}/rename`}static history(){return"/history"}static historyBatchCreate(){return"/history/batch/create"}static historyBatchDelete(){return"/history/batch/delete"}static historyItem(e){return`/history/${e}`}static historyClear(e,...t){return`/history/clear/${e}/${t.join("/")}`}static shared(e){return`/v1/orgs/${e}/shared`}static trash(e){return`/v1/orgs/${e}/trash`}static trashItem(e,t){return`${c.trash(e)}/${t}`}static trashRestore(e,t){return`${c.trashItem(e,t)}/restore`}static trashEmpty(e){return`${c.trash(e)}/empty`}static trashBatchRestore(e){return`${c.trash(e)}/restore`}static trashBatchDelete(e){return`${c.trash(e)}/delete`}static projectExecutions(){return"/project/execution"}static projectExecution(e){return`/project/execution/${e}`}static projectExecutionBulkDelete(){return"/project/execution/delete"}static projectExecutionClear(e){return`/project/execution/clear/${e}`}static organizations(){return"/v1/orgs"}static organization(e){return`/v1/orgs/${e}`}static organizationUsers(e){return`${this.organization(e)}/users`}static organizationUserBatch(e){return`${this.organization(e)}/users/batch/read`}static organizationUser(e,t){return`${this.organization(e)}/users/${t}`}static organizationUserDeactivate(e,t){return`${this.organization(e)}/users/${t}/deactivate`}static organizationUserActivate(e,t){return`${this.organization(e)}/users/${t}/activate`}static invitations(e){return`${this.organization(e)}/invitations`}static invitation(e,t){return`${this.invitations(e)}/${t}`}static findInvitation(){return`${this.organizations()}/find-invitation`}static declineInvitation(e,t){return`${this.invitation(e,t)}/decline`}static resendInvitation(e,t){return`${this.invitation(e,t)}/resend`}static authGoogle(){return"/auth/google"}static authLogout(){return"/auth/logout"}static usersMe(){return"/v1/users/me"}static usersMeTokens(){return`${c.usersMe()}/tokens`}static usersMeToken(e){return`${c.usersMeTokens()}/${e}`}static dataCatalog(){return"/v1/datacatalog"}static dataCatalogStatus(e){return`${c.dataCatalog()}/status/${e}`}static dataCatalogEntry(e){return`${c.dataCatalog()}/${e}`}static dataCatalogEntryVersions(e){return`${c.dataCatalogEntry(e)}/versions`}static dataCatalogDependencies(){return`${c.dataCatalog()}/dependencies`}static dataCatalogUpdates(){return`${c.dataCatalog()}/updates`}static dataCatalogVersion(e,t){return`${c.dataCatalogEntry(e)}/${t}`}static dataCatalogDeprecate(e){return`${c.dataCatalogEntry(e)}/deprecate`}static dataCatalogUnpublish(e){return`${c.dataCatalogEntry(e)}/unpublish`}static dataCatalogVersionDeprecate(e,t){return`${c.dataCatalogVersion(e,t)}/deprecate`}static dataCatalogVersionUnpublish(e,t){return`${c.dataCatalogVersion(e,t)}/unpublish`}static dataCatalogUsage(e){return`${c.dataCatalogEntry(e)}/apis`}static dataCatalogVersionUsage(e,t){return`${c.dataCatalogVersion(e,t)}/apis`}static groups(e){return`/v1/orgs/${e}/groups`}static group(e,t){return`/v1/orgs/${e}/groups/${t}`}static groupUsers(e,t){return`/v1/orgs/${e}/groups/${t}/users`}static aiModifyDomain(e,t){return`${this.organization(e)}/ai/domains/${t}/modify/stream`}static aiModifyApi(e,t){return`${this.organization(e)}/ai/apis/${t}/modify/stream`}static aiSessions(e,t){return`${this.organization(e)}/ai/sessions/${t}`}static aiSession(e,t,i){return`${c.aiSessions(e,t)}/${i}`}static aiMessages(e,t){return`${this.organization(e)}/ai/messages/${t}`}static aiMessage(e,t,i){return`${c.aiMessages(e,t)}/${i}`}static orgSlugGenerate(){return"/v1/orgs/slugs/generate"}static orgSlugValidate(){return"/v1/orgs/slugs/validate"}static deployments(e){return`/v1/orgs/${e}/deployments`}static deploymentsApis(e){return`${c.deployments(e)}/apis`}static deployment(e,t){return`${c.deployments(e)}/${t}`}static deploymentsForApi(e,t){return`${c.deploymentsApis(e)}/${t}`}static deploymentsApisByEnvLatest(e,t){return`${c.deploymentsApis(e)}/${t}/environments/latest`}static rollback(e,t){return`${c.deployment(e,t)}/rollback`}static deploymentDeactivate(e,t){return`${c.deployment(e,t)}/deactivate`}static deploymentOas(e,t){return`${c.deployment(e,t)}/oas`}static deploymentsApiRuntimeUsersUpdate(e,t){return`${c.deploymentsApis(e)}/${t}/runtime/users/update`}static job(e,t){return`/v1/orgs/${e}/jobs/${t}`}};var Fs=class extends me{oauthRedirect(e,t={}){let{redirect:i,token:r,type:s="redirect"}=t,o=new URL(this.sdk.baseUri);if(!["google","github","linkedin"].includes(e))throw new Error(`Invalid provider: ${e}`);let a=new URL(`/auth/${e}/redirect`,o);return i&&a.searchParams.set("r",i),r&&a.searchParams.set("token",r),s==="redirect"?(window.location.href=a.toString(),null):window.open(a.toString(),"_blank")}async logout(e={}){let{token:t,retry:i=!0}=e,r=this.sdk.getUrl(T.authLogout()),s=await this.sdk.http.post(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to log out. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body)}};import{customAlphabet as jp}from"nanoid";var W=jp("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var Tt="Core#Permission",Nt=["reader","commenter","writer","owner"],oi=class c{kind=Tt;key="";type="user";granteeId="";role="reader";displayName;expirationTime;addingUser="";itemId="";depth=0;sourceRule="direct_user_grant";static fromUserRole(e,t,i,r){let s={key:W(),kind:Tt,itemId:t,granteeId:i,role:e,type:"user",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new c(s)}static fromGroupRole(e,t,i,r){let s={key:W(),kind:Tt,itemId:t,granteeId:i,role:e,type:"group",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new c(s)}static fromOrganizationRole(e,t,i,r){let s={key:W(),kind:Tt,itemId:t,granteeId:i,role:e,type:"organization",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new c(s)}static fromValues(e){return new c({...e,key:W(),kind:Tt})}constructor(e){let t;typeof e=="string"?t=JSON.parse(e):typeof e=="object"?t=e:t={kind:Tt,key:W(),granteeId:"",itemId:"",role:"reader",type:"user",addingUser:"",depth:0,sourceRule:"direct_user_grant"},this.new(t)}new(e){if(!c.isPermission(e))throw new Error("Not a permission.");let{key:t=W(),granteeId:i,role:r,type:s,displayName:o,expirationTime:a,addingUser:n,itemId:l,depth:d,sourceRule:p}=e;this.kind=Tt,this.key=t,this.granteeId=i,this.itemId=l,this.role=r,this.type=s,this.addingUser=n,this.depth=d||0,this.sourceRule=p||"direct_user_grant",o?this.displayName=o:this.displayName=void 0,typeof a=="number"?this.expirationTime=a:this.expirationTime=void 0}static isPermission(e){return!(!e||e.kind!==Tt)}static hasRole(e,t){if(!t)return!1;let i=Nt.indexOf(t),r=Nt.indexOf(e);return i>=r}static isHigherRole(e,t){let i=Nt.indexOf(e),r=Nt.indexOf(t);return i>r}hasRole(e){return c.hasRole(e,this.role)}static hasRoleIn(e,t){if(!t||!t.length)return!1;let i=[...t].sort((n,l)=>n.depth-l.depth),r=i[0].depth,s=i.filter(n=>n.depth===r),o,a=s.filter(n=>n.type==="user");if(a.length)o=a.sort((n,l)=>Nt.indexOf(l.role)-Nt.indexOf(n.role))[0];else{let n=s.filter(l=>l.type==="group");if(n.length)o=n.sort((l,d)=>Nt.indexOf(d.role)-Nt.indexOf(l.role))[0];else{let l=s.filter(d=>d.type==="organization");l.length&&(o=l.sort((d,p)=>Nt.indexOf(p.role)-Nt.indexOf(d.role))[0])}}return o?c.hasRole(e,o.role):!1}toJSON(){let e={kind:Tt,key:this.key,role:this.role,type:this.type,addingUser:this.addingUser,granteeId:this.granteeId,itemId:this.itemId,depth:this.depth,sourceRule:this.sourceRule};return this.displayName&&(e.displayName=this.displayName),this.expirationTime&&(e.expirationTime=this.expirationTime),e}};var ai="Core#Thing",ot="Core#Folder";var Pr="Core#User",ni="Data#DomainFile",Ee="Data#Domain",Le="Domain#Namespace",Oe="Domain#Model",O="Domain#Entity",se="Domain#Association",be="Domain#Property",wt="Core#DataCatalog",Wt="Core#DataCatalogVersion";var Ri="Core#Deployment",ke="Core#ApiModel",Ht="Core#ExposedEntity",Yt="Core#ApiFile";var Rr="Core#AiSession",tc="Core#AiMessage",ic="Core#Job";var he=class c{kind=ai;name;displayName;description;version;static fromName(e){return new c({name:e,kind:ai})}static fromJSON(e={},t={}){let i=new c,{name:r,displayName:s,description:o,version:a}=e||{};return typeof r=="string"?i.name=r:typeof t.name=="string"&&(i.name=t.name),typeof s=="string"?i.displayName=s:typeof t.displayName=="string"&&(i.displayName=t.displayName),o?i.description=o:typeof t.description=="string"&&(i.description=t.description),a?i.version=a:typeof t.version=="string"&&(i.version=t.version),i}constructor(e){let t;typeof e=="string"?t=JSON.parse(e):typeof e=="object"?t=e:t={kind:ai},this.new(t)}new(e){if(!c.isThing(e))throw new Error("Not a thing.");let{description:t,name:i,version:r,displayName:s}=e;this.kind=ai,this.name=i,this.displayName=s,this.description=t,this.version=r}static validate(e,t={}){let{strict:i}=t;return e&&typeof e=="object"?!(i&&e.kind!==ai):!1}static isThing(e){return!!(e&&e.kind===ai)}toJSON(){let e={kind:ai};return typeof this.name=="string"&&(e.name=this.name),typeof this.displayName=="string"&&(e.displayName=this.displayName),this.description&&(e.description=this.description),this.version&&(e.version=this.version),e}getLabel(e){return this.displayName||this.name||e||"Unnamed object"}};var rc=Symbol("parents"),qs=Symbol("deleted"),Ks=Symbol("deletedInfo"),Bs=Symbol("lastModified"),sc=Symbol("capabilities"),oc=Symbol("permissions"),ac=Symbol("permissionIds"),nc=Symbol("shortcutTarget"),$r=class{kind="";key="";info=he.fromName("");iconColor;get isShortcut(){return!!this.shortcutTarget}[nc];get shortcutTarget(){return this[nc]}set shortcutTarget(e){this[nc]=e}static createSchema(e={}){let{key:t=W(),kind:i,iconColor:r,shortcutTarget:s}=e,o={key:t,kind:i||"",info:he.fromJSON(e.info,{name:"Unnamed file"}).toJSON()};return r&&(o.iconColor=r),s&&(o.isShortcut=!0,o.shortcutTarget=s),o}constructor(e){this.kind=e.kind,this.key=e.key,this.info=new he(e.info),e.iconColor&&(this.iconColor=e.iconColor),e.shortcutTarget&&(this.shortcutTarget=e.shortcutTarget)}toJSON(){let e={key:this.key,kind:this.kind,info:this.info.toJSON()};return this.iconColor&&(e.iconColor=this.iconColor),this.shortcutTarget&&(e.isShortcut=!0,e.shortcutTarget=this.shortcutTarget),e}static createFileCapabilities(e,t){let i=oi.hasRole("commenter",t),r=oi.hasRole("owner",t),s=oi.hasRole("reader",t),o=oi.hasRole("writer",t),a=e.kind===ot;return{canReadMedia:!a&&s,canListChildren:a&&s,canComment:!a&&i,canEditMedia:!a&&o,canEditMeta:o,canReadRevisions:o,canAddChildren:a&&o,canDelete:r,canTrash:r,canUntrash:r,canShare:o,canMove:o}}createFileCapabilities(e){return Xt.createFileCapabilities(this,e)}static updateByMeMeta(e,t){e.deletedInfo&&(e.deletedInfo.byMe=e.deletedInfo.user===t),e.lastModified&&(e.lastModified.byMe=e.lastModified.user===t)}static setLastModified(e,t){if(!e)throw new Error("The file is required.");if(!t)throw new Error("The user is required.");if(t.kind!==Pr)throw new Error('Invalid value for the user when setting "lastModified".');return e.lastModified={byMe:!1,time:Date.now(),user:t.key,name:t.name},e}static setDeleted(e,t){if(!e)throw new Error("The file is required.");if(!t)throw new Error("The user is required.");if(t.kind!==Pr)throw new Error('Invalid value for the user when setting "deletedInfo".');return e.deleted=!0,e.deletedInfo={byMe:!1,time:Date.now(),user:t.key,name:t.name},e}},Xt=class c extends $r{[rc]=[];get parents(){return this[rc]}[ac]=[];get permissionIds(){return this[ac]}[qs];get deleted(){return this[qs]||!1}[Ks];get deletedInfo(){return this[Ks]}[Bs]={user:"",time:0,byMe:!1};get lastModified(){return this[Bs]}labels;[sc];get capabilities(){return this[sc]}[oc]=[];get permissions(){return this[oc]}static createSchema(e={}){let t=$r.createSchema(e);return Array.isArray(e.parents)?t.parents=[...e.parents]:t.parents=[],Array.isArray(e.permissionIds)?t.permissionIds=[...e.permissionIds]:t.permissionIds=[],Array.isArray(e.permissions)?t.permissions=e.permissions.map(i=>({...i})):t.permissions=[],e.capabilities&&(t.capabilities={...e.capabilities}),e.lastModified?t.lastModified={...e.lastModified}:t.lastModified={user:"",time:0,byMe:!1},typeof e.deleted=="boolean"&&(t.deleted=e.deleted,t.deletedInfo=e.deletedInfo?{...e.deletedInfo}:void 0),Array.isArray(e.labels)&&(t.labels=[...e.labels]),typeof e.shortcutTarget=="string"&&(t.shortcutTarget=e.shortcutTarget),t}constructor(e){let t=c.createSchema(e);super(t),this[rc]=[...t.parents],this[ac]=[...t.permissionIds],this[oc]=t.permissions.map(i=>({...i})),this[sc]=t.capabilities?{...t.capabilities}:void 0,this[Bs]=Object.freeze({...t.lastModified}),typeof t.deleted=="boolean"&&(this[qs]=t.deleted,this[Ks]=t.deletedInfo?Object.freeze({...t.deletedInfo}):void 0),Array.isArray(t.labels)&&(this.labels=[...t.labels])}toJSON(){let e={...super.toJSON(),parents:[...this.parents],permissionIds:[...this.permissionIds],lastModified:{...this.lastModified},permissions:[...this.permissions]};return this.deleted&&(e.deleted=this.deleted,e.deletedInfo={...this.deletedInfo}),Array.isArray(this.labels)&&(e.labels=[...this.labels]),e}static fromName(e,t){return new c({kind:t,info:{name:e}})}shortcutTo(e){return this.shortcutTarget=e,this}setLastModified(e){if(!e)throw new Error("The user is required.");if(e.kind!==Pr)throw new Error('Invalid value for the user when setting "lastModified".');this[Bs]={byMe:!1,time:Date.now(),user:e.key,name:e.name}}addLabel(e){if(typeof e!="string")throw new Error("The label must be a string.");if(!e.trim())throw new Error("The label is required.");Array.isArray(this.labels)||(this.labels=[]),!this.labels.includes(e)&&this.labels.push(e)}setDeleted(e){if(!e)throw new Error("The user is required.");if(e.kind!==Pr)throw new Error('Invalid value for the user when setting "deletedInfo".');this[qs]=!0,this[Ks]={byMe:!1,time:Date.now(),user:e.key,name:e.name}}isFile(){return this.kind!==ot}isFolder(){return this.kind===ot}};var Or=class extends Xt{kind=ot;static fromName(e){return super.fromName(e,ot)}constructor(e){let t=Xt.createSchema(e);t.kind=ot,super(t)}static isFolder(e){return!(!e||e.kind!==ot)}toJSON(){return{...super.toJSON(),kind:ot}}};var Gs=class extends me{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o={...t},a=this.sdk.getUrl(T.files(e));this.sdk.appendListOptions(a,o);let n=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(n);let l="Unable to list files. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async search(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.filesSearch(e)),{searchParams:a}=o;if(t.cursor&&a.set("cursor",t.cursor),typeof t.limit=="number"&&a.set("limit",String(t.limit)),t.parent&&a.set("parent",t.parent),t.kind)for(let l of t.kind)a.append("kind",l);if(t.query)for(let l of t.query)a.append("query",l);let n=await this.sdk.http.get(o.toString(),{token:r,retry:s});return this.processListResponse(n,"Unable to search files. ")}async create(e,t,i,r={},s={}){let o=await this.createMeta(e,i,r,s);return await this.createMedia(t,i,o.key,r,s),o}async createMeta(e,t,i={},r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.files(t));i.parent&&a.searchParams.set("parent",i.parent);let n=JSON.stringify(e),l=await this.sdk.http.post(a.toString(),{token:s,body:n,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let d="Unable to create a file. ";if(l.status!==201)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async createMedia(e,t,i,r={},s={}){let{token:o=this.sdk.token,retry:a=!0}=s,n=T.fileMedia(t,i),l=this.sdk.getUrl(n),d=r.mime||"application/json",p;d.includes("json")?p=JSON.stringify(e):p=String(e);let m=await this.sdk.http.put(l.toString(),{token:o,body:p,retry:a,headers:{"content-type":d}});this.inspectCommonStatusCodes(m);let h="Unable to create a file. ";if(m.status!==200)throw this.logInvalidResponse(m),this.createApiError(`${h}${C}${m.status}`,m.body)}async createFolder(e,t,i={},r={}){let s=Or.fromName(e),{token:o=this.sdk.token,retry:a=!0}=r,n=this.sdk.getUrl(T.files(t));i.parent&&n.searchParams.set("parent",i.parent);let l=JSON.stringify(s),d=await this.sdk.http.post(n.toString(),{token:o,body:l,retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(d);let p="Unable to create a file. ";if(d.status!==201)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}if(!m.key)throw new b(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:d.status});return m}async read(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.file(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read a file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async readMedia(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.fileMedia(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read a file media. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l||typeof l!="object"||!("data"in l)||!("meta"in l))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});let{data:d,meta:p}=l;if(!p||typeof p!="object"||typeof p.version!="number"||typeof p.updated!="number"||isNaN(p.version)||isNaN(p.updated))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return{media:d,meta:p}}async readBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.filesBatch(e)),a=JSON.stringify({ids:t}),n=await this.sdk.http.post(o.toString(),{token:r,body:a,retry:s});this.inspectCommonStatusCodes(n);let l="Unable to read files in bulk. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async patch(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=T.file(e,t),n=this.sdk.getUrl(a),l=JSON.stringify(i),d=await this.sdk.http.patch(n.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(d);let p="Unable to patch a file. ";if(d.status!==200)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}if(!m.kind)throw new b(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:d.status});return m}async patchMedia(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=T.fileMedia(e,t),n=this.sdk.getUrl(a),l=JSON.stringify(i),d=await this.sdk.http.patch(n.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(d);let p="Unable to patch a file contents. ";if(d.status!==200)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}return m}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.file(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to trash a file. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async deleteBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.files(e)),a=await this.sdk.http.delete(o.toString(),{token:r,body:JSON.stringify({ids:t}),retry:s});this.inspectCommonStatusCodes(a);let n="Unable to trash files. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async patchUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.filesAccess(e,t)),n=JSON.stringify(i),l=await this.sdk.http.patch(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to patch the file. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async addUser(e,t,i,r,s,o){let a={op:"add",type:"user",value:r,id:i};typeof s=="number"&&(a.expirationTime=s);let n={patch:[a],id:W()};return this.patchUsers(e,t,n,o)}async removeUser(e,t,i,r){let o={patch:[{op:"remove",type:"user",id:i}],id:W()};return this.patchUsers(e,t,o,r)}async listUsers(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.fileUsers(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list users in the file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async breadcrumbs(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.fileBreadcrumbs(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read breadcrumbs. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async rename(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.fileRename(e,t)),n=await this.sdk.http.put(a.toString(),{token:s,body:JSON.stringify({name:i}),retry:o});this.inspectCommonStatusCodes(n);let l="Unable to rename file. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}return d}};var Js=class extends me{async me(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(T.usersMe()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to read a user. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!a.key)throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async listTokens(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(T.usersMeTokens()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to list tokens. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}return a}async createToken(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.usersMeTokens()),o=JSON.stringify(e),a=await this.sdk.http.post(s.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to create a token. ";if(a.status!==200&&a.status!==201)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l}async deleteToken(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.usersMeToken(e)),o=await this.sdk.http.delete(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to delete a token. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body)}};var Ws=class extends me{async list(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.shared(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list shared files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}};var Hs=class extends me{async list(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.fileRevisions(e,t));this.sdk.appendListOptions(a,i);let n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to list revisions for a file. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}};var Ys=class extends me{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.trash(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list trash. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}async delete(e,t,i={}){let r=T.trashBatchDelete(e),s=this.sdk.getUrl(r),{token:o=this.sdk.token,retry:a=!0}=i,n=await this.sdk.http.delete(s.toString(),{token:o,body:JSON.stringify({ids:t}),retry:a});this.inspectCommonStatusCodes(n);let l="Unable to delete trash. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body)}async restore(e,t,i={}){let r=this.sdk.getUrl(T.trashBatchRestore(e)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,body:JSON.stringify({ids:t}),retry:o});this.inspectCommonStatusCodes(a);let n="Unable to restore from trash. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async empty(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.trashEmpty(e)),o=await this.sdk.http.delete(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to empty trash. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body)}};var Xs=class extends me{async list(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(T.organizations()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let o="Unable to list your organizations. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${o}${C}${s.status}`,s.body);if(!s.body)throw new b(`${o}${B}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new b(`${o}${G}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new b(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizations()),a={name:e,slug:t},n=await this.sdk.http.post(o.toString(),{body:JSON.stringify(a),token:r,headers:{"Content-Type":"application/json"},retry:s});this.inspectCommonStatusCodes(n);let l="Unable to create an organization. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.kind)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}invitations={list:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.invitations(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to list organization invitations. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);if(!o.body)throw new b(`${a}${B}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let n;try{n=JSON.parse(o.body)}catch{throw new b(`${a}${G}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(n.data))throw new b(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return n},create:async(e,t,i,r,s={})=>{let{token:o=this.sdk.token,retry:a=!0}=s,n=this.sdk.getUrl(T.invitations(e)),l={email:t,name:r,grant_type:i},d=await this.sdk.http.post(n.toString(),{body:JSON.stringify(l),token:o,headers:{"Content-Type":"application/json"},retry:a});this.inspectCommonStatusCodes(d);let p="Unable to create an invitation. ";if(d.status!==200)throw this.logInvalidResponse(d),this.createApiError(`${p}${C}${d.status}`,d.body);if(!d.body)throw new b(`${p}${B}`,{code:"E_RESPONSE_NO_VALUE",status:d.status});let m;try{m=JSON.parse(d.body).data}catch{throw new b(`${p}${G}`,{code:"E_INVALID_JSON",status:d.status})}if(!m.kind)throw new b(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:d.status});return m},findByToken:async(e,t={})=>{let i=this.sdk.getUrl(T.findInvitation());i.searchParams.append("token",e);let{retry:r=!0,token:s}=t,o=await this.sdk.http.get(i.toString(),{token:s,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to find invitation by token. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);if(!o.body)throw new b(`${a}${B}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let n;try{n=JSON.parse(o.body).data}catch{throw new b(`${a}${G}`,{code:"E_INVALID_JSON",status:o.status})}if(!n.kind)throw new b(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return n},decline:async(e,t,i={})=>{let r=this.sdk.getUrl(T.declineInvitation(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to decline invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},delete:async(e,t,i={})=>{let r=this.sdk.getUrl(T.invitation(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.delete(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to delete invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},patch:async(e,t,i,r={})=>{let s=this.sdk.getUrl(T.invitation(e,t)),{token:o=this.sdk.token,retry:a=!0}=r,n=await this.sdk.http.patch(s.toString(),{body:JSON.stringify(i),token:o,headers:{"Content-Type":"application/json"},retry:a});this.inspectCommonStatusCodes(n);let l="Unable to update invitation. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.kind)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},resend:async(e,t,i={})=>{let r=this.sdk.getUrl(T.resendInvitation(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.put(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to resend invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}};users={list:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUsers(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to list projects. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},read:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUser(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read the user info. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l},readBatch:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUserBatch(e)),a={ids:t},n=await this.sdk.http.post(o.toString(),{body:JSON.stringify(a),token:r,retry:s});this.inspectCommonStatusCodes(n);let l="Unable to read the user batch info. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},activate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUserActivate(e,t)),a=await this.sdk.http.post(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to activate the user. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l},deactivate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUserDeactivate(e,t)),a=await this.sdk.http.post(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to deactivate the user. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}return l},delete:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.organizationUser(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to delete the user. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}};slugs={generate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.orgSlugGenerate()).toString(),o={name:e},a=await this.sdk.http.post(s,{body:JSON.stringify(o),token:i,retry:r});this.inspectCommonStatusCodes(a);let n="Unable to generate the slug. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.slug)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l.slug},validate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.orgSlugValidate()).toString(),o={slug:e},a=await this.sdk.http.post(s,{body:JSON.stringify(o),token:i,retry:r});this.inspectCommonStatusCodes(a);let n="Unable to validate the slug. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);if(!a.body)throw new b(`${n}${B}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new b(`${n}${G}`,{code:"E_INVALID_JSON",status:a.status})}if(typeof l.valid!="boolean")throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l}}};var Zs=class extends me{async list(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s={...e},o=this.sdk.getUrl(T.dataCatalog());this.sdk.appendListOptions(o,s),s.scope&&o.searchParams.set("scope",s.scope);let a=await this.sdk.http.get(o.toString(),{token:i,retry:r});return this.processListResponse(a,"Unable to list data domains. ")}async listVersions(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogEntryVersions(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});return this.processListResponse(o,"Unable to list data domain versions. ")}async publish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalog()),o=JSON.stringify(e),a=await this.sdk.http.post(s.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to publish data domain. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,wt,l.kind),l}async read(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogEntry(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to read data domain. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);let n=this.readResponseJSON(o,a).data;return this.assertObjectKind(a,wt,n.kind),n}async deprecate(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogDeprecate(e)),a=JSON.stringify({reason:t}),n=await this.sdk.http.put(o.toString(),{token:r,body:a,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(n);let l="Unable to deprecate data domain. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);let d=this.readResponseJSON(n,l).data;return this.assertObjectKind(l,wt,d.kind),d}async unpublish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogUnpublish(e)),o=await this.sdk.http.put(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to unpublish data domain. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);let n=this.readResponseJSON(o,a).data;return this.assertObjectKind(a,wt,n.kind),n}async publishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogEntryVersions(e)),a=JSON.stringify(t),n=await this.sdk.http.post(o.toString(),{token:r,body:a,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(n);let l="Unable to publish data domain version. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);let d=this.readResponseJSON(n,l).data;return this.assertObjectKind(l,Wt,d.kind),d}async readVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogVersion(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to read data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Wt,l.kind),l}async listDependencies(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogDependencies()),o=JSON.stringify({items:e}),a=await this.sdk.http.post(s.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(a,"Unable to list data domain dependencies. ")}async checkUpdates(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=e.map(l=>({fid:l.key,version:l.version})),o=this.sdk.getUrl(T.dataCatalogUpdates()),a=JSON.stringify({dependencies:s}),n=await this.sdk.http.post(o.toString(),{token:i,body:a,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(n,"Unable to check for data domain updates. ")}async deprecateVersion(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.dataCatalogVersionDeprecate(e,t)),n=JSON.stringify({reason:i}),l=await this.sdk.http.put(a.toString(),{token:s,body:n,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let d="Unable to deprecate data domain version. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);let p=this.readResponseJSON(l,d).data;return this.assertObjectKind(d,Wt,p.kind),p}async unpublishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogVersionUnpublish(e,t)),a=await this.sdk.http.put(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to unpublish data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Wt,l.kind),l}async checkPublicationStatus(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogStatus(e));t&&o.searchParams.set("oid",t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to check data domain publication status. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,wt,l.kind),l}async getUsageFiles(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(T.dataCatalogUsage(e)),o=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(o);let a="Unable to get data catalog usage files. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${a}${C}${o.status}`,o.body);return this.processListResponse(o,a)}async getVersionUsageFiles(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.dataCatalogVersionUsage(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to get data catalog version usage files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);return this.processListResponse(a,n)}};var Qs=class extends me{async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.groups(e)),a=JSON.stringify(t),n=await this.sdk.http.post(o.toString(),{token:r,body:a,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(n);let l="Unable to create a group. ";if(n.status!==201)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.key)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.groups(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to create a group. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(n+C+a.status,a.body);if(!a.body)throw new b(n+B,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new b(n+G,{code:"E_INVALID_JSON",status:a.status})}return l}async update(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.group(e,t.key)),a=JSON.stringify(t),n=await this.sdk.http.put(o.toString(),{token:r,body:a,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(n);let l="Unable to update a group. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!d.key)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.group(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let n="Unable to delete a group. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async addUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.groupUsers(e,t)),n=JSON.stringify({ids:i}),l=await this.sdk.http.post(a.toString(),{token:s,body:n,headers:{"content-type":"application/json"},retry:o});this.inspectCommonStatusCodes(l);let d="Unable to add users to a group. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async removeUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.groupUsers(e,t)),n=JSON.stringify({ids:i}),l=await this.sdk.http.delete(a.toString(),{token:s,body:n,headers:{"content-type":"application/json"},retry:o});this.inspectCommonStatusCodes(l);let d="Unable to remove users from a group. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}};var eo=class extends me{async*modifyDomain(e,t,i,r,s={}){let{token:o=this.sdk.token,signal:a}=s,n=this.sdk.getUrl(T.aiModifyDomain(e,t)),l=JSON.stringify({goal:i,sid:r}),d={method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${o}`},redirect:"follow",credentials:"include",body:l,signal:a},p=await fetch(n,d);if(!p.ok){let k=await p.text();throw new b(`Failed to modify domain: ${p.status} ${k}`)}let m=p.body?.getReader();if(!m)throw new b("Failed to get reader from response");let h=new TextDecoder,f="";for(;;){let{done:k,value:w}=await m.read();if(k)return;f+=h.decode(w,{stream:!0});let S;for(;(S=f.indexOf(`
|
|
17
17
|
|
|
18
18
|
`))>=0;){let E=f.slice(0,S);if(f=f.slice(S+2),!E.trim())continue;let A=E.split(`
|
|
19
|
-
`),_="message",O="";for(let j of A)j.startsWith("event:")?_=j.substring(6).trim():j.startsWith("data:")&&(O+=j.substring(5).trim());if(!O)continue;let I;try{I=JSON.parse(O)}catch{console.error("Failed to parse SSE JSON data:",O);continue}switch(_){case"user-message":yield{event:_,data:I};break;case"agent-message":yield{event:_,data:I};break;case"thought-chunk":case"text-chunk":yield{event:_,data:I};break;case"done":yield{event:_,data:I};return;case"error":yield{event:_,data:b.fromRawException(I,"Failed to generate results")};break;case"session-updated":yield{event:_,data:I};break;default:console.warn(`Unknown SSE event: ${_}`)}}}}sessions={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSessions(e,t));this.sdk.appendListOptions(a,i);let n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to list sessions. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},read:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSession(e,t,i)),n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to read session. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(d.kind!==Rr)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},create:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSessions(e,t)),n=JSON.stringify(i),l=await this.sdk.http.post(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to create session. ";if(l.status!==201)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==Rr)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSession(e,t,i)),n=await this.sdk.http.delete(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to delete session. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSession(e,t,i.key)),n=JSON.stringify(i),l=await this.sdk.http.put(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to update session. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==Rr)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}};messages={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiMessages(e,t));this.sdk.appendListOptions(a,i);let n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to list messages. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiMessage(e,t,i)),n=await this.sdk.http.delete(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to delete message. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiMessage(e,t,i.key)),n=JSON.stringify(i),l=await this.sdk.http.put(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to update message. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==tc)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}}};var Nr;(function(c){c.Pending="pending",c.Active="active",c.Inactive="inactive",c.Failed="failed"})(Nr||(Nr={}));var Hi;(function(c){c.PROD="prod",c.STAGING="staging",c.DEV="dev"})(Hi||(Hi={}));var to=class extends me{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.deployments(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});return this.processListResponse(a,"Unable to list deployments. ")}async create(e,t,i={}){if(t.env===Hi.PROD&&!t.version)throw new b(`Version must not be empty for production environment: ${t.env}`,{code:"INVALID_DEPLOYMENT_VERSION",help:"Please provide a version for production environment",status:400});if(t.env!==Hi.PROD&&t.version)throw new b(`Version must not be present for non-production environment: ${t.env}`,{code:"INVALID_DEPLOYMENT_VERSION",help:"Please remove the version for non-production environment",status:400});let r=this.sdk.getUrl(T.deployments(e)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,body:JSON.stringify(t),retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to create a deployment. ";if(a.status!==202)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async read(e,t,i={}){let r=this.sdk.getUrl(T.deployment(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to read a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async update(e,t,i,r={}){let s=this.sdk.getUrl(T.deployment(e,t)),{token:o=this.sdk.token,retry:a=!0}=r,n=await this.sdk.http.patch(s.toString(),{token:o,body:JSON.stringify(i),retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(n);let l="Unable to update deployment configuration. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);let d=this.readResponseJSON(n,l).data;return this.assertObjectKind(l,Ri,d.kind),d}async deactivate(e,t,i={}){let r=this.sdk.getUrl(T.deploymentDeactivate(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to deactivate a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async delete(e,t,i={}){let r=this.sdk.getUrl(T.deployment(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.delete(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to delete a deployment. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async rollback(e,t,i={}){let r=this.sdk.getUrl(T.rollback(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to rollback a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async oas(e,t,i={}){let r=this.sdk.getUrl(T.deploymentOas(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o,headers:{Accept:"application/vnd.oai.openapi+json, application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to retrieve OAS model. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);return this.readResponseJSON(a,n).data}apis={getLatestPerEnvironment:async(e,t,i={})=>{let r=this.sdk.getUrl(T.deploymentsApisByEnvLatest(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to list latest deployments for an API. ",l=this.readResponseJSON(a,n);if(!l.data)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},list:async(e,t={})=>{let i=this.sdk.getUrl(T.deploymentsApis(e)),{token:r=this.sdk.token,retry:s=!0}=t,o=await this.sdk.http.get(i.toString(),{token:r,retry:s});return this.processListResponse(o,"Unable to list APIs. ")},listDeployments:async(e,t,i={},r={})=>{let s=this.sdk.getUrl(T.deploymentsForApi(e,t));this.sdk.appendListOptions(s,i);let{token:o=this.sdk.token,retry:a=!0}=r,n=await this.sdk.http.get(s.toString(),{token:o,retry:a});return this.processListResponse(n,"Unable to list deployments. ")},updateRuntimeUser:async(e,t,i,r,s="production",o={})=>{let a=this.sdk.getUrl(T.deploymentsApiRuntimeUsersUpdate(e,t)),{token:n=this.sdk.token,retry:l=!0}=o,d=JSON.stringify({userId:i,properties:r,env:s}),p=await this.sdk.http.post(a.toString(),{token:n,body:d,retry:l,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(p);let m="Unable to update runtime user. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${m}${C}${p.status}`,p.body);if(!p.body)throw new b(`${m}${B}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});return this.readResponseJSON(p,m)}}};var cc;(function(c){c.Pending="pending",c.Running="running",c.Completed="completed",c.Failed="failed"})(cc||(cc={}));var io=class extends me{async checkStatus(e,t,i={}){let r=this.sdk.getUrl(T.job(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to check job status. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,ic,l.kind),l}};var lc=Symbol("baseUri"),ro=class extends EventTarget{basePath;#e;logger;get token(){return this.#e}set token(e){this.#e=e}auth=new Fs(this);files=new Gs(this);users=new Js(this);shared=new Ws(this);revisions=new Hs(this);trash=new Ys(this);organizations=new Xs(this);dataCatalog=new Zs(this);groups=new Qs(this);ai=new eo(this);deployments=new to(this);jobs=new io(this);silent=!1;[lc]="";get baseUri(){return this[lc]}set baseUri(e){if(!e)throw new Error("Invalid value for the baseUri");let t;try{t=new URL(e)}catch{throw new Error("Invalid baseUri: Not an URL")}this[lc]=t.origin;let{pathname:i}=t;i&&i!=="/"?this.basePath=i:this.basePath=void 0}constructor(e,t){super(),this.basePath=t,this.baseUri=e}getUrl(e="/"){if(e.startsWith("http:")||e.startsWith("https:"))return new URL(e);let{baseUri:t,basePath:i=""}=this,r=e;return i&&r.startsWith(i)&&(r=r.substring(i.length)),new URL(`${i}${r}`,t)}appendListOptions(e,t={}){let{searchParams:i}=e;if(t.cursor&&i.set("cursor",t.cursor),typeof t.limit=="number"&&i.set("limit",String(t.limit)),t.parent&&i.set("parent",t.parent),t.since&&i.set("since",String(t.since)),t.sort&&i.set("sort",String(t.sort)),t.order&&i.set("order",String(t.order)),t.oid&&i.set("oid",String(t.oid)),t.uid&&i.set("uid",String(t.uid)),t.filter){let r=new TextEncoder().encode(JSON.stringify(t.filter)),s=Array.from(r,o=>String.fromCodePoint(o)).join("");i.set("filter",btoa(s))}}};var so=class extends ro{http=new Vs(this)};function F(c={}){let e=N.resolved,t=c.apiUrl||e.apiUrl,i=new so(t);return e.token&&(i.token=e.token),i.logger=y,i}function U(c){if(c&&typeof c=="object"){let t=c,i=t.status,r=t.code,s=t.message||"An unknown error occurred.",o=t.help;return i===401?(s="Unauthorized. Please login using `auth login`.",{message:s,status:i,code:"CLI_ERR_UNAUTHORIZED",help:o}):i===403?(s=t.message||"Forbidden. You do not have permission to access this resource.",{message:s,status:i,code:r||"CLI_ERR_FORBIDDEN",help:o||"Check your organization permissions or role."}):{message:s,status:i,code:r||"CLI_ERR_API_FAILURE",help:o}}return{message:c?.message||"An unknown error occurred.",code:"CLI_ERR_UNKNOWN"}}function ci(c,e){return c.token||(e.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1)),c.token}var He=class extends Ae{client;constructor(e,t,i=F()){super(e,t),this.client=i}ensureAuth(){return ci(this.client,this.formatter)}async resolveDefaultOrgLabel(e){if(!e)return"None";try{let r=((await this.client.organizations.list({token:this.client.token})).data||[]).find(s=>s.key===e);if(r?.name)return`${r.name} (${e})`}catch{}return e}};import Mp from"node:http";import{readFileSync as Up}from"node:fs";import zp from"open";import{input as Cp,confirm as Dp,select as Lp}from"@inquirer/prompts";async function pe(c,e){return(await Cp({message:c,default:e})).trim()}async function oo(c,e=!0){return Dp({message:c,default:e})}async function Ce(c,e){return Lp({message:c,choices:e})}async function ao(c,e){let t;try{t=(await c.organizations.list({token:c.token})).data||[]}catch{return}if(t.length>0){if(!N.resolved.org){let o=t[0],a=o.key;N.writeOrgToActiveProfile(a),e.format!=="json"&&console.log(`
|
|
19
|
+
`),_="message",$="";for(let j of A)j.startsWith("event:")?_=j.substring(6).trim():j.startsWith("data:")&&($+=j.substring(5).trim());if(!$)continue;let P;try{P=JSON.parse($)}catch{console.error("Failed to parse SSE JSON data:",$);continue}switch(_){case"user-message":yield{event:_,data:P};break;case"agent-message":yield{event:_,data:P};break;case"thought-chunk":case"text-chunk":yield{event:_,data:P};break;case"done":yield{event:_,data:P};return;case"error":yield{event:_,data:b.fromRawException(P,"Failed to generate results")};break;case"session-updated":yield{event:_,data:P};break;default:console.warn(`Unknown SSE event: ${_}`)}}}}sessions={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSessions(e,t));this.sdk.appendListOptions(a,i);let n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to list sessions. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},read:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSession(e,t,i)),n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to read session. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body).data}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(d.kind!==Rr)throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},create:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSessions(e,t)),n=JSON.stringify(i),l=await this.sdk.http.post(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to create session. ";if(l.status!==201)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==Rr)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSession(e,t,i)),n=await this.sdk.http.delete(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to delete session. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiSession(e,t,i.key)),n=JSON.stringify(i),l=await this.sdk.http.put(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to update session. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==Rr)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}};messages={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiMessages(e,t));this.sdk.appendListOptions(a,i);let n=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to list messages. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);if(!n.body)throw new b(`${l}${B}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let d;try{d=JSON.parse(n.body)}catch{throw new b(`${l}${G}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(d.data))throw new b(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return d},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiMessage(e,t,i)),n=await this.sdk.http.delete(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(n);let l="Unable to delete message. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(T.aiMessage(e,t,i.key)),n=JSON.stringify(i),l=await this.sdk.http.put(a.toString(),{token:s,body:n,retry:o});this.inspectCommonStatusCodes(l);let d="Unable to update message. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${d}${C}${l.status}`,l.body);if(!l.body)throw new b(`${d}${B}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new b(`${d}${G}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==tc)throw new b(`${d}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}}};var Nr;(function(c){c.Pending="pending",c.Active="active",c.Inactive="inactive",c.Failed="failed"})(Nr||(Nr={}));var Hi;(function(c){c.PROD="prod",c.STAGING="staging",c.DEV="dev"})(Hi||(Hi={}));var to=class extends me{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(T.deployments(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});return this.processListResponse(a,"Unable to list deployments. ")}async create(e,t,i={}){if(t.env===Hi.PROD&&!t.version)throw new b(`Version must not be empty for production environment: ${t.env}`,{code:"INVALID_DEPLOYMENT_VERSION",help:"Please provide a version for production environment",status:400});if(t.env!==Hi.PROD&&t.version)throw new b(`Version must not be present for non-production environment: ${t.env}`,{code:"INVALID_DEPLOYMENT_VERSION",help:"Please remove the version for non-production environment",status:400});let r=this.sdk.getUrl(T.deployments(e)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,body:JSON.stringify(t),retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to create a deployment. ";if(a.status!==202)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async read(e,t,i={}){let r=this.sdk.getUrl(T.deployment(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to read a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async update(e,t,i,r={}){let s=this.sdk.getUrl(T.deployment(e,t)),{token:o=this.sdk.token,retry:a=!0}=r,n=await this.sdk.http.patch(s.toString(),{token:o,body:JSON.stringify(i),retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(n);let l="Unable to update deployment configuration. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${l}${C}${n.status}`,n.body);let d=this.readResponseJSON(n,l).data;return this.assertObjectKind(l,Ri,d.kind),d}async deactivate(e,t,i={}){let r=this.sdk.getUrl(T.deploymentDeactivate(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to deactivate a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async delete(e,t,i={}){let r=this.sdk.getUrl(T.deployment(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.delete(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to delete a deployment. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body)}async rollback(e,t,i={}){let r=this.sdk.getUrl(T.rollback(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.post(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to rollback a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,Ri,l.kind),l}async oas(e,t,i={}){let r=this.sdk.getUrl(T.deploymentOas(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o,headers:{Accept:"application/vnd.oai.openapi+json, application/json"}});this.inspectCommonStatusCodes(a);let n="Unable to retrieve OAS model. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);return this.readResponseJSON(a,n).data}apis={getLatestPerEnvironment:async(e,t,i={})=>{let r=this.sdk.getUrl(T.deploymentsApisByEnvLatest(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to list latest deployments for an API. ",l=this.readResponseJSON(a,n);if(!l.data)throw new b(`${n}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},list:async(e,t={})=>{let i=this.sdk.getUrl(T.deploymentsApis(e)),{token:r=this.sdk.token,retry:s=!0}=t,o=await this.sdk.http.get(i.toString(),{token:r,retry:s});return this.processListResponse(o,"Unable to list APIs. ")},listDeployments:async(e,t,i={},r={})=>{let s=this.sdk.getUrl(T.deploymentsForApi(e,t));this.sdk.appendListOptions(s,i);let{token:o=this.sdk.token,retry:a=!0}=r,n=await this.sdk.http.get(s.toString(),{token:o,retry:a});return this.processListResponse(n,"Unable to list deployments. ")},updateRuntimeUser:async(e,t,i,r,s="production",o={})=>{let a=this.sdk.getUrl(T.deploymentsApiRuntimeUsersUpdate(e,t)),{token:n=this.sdk.token,retry:l=!0}=o,d=JSON.stringify({userId:i,properties:r,env:s}),p=await this.sdk.http.post(a.toString(),{token:n,body:d,retry:l,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(p);let m="Unable to update runtime user. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${m}${C}${p.status}`,p.body);if(!p.body)throw new b(`${m}${B}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});return this.readResponseJSON(p,m)}}};var cc;(function(c){c.Pending="pending",c.Running="running",c.Completed="completed",c.Failed="failed"})(cc||(cc={}));var io=class extends me{async checkStatus(e,t,i={}){let r=this.sdk.getUrl(T.job(e,t)),{token:s=this.sdk.token,retry:o=!0}=i,a=await this.sdk.http.get(r.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(a);let n="Unable to check job status. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${n}${C}${a.status}`,a.body);let l=this.readResponseJSON(a,n).data;return this.assertObjectKind(n,ic,l.kind),l}};var lc=Symbol("baseUri"),ro=class extends EventTarget{basePath;#e;logger;get token(){return this.#e}set token(e){this.#e=e}auth=new Fs(this);files=new Gs(this);users=new Js(this);shared=new Ws(this);revisions=new Hs(this);trash=new Ys(this);organizations=new Xs(this);dataCatalog=new Zs(this);groups=new Qs(this);ai=new eo(this);deployments=new to(this);jobs=new io(this);silent=!1;[lc]="";get baseUri(){return this[lc]}set baseUri(e){if(!e)throw new Error("Invalid value for the baseUri");let t;try{t=new URL(e)}catch{throw new Error("Invalid baseUri: Not an URL")}this[lc]=t.origin;let{pathname:i}=t;i&&i!=="/"?this.basePath=i:this.basePath=void 0}constructor(e,t){super(),this.basePath=t,this.baseUri=e}getUrl(e="/"){if(e.startsWith("http:")||e.startsWith("https:"))return new URL(e);let{baseUri:t,basePath:i=""}=this,r=e;return i&&r.startsWith(i)&&(r=r.substring(i.length)),new URL(`${i}${r}`,t)}appendListOptions(e,t={}){let{searchParams:i}=e;if(t.cursor&&i.set("cursor",t.cursor),typeof t.limit=="number"&&i.set("limit",String(t.limit)),t.parent&&i.set("parent",t.parent),t.since&&i.set("since",String(t.since)),t.sort&&i.set("sort",String(t.sort)),t.order&&i.set("order",String(t.order)),t.oid&&i.set("oid",String(t.oid)),t.uid&&i.set("uid",String(t.uid)),t.filter){let r=new TextEncoder().encode(JSON.stringify(t.filter)),s=Array.from(r,o=>String.fromCodePoint(o)).join("");i.set("filter",btoa(s))}}};var so=class extends ro{http=new Vs(this)};function F(c={}){let e=N.resolved,t=c.apiUrl||e.apiUrl,i=new so(t);return e.token&&(i.token=e.token),i.logger=y,i}function U(c){if(c&&typeof c=="object"){let t=c,i=t.status,r=t.code,s=t.message||"An unknown error occurred.",o=t.help;return i===401?(s="Unauthorized. Please login using `auth login`.",{message:s,status:i,code:"CLI_ERR_UNAUTHORIZED",help:o}):i===403?(s=t.message||"Forbidden. You do not have permission to access this resource.",{message:s,status:i,code:r||"CLI_ERR_FORBIDDEN",help:o||"Check your organization permissions or role."}):{message:s,status:i,code:r||"CLI_ERR_API_FAILURE",help:o}}return{message:c?.message||"An unknown error occurred.",code:"CLI_ERR_UNKNOWN"}}function ci(c,e){return c.token||(e.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1)),c.token}var He=class extends Ae{client;constructor(e,t,i=F()){super(e,t),this.client=i}ensureAuth(){return ci(this.client,this.formatter)}async resolveDefaultOrgLabel(e){if(!e)return"None";try{let r=((await this.client.organizations.list({token:this.client.token})).data||[]).find(s=>s.key===e);if(r?.name)return`${r.name} (${e})`}catch{}return e}};import Mp from"node:http";import{readFileSync as Up}from"node:fs";import zp from"open";import{input as Cp,confirm as Dp,select as Lp}from"@inquirer/prompts";async function pe(c,e){return(await Cp({message:c,default:e})).trim()}async function oo(c,e=!0){return Dp({message:c,default:e})}async function Ce(c,e){return Lp({message:c,choices:e})}async function ao(c,e){let t;try{t=(await c.organizations.list({token:c.token})).data||[]}catch{return}if(t.length>0){if(!N.resolved.org){let o=t[0],a=o.key;N.writeOrgToActiveProfile(a),e.format!=="json"&&console.log(`
|
|
20
20
|
`+ie.cyan(`\u2139 Automatically set default organization to "${o.name}" (${a}).`))}return}if(e.format==="json")return;console.log(`
|
|
21
21
|
`+ie.yellow("\u26A0 It looks like you do not have any organizations yet.")),console.log("Let's set up your first organization now.");let i="";for(;!i;)i=await pe("Enter organization name:"),i||console.log(ie.red("Error: Organization name cannot be empty."));let r;try{r=await c.organizations.slugs.generate(i,{token:c.token})}catch{r=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}if(!await oo(`Use suggested organization slug "${r}"?`,!0)){let o=!1;for(;!o;){let a=await pe("Enter organization slug:");if(!a){console.log(ie.red("Error: Slug cannot be empty."));continue}try{let n=await c.organizations.slugs.validate(a,{token:c.token});n.valid?(r=a,o=!0):console.log(ie.red(`Error: ${n.reason||"Invalid slug"}`))}catch{console.log(ie.red("Error validating slug with server. Please try another slug."))}}}console.log(`
|
|
22
22
|
Creating organization "${i}" with slug "${r}"...`);try{let a=(await c.organizations.create(i,r,{token:c.token})).key;N.writeOrgToActiveProfile(a),console.log(`
|
|
@@ -24,7 +24,7 @@ Creating organization "${i}" with slug "${r}"...`);try{let a=(await c.organizati
|
|
|
24
24
|
${h}`));try{await zp(h)}catch{}})})}getLoginHtml(e){let t=[new URL("./templates/login.html",import.meta.url),new URL("../../commands/templates/login.html",import.meta.url),new URL("../commands/templates/login.html",import.meta.url)];for(let i of t)try{return Up(i,"utf8").replaceAll("{{API_URL}}",e)}catch{}throw new Error("Unable to locate login.html template.")}};var co=class extends He{constructor(e,t,i=F()){super(e,t,i)}execute(){let e=this.options.profile||N.resolved.activeProfile||"default";y.debug(`[auth] Executing logout command for profile '${e}'...`),N.deleteProfile(e),y.debug("[auth] Profile credentials removed successfully."),this.formatter.success(`Logged out of profile '${e}'.`),!N.resolved.activeProfile&&this.formatter.format!=="json"&&console.log("No active profile is set. Run `apinow auth profile use <name>` or `apinow auth login`.")}};var lo=class extends He{constructor(e,t,i=F()){super(e,t,i)}async execute(){y.debug("[auth] Checking current authentication status..."),this.ensureAuth();try{y.debug("[auth] Retrieving user profile details from platform...");let e=await this.client.users.me({token:this.client.token});if(y.debug(`[auth] User retrieved successfully: ${e.name}`),N.resolved.format==="json")this.formatter.object({authenticated:!0,profile:N.resolved.activeProfile,user:e});else{console.log(ie.green("\u2714 Authenticated successfully!")),N.resolved.activeProfile&&console.log(`Profile: ${N.resolved.activeProfile}`);let t=this.extractUserEmail(e.email);console.log(`User: ${e.name} (${t})`);let i=await this.resolveDefaultOrgLabel(N.resolved.org);console.log(`Default Org: ${i}`)}y.debug("[auth] Checking default organization status..."),await ao(this.client,this.formatter)}catch(e){let t=U(e);this.formatter.error({code:t.code||"CLI_ERR_UNAUTHORIZED",message:"Authentication token is invalid or expired.",detail:t.message}),process.exit(1)}}extractUserEmail(e){if(Array.isArray(e)){let t=e[0];if(t&&typeof t=="object"&&"email"in t)return String(t.email||"")}else if(typeof e=="string")return e;return""}};var po=class extends He{execute(){y.debug("[auth:profile:list] Listing configured authentication profiles...");let e=N.listProfiles(),t=N.getActiveProfile(),i=Object.entries(e);if(this.formatter.format==="json"){let s=i.map(([o,a])=>({alias:o,active:o===t,org:a.org||null,apiUrl:a.apiUrl||null}));this.formatter.list(s,["alias","active","org","apiUrl"]);return}if(i.length===0){console.log("No authentication profiles found. Run `apinow auth login` to authenticate.");return}let r=i.map(([s,o])=>({alias:s===t?`* ${s}`:` ${s}`,active:s===t?"true":"false",org:o.org||"-",apiUrl:o.apiUrl||"-"}));this.formatter.list(r,["alias","active","org","apiUrl"],{headers:["PROFILE","ACTIVE","DEFAULT ORG","API URL"]})}};var uo=class extends He{alias;constructor(e,t,i,r=F()){super(t,i,r),this.alias=e}async execute(){y.debug(`[auth:profile:use] Switching active profile to '${this.alias}'...`);let e=N.listProfiles();this.alias in e||(y.debug(`[auth:profile:use] Profile '${this.alias}' not found in profiles list.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Profile '${this.alias}' does not exist.`,detail:"Run `apinow auth profile list` to view available profiles or `apinow auth login` to create a new profile."}),process.exit(1));let t=e[this.alias];if(this.options.verify){y.debug(`[auth:profile:use] Verifying token validity for profile '${this.alias}'...`);try{await F({apiUrl:t.apiUrl}).users.me({token:t.token}),y.debug(`[auth:profile:use] Profile '${this.alias}' verified successfully.`)}catch(i){y.debug(`[auth:profile:use] Verification failed for profile '${this.alias}': ${String(i)}`),this.formatter.format!=="json"&&console.warn(ie.yellow(`\u26A0 Warning: Token for profile '${this.alias}' appears to be invalid or expired.`))}}N.setActiveProfile(this.alias),y.debug(`[auth:profile:use] Active profile updated to '${this.alias}'.`),this.formatter.success(`Switched to profile '${this.alias}'.`)}};var mo=class extends He{alias;constructor(e,t,i){super(t,i),this.alias=e}execute(){y.debug(`[auth:profile:delete] Deleting profile '${this.alias}'...`);let e=N.listProfiles();this.alias in e||(y.debug(`[auth:profile:delete] Profile '${this.alias}' not found.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Profile '${this.alias}' does not exist.`,detail:"Run `apinow auth profile list` to view configured profiles."}),process.exit(1));let t=N.getActiveProfile()===this.alias;N.deleteProfile(this.alias),y.debug(`[auth:profile:delete] Profile '${this.alias}' deleted successfully.`),this.formatter.success(`Profile '${this.alias}' deleted.`),t&&!N.getActiveProfile()&&this.formatter.format!=="json"&&console.log("No active profile is set. Run `apinow auth profile use <name>` to activate another, or `apinow auth login` to create a new one.")}};var li=class extends Ae{client;constructor(e,t,i=F()){super(e,t),this.client=i}ensureAuth(){return ci(this.client,this.formatter)}getActiveTokenId(){let e=N.resolved.token;if(!e)return null;try{let t=e.split(".");if(t.length===3){let i=t[1],r=Buffer.from(i,"base64url").toString("utf8"),s=JSON.parse(r);if(s&&typeof s=="object")return s.jti||s.id||null}}catch{}return null}};var ho=class extends li{constructor(e,t,i=F()){super(e,t,i)}async execute(){try{y.debug("[auth:tokens] Listing personal access tokens..."),this.ensureAuth();let e=await this.client.users.listTokens({token:this.client.token});y.debug(`[auth:tokens] Retrieved ${e.length} personal access token(s)`);let t=this.getActiveTokenId(),i=e.map(r=>({id:r.id,name:r.name||"N/A",lastUsedAt:r.lastUsedAt||"Never",expiresAt:r.expiresAt||"Never",active:r.id===t?"Yes":"No"}));this.formatter.list(i,["id","name","lastUsedAt","expiresAt","active"],{headers:["ID","NAME","LAST USED","EXPIRES","ACTIVE"]})}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};var fo=class extends li{constructor(e,t,i=F()){super(e,t,i)}async execute(){try{y.debug(`[auth:tokens] Creating personal access token with name="${this.options.name||"default"}"`),this.ensureAuth();let e=this.buildPayload(),t=await this.client.users.createToken(e,{token:this.client.token});y.debug(`[auth:tokens] Token created successfully with ID="${t.id}"`),this.formatResult(t)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}buildPayload(){let e={};return this.options.name&&(e.name=this.options.name),this.options.expiresAt&&(/^\d+$/.test(this.options.expiresAt)?e.expiresAt=parseInt(this.options.expiresAt,10):e.expiresAt=this.options.expiresAt),e}formatResult(e){N.resolved.format==="json"?this.formatter.success("Token created successfully!",e):(this.formatter.success("Token created successfully!"),console.log(`
|
|
25
25
|
`+ie.yellow("\u26A0 WARNING: Make sure to copy your personal access token now. You will NOT be able to see it again!")+`
|
|
26
26
|
`),console.log(`${ie.bold("Raw Token")}: ${ie.cyan(e.token)}`),console.log(`${ie.bold("ID")}: ${e.id}`),console.log(`${ie.bold("Name")}: ${e.name||"N/A"}`),console.log(`${ie.bold("Type")}: ${e.type}`),console.log(`${ie.bold("Expires At")}: ${e.expiresAt||"Never"}
|
|
27
|
-
`))}};var go=class extends li{id;constructor(e,t,i,r=F()){super(t,i,r),this.id=e}async execute(){try{y.debug(`[auth:tokens] Deleting personal access token with ID="${this.id}"`),this.ensureAuth(),await this.client.users.deleteToken(this.id,{token:this.client.token}),y.debug(`[auth:tokens] Successfully deleted token ID="${this.id}"`),this.formatter.success(`Token '${this.id}' deleted successfully.`)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};function gl(c){let e=c.command("tokens").description("Manage personal access tokens");e.command("list").description("List all personal access tokens").action(async t=>{let i=new K({format:N.resolved.format});await new ho(t,i).execute()}),e.command("create").description("Create a new personal access token").option("--name <name>","Optional name to identify the token").option("--expires-at <expires>",'Optional expiration time (e.g. "30 days", "10 minutes", or timestamp)').action(async t=>{let i=new K({format:N.resolved.format});await new fo(t,i).execute()}),e.command("delete <id>").description("Delete a personal access token by ID").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new go(t,i,r).execute()})}function yl(c){let e=c.command("auth").description("Manage CLI authentication");gl(e),e.command("login").description("Authenticate with the API platform using OAuth2 (google, github, or linkedin)").addArgument(new Vp("provider","Authentication provider").choices(["google","github","linkedin"])).option("--profile <name>","Authentication profile alias","default").option("--api-url <url>","API base URL for this profile").action(async(i,r)=>{let s=new K({format:N.resolved.format});await new no(i,r,s).execute()}),e.command("logout").description("Log out and clear the stored profile credentials").option("--profile <name>","Authentication profile alias to log out from").action(i=>{let r=new K({format:N.resolved.format});new co(i,r).execute()}),e.command("status").description("Check current authentication status").action(async i=>{let r=new K({format:N.resolved.format});await new lo(i,r).execute()});let t=e.command("profile").description("Manage authentication profiles");t.command("list").description("List all configured authentication profiles").action(i=>{let r=new K({format:N.resolved.format});new po(i,r).execute()}),t.command("use <name>").description("Switch the active authentication profile").option("--verify","Verify the profile token is valid with the server").action(async(i,r)=>{let s=new K({format:N.resolved.format});await new uo(i,r,s).execute()}),t.command("delete <name>").description("Delete a configured authentication profile").action((i,r)=>{let s=new K({format:N.resolved.format});new mo(i,r,s).execute()})}var di=class extends Ae{client;constructor(e,t,i=F()){super(e,t),this.client=i}async fetchOrganizations(){return(await this.client.organizations.list({token:this.client.token})).data||[]}};var yo=class extends di{constructor(e,t,i=F()){super(e,t,i)}async execute(){y.debug("[orgs:list] Listing all authorized organizations...");try{let e=await this.fetchOrganizations();y.debug(`[orgs:list] Found ${e.length} organizations.`);let t=N.resolved,i=e.map(r=>({id:r.key,name:r.name,slug:r.slug,isDefault:r.key===t.org?"Yes":"No"}));this.formatter.list(i,["id","name","slug","isDefault"],{headers:["ID","NAME","SLUG","DEFAULT"]})}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};var bo=class extends di{oid;constructor(e,t,i,r=F()){super(t,i,r),this.oid=e}async execute(){y.debug(`[orgs:set-default] Setting default organization ID to '${this.oid}'...`);try{y.debug("[orgs:set-default] Validating organization ID in user's authorized list..."),(await this.fetchOrganizations()).some(i=>i.key===this.oid)||(y.debug(`[orgs:set-default] Organization ID '${this.oid}' not found.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Organization ID '${this.oid}' not found in your authorized list.`,detail:"Run `apinow orgs list` to see all authorized organizations and their IDs."}),process.exit(1)),y.debug(`[orgs:set-default] Organization ID validated. Writing 'org' property as '${this.oid}'...`),N.writeOrgToActiveProfile(this.oid),y.debug("[orgs:set-default] Configuration property written successfully."),this.formatter.success(`Default organization ID set to '${this.oid}'.`)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};var ko=class extends di{constructor(e,t,i=F()){super(e,t,i)}async execute(){y.debug("[orgs:default] Retrieving the default configured organization...");try{let e=N.resolved;e.org||(y.debug("[orgs:default] No default organization configured in local settings."),this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"No default organization configured.",detail:"Set one using `apinow orgs set-default <oid>`. Run `apinow orgs list` to list available organizations."}),process.exit(1)),y.debug(`[orgs:default] Fetching organization list to validate configured org '${e.org}'...`);let i=(await this.fetchOrganizations()).find(r=>r.key===e.org);i||(y.debug(`[orgs:default] Configured org '${e.org}' not found in authorized list.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Default organization ID '${e.org}' not found in your authorized list.`,detail:"Run `apinow orgs set-default <oid>` to configure a valid default organization."}),process.exit(1)),y.debug(`[orgs:default] Default organization validated successfully: ${i.name}`),this.formatter.object({id:i.key,name:i.name,slug:i.slug})}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};function bl(c){let e=c.command("orgs").description("Manage organization configurations");e.command("list").description("List all organizations you belong to").action(async t=>{let i=new K({format:N.resolved.format});await new yo(t,i).execute()}),e.command("set-default <oid>").description("Set your default organization ID").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new bo(t,i,r).execute()}),e.command("default").alias("get-default").description("Get the default configured organization").action(async t=>{let i=new K({format:N.resolved.format});await new ko(t,i).execute()})}import kl from"node:fs";import Fp from"node:path";import{nanoid as qp}from"nanoid";var Z=class{constructor(e=F()){this.client=e}client;getFileMetaKind(e){let t=e.toLowerCase();if(t==="api"||t===Yt.toLowerCase())return Yt;if(t==="domain"||t===ni.toLowerCase())return ni;if(t==="folder"||t===ot.toLowerCase())return ot;throw new Error(`Unsupported file kind "${e}". Allowed: api, domain, folder`)}async list(e,t){let i={};if(t?.parent&&(i.parent=t.parent),t?.kind){let s=this.getFileMetaKind(t.kind);i.filter={field:"kind",operator:"eq",value:s}}return y.debug(`[FileManager:list] Listing files for org: ${e}, kind: ${t?.kind||"all"}, parent: ${t?.parent||"root"}`),(await this.client.files.list(e,i,{token:this.client.token})).data||[]}async search(e,t){let i=[];if(t?.kind){let s=Array.isArray(t.kind)?t.kind:[t.kind];for(let o of s)i.push(this.getFileMetaKind(o))}return y.debug(`[FileManager:search] Searching files for org: ${e}, kinds: ${i.join(",")||"all"}, parent: ${t?.parent||"all"}`),(await this.client.files.search(e,{kind:i.length>0?i:void 0,parent:t?.parent,query:t?.query,limit:t?.limit,cursor:t?.cursor},{token:this.client.token})).data||[]}async read(e,t){return y.debug(`[FileManager:read] Reading metadata for file ID '${t}' in org '${e}'...`),await this.client.files.read(e,t,{token:this.client.token})}async readMedia(e,t){y.debug(`[FileManager:readMedia] Reading media content for file ID '${t}' in org '${e}'...`);let i=await this.client.files.readMedia(e,t,{token:this.client.token});return{media:i.media,meta:i.meta}}async create(e,t){let i=this.getFileMetaKind(t.kind),r=Xt.createSchema({kind:i,info:{name:t.name},key:t.key}),s={};t.parent&&(s.parent=t.parent),y.debug(`[FileManager:create] Creating file metadata '${t.name}' (kind: ${i})...`);let o=await this.client.files.createMeta(r,e,s,{token:this.client.token}),a=o.key;return y.debug(`[FileManager:create] Created file metadata successfully. Key: ${a}`),t.mediaContent!==void 0&&(y.debug(`[FileManager:create] Uploading file media for key '${a}'...`),await this.client.files.createMedia(t.mediaContent,e,a,{},{token:this.client.token}),y.debug("[FileManager:create] Media uploaded successfully.")),o}async patchMedia(e,t,i){y.debug(`[FileManager:patchMedia] Sending ${i.patchOps.length} patch op(s) for file ID '${t}' (current version: ${i.version})...`);let r={id:qp(),timestamp:Date.now(),patch:i.patchOps,version:i.version};return await this.client.files.patchMedia(e,t,r,{token:this.client.token})}async parseMediaInput(e){if(e.mediaPath&&e.stdin)throw new Error("Cannot specify both media path and STDIN.");let t;if(e.mediaPath){let i=Fp.resolve(e.mediaPath);if(y.debug(`[FileManager:parseMediaInput] Reading media file from: ${i}`),!kl.existsSync(i))throw new Error(`Media file not found at path: ${i}`);t=kl.readFileSync(i,"utf8")}else e.stdin&&(y.debug("[FileManager:parseMediaInput] Reading media from STDIN..."),t=await this.readStdin());if(t!==void 0)return this.validateParsedMedia(t)}validateParsedMedia(e){let t;try{t=JSON.parse(e)}catch{throw new Error("invalid API now platform file")}if(!t||typeof t!="object"||Array.isArray(t)||!("key"in t)||typeof t.key!="string"||!t.key.trim())throw new Error("invalid API now platform file");let i=t.key;return{content:t,key:i}}async readStdin(){return new Promise((e,t)=>{let i="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{i+=r}),process.stdin.on("end",()=>{e(i)}),process.stdin.on("error",r=>{t(r)})})}};var pi=class extends Ae{fileManager;constructor(e,t,i=new Z){super(e,t),this.fileManager=i}async resolveFileId(e,t="Select a file to read:"){let i=this.options.id;if(!i&&process.stdout.isTTY){y.debug("[files] ID not provided, fetching files list for interactive selection...");try{let r=await this.fileManager.list(e);r.length>0&&(i=await Ce(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.kind})`,value:s.key}))))}catch{}}return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --id <fid>."}),process.exit(1)),i}};var vo=class extends pi{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[files:list] Listing files for org: ${e}, kind: ${this.options.kind||"all"}, parent: ${this.options.parent||"root"}`);try{let t=await this.fileManager.list(e,{kind:this.options.kind,parent:this.options.parent});y.debug(`[files:list] Found ${t.length} files.`);let i=t.map(r=>({id:r.key,name:r.info?.name||"",kind:r.kind,isShortcut:r.isShortcut?"Yes":"No"}));this.formatter.list(i,["id","name","kind","isShortcut"],{headers:["ID","NAME","KIND","SHORTCUT"]})}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var wo=class extends pi{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[files:create] Creating file with options: name=${this.options.name}, kind=${this.options.kind}, org=${e}, parent=${this.options.parent}, media=${this.options.media}, stdin=${this.options.stdin}`),this.options.media&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let t=this.options.name;!t&&process.stdout.isTTY&&(t=await pe("Enter file name:")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));let i=this.options.kind;!i&&process.stdout.isTTY&&(i=await Ce("Select file kind:",[{name:"API Domain / Schema (domain)",value:"domain"},{name:"API Schema (api)",value:"api"},{name:"Folder (folder)",value:"folder"}])),i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Kind is required.",detail:"Specify --kind <kind> (allowed: api, domain, folder)."}),process.exit(1));try{let r=await this.fileManager.parseMediaInput({mediaPath:this.options.media,stdin:this.options.stdin}),s=await this.fileManager.create(e,{name:t,kind:i,parent:this.options.parent,mediaContent:r?.content,key:r?.key});this.formatter.success("File created successfully!",s)}catch(r){r instanceof Error&&(r.message.startsWith("Media file not found")||r.message==="Cannot specify both media path and STDIN.")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:r.message}),process.exit(1));let o=U(r);this.formatter.error({code:"CLI_ERR_API_FAILURE",...o}),process.exit(1)}}};var So=class extends pi{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[files:read] Reading file with options: id=${this.options.id}, org=${e}, meta=${this.options.meta}, media=${this.options.media}`);let t=await this.resolveFileId(e);try{if(this.options.media){y.debug(`[files:read] Fetching media content for file ID '${t}'...`);let r=(await this.fileManager.readMedia(e,t)).media;y.debug("[files:read] Media retrieved successfully."),this.formatter.format==="json"?console.log(JSON.stringify(r,null,2)):console.log(typeof r=="object"&&r!==null?JSON.stringify(r,null,2):r)}else{y.debug(`[files:read] Fetching metadata for file ID '${t}'...`);let i=await this.fileManager.read(e,t);y.debug("[files:read] Metadata retrieved successfully."),this.formatter.object(i)}}catch(i){let r=U(i);this.formatter.error(r),process.exit(1)}}};function vl(c){let e=c.command("files").description("Manage files and metadata");e.command("list").description("List files in an organization").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--kind <kind>","Filter by file kind (e.g. domain, api, folder)").option("--parent <parent>","Filter by parent folder ID").action(async t=>{let i=new K({format:N.resolved.format});await new vo(t,i).execute()}),e.command("create").description("Create a new file metadata record (and optionally upload media)").option("--name <name>","Name of the file").option("--kind <kind>","Kind of the file (e.g., domain, api)").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Parent folder ID").option("--media <path>","Local path to the file content/media to upload").option("--stdin","Read media content from STDIN").action(async t=>{let i=new K({format:N.resolved.format});await new wo(t,i).execute()}),e.command("read").description("Read file metadata or media content").option("--id <fid>","File ID").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--meta","Read file metadata (default)").option("--media","Read file media/content").action(async t=>{let i=new K({format:N.resolved.format});await new So(t,i).execute()})}import{InvalidArgumentError as wl}from"commander";function Yi(c){if(!/^\d+$/.test(c.trim()))throw new wl("Must be a positive integer.");let e=parseInt(c,10);if(e<1)throw new wl("Must be a positive integer.");return e}var g;(function(c){c.User="Semantic#User",c.Address="Semantic#Address",c.Organization="Semantic#Organization",c.Project="Semantic#Project",c.AbstractManyToMany="Semantic#AbstractManyToMany",c.Password="Semantic#Password",c.Username="Semantic#Username",c.CreatedTimestamp="Semantic#CreatedTimestamp",c.UpdatedTimestamp="Semantic#UpdatedTimestamp",c.DeletedTimestamp="Semantic#DeletedTimestamp",c.DeletedFlag="Semantic#DeletedFlag",c.PublicUniqueName="Semantic#PublicUniqueName",c.Title="Semantic#Title",c.Name="Semantic#Name",c.UserRole="Semantic#UserRole",c.OrganizationRole="Semantic#OrganizationRole",c.ProjectRole="Semantic#ProjectRole",c.AssociationRole="Semantic#AssociationRole",c.Status="Semantic#Status",c.Version="Semantic#Version",c.ImageURL="Semantic#ImageURL",c.FileURL="Semantic#FileURL",c.Markdown="Semantic#Markdown",c.HTML="Semantic#HTML",c.GeospatialCoordinates="Semantic#GeospatialCoordinates",c.Email="Semantic#Email",c.Phone="Semantic#Phone",c.Currency="Semantic#Currency",c.URL="Semantic#URL",c.SKU="Semantic#SKU",c.Description="Semantic#Description",c.Summary="Semantic#Summary",c.Calculated="Semantic#Calculated",c.Derived="Semantic#Derived",c.ClientIPAddress="Semantic#ClientIPAddress",c.StreetAddress="Semantic#StreetAddress",c.StreetAddressSupplemental="Semantic#StreetAddressSupplemental",c.City="Semantic#City",c.PostalCode="Semantic#PostalCode",c.Country="Semantic#Country",c.Region="Semantic#Region",c.ResourceOwnerIdentifier="Semantic#ResourceOwnerIdentifier",c.RelationalResourceOwner="Semantic#RelationalResourceOwner",c.OrganizationMembers="Semantic#OrganizationMembers",c.ProjectMembers="Semantic#ProjectMembers",c.OrganizationResource="Semantic#OrganizationResource",c.ProjectResource="Semantic#ProjectResource",c.CreatedBy="Semantic#CreatedBy",c.UpdatedBy="Semantic#UpdatedBy",c.DeletedBy="Semantic#DeletedBy",c.Tags="Semantic#Tags",c.Categories="Semantic#Categories",c.PeerRelation="Semantic#PeerRelation"})(g||(g={}));var q;(function(c){c.Entity="Entity",c.Property="Property",c.Association="Association"})(q||(q={}));var J;(function(c){c.Identity="Identity & Authentication",c.Lifecycle="Timestamps & Versioning",c.Content="Content & Media",c.Business="Business Data",c.Organization="Classification & Organization",c.Location="Location & Geography",c.Contact="Contact Information",c.Computed="Computed Values"})(J||(J={}));var Sl=c=>c.scope===q.Entity,Ao=c=>c.scope===q.Property,Xi=c=>c.scope===q.Association,at={[g.User]:{id:g.User,displayName:"User Entity",scope:q.Entity,description:"System users and accounts",category:J.Identity,hasConfig:!1},[g.Password]:{id:g.Password,displayName:"User Password",scope:q.Property,description:"Secure password field",category:J.Identity,applicableDataTypes:["string"],hasConfig:!0},[g.Username]:{id:g.Username,displayName:"Username",scope:q.Property,description:"User authentication identifier",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.UserRole]:{id:g.UserRole,displayName:"User Role Field",scope:q.Property,description:"User permissions and access level",category:J.Identity,applicableDataTypes:["string"],hasConfig:!0},[g.ResourceOwnerIdentifier]:{id:g.ResourceOwnerIdentifier,displayName:"Resource Owner Identifier",scope:q.Association,description:"Links record to owner user",category:J.Identity,hasConfig:!1},[g.RelationalResourceOwner]:{id:g.RelationalResourceOwner,displayName:"Relational Resource Owner",scope:q.Association,description:"Specifies that the target entity of this association acts as the relational owner context for ownership verification.",category:J.Identity,hasConfig:!1},[g.Organization]:{id:g.Organization,displayName:"Organization Entity",scope:q.Entity,description:"Applied to the top-level Organization entity",category:J.Identity,hasConfig:!0},[g.AbstractManyToMany]:{id:g.AbstractManyToMany,displayName:"Abstract Many-To-Many",scope:q.Association,description:"Hidden parent semantic for all M:N relationships",category:J.Organization,hasConfig:!1,isHidden:!0,isManyToMany:!0},[g.OrganizationMembers]:{id:g.OrganizationMembers,displayName:"Organization Members",scope:q.Association,description:"Applied to the association pointing from Organization to User",category:J.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Organization Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:g.Organization,target:g.User},{parent:g.User,target:g.Organization}],unmetMessage:"Organization Members semantic can only be applied to an association connecting an Organization entity and a User entity."}],properties:[{meta:{required:!0},value:{info:{name:"organization_role",displayName:"Organization Role",description:"The role of the user in the organization"},semantics:[{id:g.OrganizationRole}],type:"string",index:!0,required:!0,schema:{enum:["owner","admin","editor","viewer"],defaultValue:{type:"literal",value:"viewer"}}}},{meta:{required:!1},value:{info:{name:"organization_status",displayName:"Organization Status",description:"The status of the user in the organization"},semantics:[{id:g.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[g.Project]:{id:g.Project,displayName:"Project Entity",scope:q.Entity,description:"Applied to a Project entity",category:J.Identity,hasConfig:!1},[g.ProjectMembers]:{id:g.ProjectMembers,displayName:"Project Members",scope:q.Association,description:"Applied to the association pointing from Project to User",category:J.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Project Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:g.Project,target:g.User},{parent:g.User,target:g.Project}],unmetMessage:"Project Members semantic can only be applied to an association connecting a Project entity and a User entity."}],properties:[{meta:{required:!0},value:{info:{name:"project_role",displayName:"Project Role",description:"The role of the user in the project"},semantics:[{id:g.ProjectRole}],type:"string",index:!0,required:!0,schema:{enum:["owner","admin","editor","viewer"],defaultValue:{type:"literal",value:"viewer"}}}},{meta:{required:!1},value:{info:{name:"project_status",displayName:"Project Status",description:"The status of the user in the project"},semantics:[{id:g.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[g.OrganizationRole]:{id:g.OrganizationRole,displayName:"Organization Role Property",scope:q.Property,description:"Represents a membership role inside an organization",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.ProjectRole]:{id:g.ProjectRole,displayName:"Project Role Property",scope:q.Property,description:"Represents a membership role inside a project",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.AssociationRole]:{id:g.AssociationRole,displayName:"Association Role Property",scope:q.Property,description:"Represents a membership access role on a many-to-many association",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.OrganizationResource]:{id:g.OrganizationResource,displayName:"Organization Resources",scope:q.Association,description:"Represents resources owned by an organization",category:J.Identity,hasConfig:!1},[g.ProjectResource]:{id:g.ProjectResource,displayName:"Project Resources",scope:q.Association,description:"Represents resources owned by a project",category:J.Identity,hasConfig:!1},[g.CreatedBy]:{id:g.CreatedBy,displayName:"Created By",scope:q.Association,description:"Links record to the user who created it",category:J.Identity,hasConfig:!1},[g.UpdatedBy]:{id:g.UpdatedBy,displayName:"Updated By",scope:q.Association,description:"Links record to the user who last updated it",category:J.Identity,hasConfig:!1},[g.DeletedBy]:{id:g.DeletedBy,displayName:"Deleted By",scope:q.Association,description:"Links record to the user who soft-deleted it",category:J.Identity,hasConfig:!1},[g.CreatedTimestamp]:{id:g.CreatedTimestamp,displayName:"Creation Timestamp",scope:q.Property,description:"When record was created",category:J.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.UpdatedTimestamp]:{id:g.UpdatedTimestamp,displayName:"Update Timestamp",scope:q.Property,description:"When record was last modified",category:J.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.DeletedTimestamp]:{id:g.DeletedTimestamp,displayName:"Soft Delete Timestamp",scope:q.Property,description:"When record was marked deleted",category:J.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.DeletedFlag]:{id:g.DeletedFlag,displayName:"Soft Delete Flag",scope:q.Property,description:"Mark record as deleted",category:J.Lifecycle,applicableDataTypes:["boolean"],hasConfig:!1},[g.Address]:{id:g.Address,displayName:"Address Entity",scope:q.Entity,description:"Physical address entity",category:J.Contact,hasConfig:!1},[g.StreetAddress]:{id:g.StreetAddress,displayName:"Street Address",scope:q.Property,description:"Street address line",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.StreetAddressSupplemental]:{id:g.StreetAddressSupplemental,displayName:"Street Address Supplemental",scope:q.Property,description:"Supplemental street address line (e.g., Unit, Suite, Apartment, Floor)",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.City]:{id:g.City,displayName:"City",scope:q.Property,description:"City or locality",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.PostalCode]:{id:g.PostalCode,displayName:"Postal Code",scope:q.Property,description:"Postal or zip code",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Country]:{id:g.Country,displayName:"Country",scope:q.Property,description:"Country name or code",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Region]:{id:g.Region,displayName:"Region",scope:q.Property,description:"State, province, or region",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.Version]:{id:g.Version,displayName:"Version Number",scope:q.Property,description:"Auto-incrementing version counter",category:J.Lifecycle,applicableDataTypes:["number"],hasConfig:!1},[g.Title]:{id:g.Title,displayName:"Record Title",scope:q.Property,description:"Main title or heading",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Name]:{id:g.Name,displayName:"Name",scope:q.Property,description:"A person or pet name",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Description]:{id:g.Description,displayName:"Description",scope:q.Property,description:"Detailed description text",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Summary]:{id:g.Summary,displayName:"Summary",scope:q.Property,description:"Brief summary text",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Markdown]:{id:g.Markdown,displayName:"Markdown Content",scope:q.Property,description:"Formatted text content",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.HTML]:{id:g.HTML,displayName:"HTML Content",scope:q.Property,description:"Rich HTML content",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.ImageURL]:{id:g.ImageURL,displayName:"Image URL",scope:q.Property,description:"Link to image file",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.FileURL]:{id:g.FileURL,displayName:"File URL",scope:q.Property,description:"Link to file attachment",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.Status]:{id:g.Status,displayName:"Record Status",scope:q.Property,description:"Current state of record",category:J.Business,applicableDataTypes:["string"],hasConfig:!0},[g.Currency]:{id:g.Currency,displayName:"Currency",scope:q.Property,description:"Monetary value with currency",category:J.Business,applicableDataTypes:["number","string"],hasConfig:!0},[g.SKU]:{id:g.SKU,displayName:"SKU",scope:q.Property,description:"Product identification code",category:J.Business,applicableDataTypes:["string"],hasConfig:!0},[g.Email]:{id:g.Email,displayName:"Email",scope:q.Property,description:"Email address",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Phone]:{id:g.Phone,displayName:"Phone",scope:q.Property,description:"Phone number",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.URL]:{id:g.URL,displayName:"URL",scope:q.Property,description:"Web address or link",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.ClientIPAddress]:{id:g.ClientIPAddress,displayName:"Client IP Address",scope:q.Property,description:"Automatically populated client IP address",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.PublicUniqueName]:{id:g.PublicUniqueName,displayName:"Public Unique Name (Slug)",scope:q.Property,description:"URL-friendly unique identifier",category:J.Organization,applicableDataTypes:["string"],hasConfig:!0},[g.Tags]:{id:g.Tags,displayName:"Tags",scope:q.Association,description:"Enable tagging functionality",category:J.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Tags semantic can only be applied to multi-valued (array) associations."}]},[g.Categories]:{id:g.Categories,displayName:"Categories",scope:q.Association,description:"Enable categorization functionality",category:J.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany},[g.PeerRelation]:{id:g.PeerRelation,displayName:"Peer Relation",scope:q.Association,description:"Models peer, pairing, prerequisite, or recommendation relationships between domain entities",category:J.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Peer Relation semantic can only be applied to multi-valued (array) associations."}]},[g.GeospatialCoordinates]:{id:g.GeospatialCoordinates,displayName:"Geospatial Coordinates",scope:q.Property,description:"Location coordinates",category:J.Location,applicableDataTypes:["string"],hasConfig:!0},[g.Calculated]:{id:g.Calculated,displayName:"Calculated",scope:q.Property,description:"Auto-calculated field value",category:J.Computed,applicableDataTypes:["string","number","boolean","date","datetime","time","binary"],hasConfig:!0},[g.Derived]:{id:g.Derived,displayName:"Derived",scope:q.Property,description:"Value derived from other fields",category:J.Computed,applicableDataTypes:["string"],hasConfig:!0}};var Zt=class{domain;report=[];cachedEntitiesByDomainKey=new Map;cachedAssociationsByDomainKey=new Map;cachedLocalEntities;cachedForeignEntities;cachedAllEntities;cachedEntitiesBySemantic=new Map;cachedAssociationsBySemantic=new Map;cachedPropertiesBySemantic=new Map;constructor(e){this.domain=e}addIssue(e){this.report.push(e)}addIssues(e){e.length>0&&this.report.push(...e)}findEntity(e,t){let i=`${t??this.domain.key}:${e}`;if(this.cachedEntitiesByDomainKey.has(i))return this.cachedEntitiesByDomainKey.get(i)??void 0;let r=this.domain.findEntity(e,t);return this.cachedEntitiesByDomainKey.set(i,r??null),r}findAssociation(e,t){let i=`${t??this.domain.key}:${e}`;if(this.cachedAssociationsByDomainKey.has(i))return this.cachedAssociationsByDomainKey.get(i)??void 0;let r=this.domain.findAssociation(e,t);return this.cachedAssociationsByDomainKey.set(i,r??null),r}listEntities(e){return e?.foreignOnly?(this.cachedForeignEntities||(this.cachedForeignEntities=Array.from(this.domain.listEntities({foreignOnly:!0}))),this.cachedForeignEntities):e?.includeForeign?(this.cachedAllEntities||(this.cachedAllEntities=Array.from(this.domain.listEntities({includeForeign:!0}))),this.cachedAllEntities):(this.cachedLocalEntities||(this.cachedLocalEntities=Array.from(this.domain.listEntities()).filter(t=>t.domain.key===this.domain.key)),this.cachedLocalEntities)}getEntitiesWithSemantic(e){let t=this.cachedEntitiesBySemantic.get(e);if(t)return t;let i=this.listEntities().filter(r=>r.hasSemantic(e));return this.cachedEntitiesBySemantic.set(e,i),i}getUserEntities(){return this.getEntitiesWithSemantic(g.User)}getUserEntity(){let e=this.getUserEntities();return e.length===1?e[0]:void 0}getOrganizationEntities(){return this.getEntitiesWithSemantic(g.Organization)}getOrganizationEntity(){let e=this.getOrganizationEntities();return e.length===1?e[0]:void 0}getProjectEntities(){return this.getEntitiesWithSemantic(g.Project)}getProjectEntity(){let e=this.getProjectEntities();return e.length===1?e[0]:void 0}getAssociationsWithSemantic(e){let t=this.cachedAssociationsBySemantic.get(e);if(t)return t;let i=[];for(let r of this.listEntities())for(let s of r.listAssociations())s.hasSemantic(e)&&i.push(s);return this.cachedAssociationsBySemantic.set(e,i),i}getPropertiesWithSemantic(e){let t=this.cachedPropertiesBySemantic.get(e);if(t)return t;let i=[];for(let r of this.listEntities())for(let s of r.withInheritedProperties())s.hasSemantic(e)&&i.push({property:s,entity:r});return this.cachedPropertiesBySemantic.set(e,i),i}clearCache(){this.cachedEntitiesByDomainKey.clear(),this.cachedAssociationsByDomainKey.clear(),this.cachedLocalEntities=void 0,this.cachedForeignEntities=void 0,this.cachedAllEntities=void 0,this.cachedEntitiesBySemantic.clear(),this.cachedAssociationsBySemantic.clear(),this.cachedPropertiesBySemantic.clear()}};var Eo=new Set(["IN","EXISTS","SELECT","FROM","WHERE","AND","OR","NOT","NULL","TRUE","FALSE","BETWEEN","LIKE","INTO","JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","CROSS JOIN","UNION","INTERSECT","EXCEPT","ORDER BY","GROUP BY","HAVING","DISTINCT","LIMIT","OFFSET","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","RENAME","GRANT","REVOKE","CASCADE","RESTRICT","FETCH","FIRST","NEXT","ROWS","ONLY","WINDOW","OVER","PARTITION BY","PRECEDING","FOLLOWING","UNBOUNDED","CURRENT ROW","FILTER","WITH","RECURSIVE","COLLATE"]);var Tr=class{validate(e,t){let i;if(typeof e=="string"?i=t.findEntity(e):i=e,!i){t.addIssue({field:"*",rule:"exists",message:`The "${e}" entity does not exist.`,help:"The entity must be defined in the domain.",key:e,kind:$,severity:"error",parentKind:$});return}this.validatePrimaryKey(i,t),this.minimumRequiredProperties(i,t),this.validateName(i,t),this.uniqueName(i,t)}validatePrimaryKey(e,t){e.primaryKey()||t.addIssue({field:"properties",rule:"primary_key",message:`The "${e.info.getLabel()}" entity has no identifier.`,help:"An entity that can exists by itself must have identifier defined.",severity:"error",key:e.key,kind:e.kind,parentKind:$})}hasPropertiesInherited(e){if(e.hasProperties())return!0;for(let t of e.listParents())if(this.hasPropertiesInherited(t))return!0;return!1}hasAssociationsInherited(e){if(e.hasAssociations())return!0;for(let t of e.listParents())if(this.hasAssociationsInherited(t))return!0;return!1}minimumRequiredProperties(e,t){let i=this.hasPropertiesInherited(e),r=this.hasAssociationsInherited(e);!i&&!r&&t.addIssue({field:"properties",rule:"required",message:`The "${e.info.getLabel()}" entity has no properties. It will be ignored.`,help:"Entities that have no properties are ignored in the data domain. No schema will be generated for it.",severity:"warning",key:e.key,kind:e.kind,parentKind:$})}validateName(e,t){let i=e.info.getLabel();if(!e.info.name){t.addIssue({field:"name",rule:"required",message:`The "${i}" entity has no name.`,help:"An entity must have a name.",severity:"error",key:e.key,kind:e.kind,parentKind:$});return}let r=e.info.name;r.length<2&&t.addIssue({field:"name",rule:"length",message:`The "${i}" entity name is too short.`,help:"The name must be at least 2 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:$}),r.length>31&&t.addIssue({field:"name",rule:"length",message:`The "${i}" entity name is too long.`,help:"The name must be at most 31 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:$}),/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)||t.addIssue({field:"name",rule:"format",message:`The "${i}" entity name is invalid.`,help:"The name must start with a letter (a-z) or underscore (_). Subsequent characters can be letters, digits (0-9), or underscores (_).",severity:"error",key:e.key,kind:e.kind,parentKind:$}),/^[A-Z]/.test(r)&&t.addIssue({field:"name",rule:"snake_case",message:`The "${i}" entity name is not in snake case.`,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:e.key,kind:e.kind,parentKind:$}),Eo.has(r.toUpperCase())&&t.addIssue({field:"name",rule:"reserved",message:`The "${i}" entity name is a reserved keyword.`,help:"The name should not be a reserved keyword.",severity:"error",key:e.key,kind:e.kind,parentKind:$}),/^verify[-_].*$/i.test(r)&&t.addIssue({field:"name",rule:"reserved_pattern",message:`The "${i}" entity name matches the reserved pattern "verify-*".`,help:'Entity names starting with "verify-" are reserved for system verification endpoints (e.g. verify-email, verify-phone).',severity:"error",key:e.key,kind:e.kind,parentKind:$})}uniqueName(e,t){let i=e.info.name?.toLowerCase();if(i){for(let r of t.listEntities())r.info.name?.toLowerCase()===i&&r.key!==e.key&&t.addIssue({field:"name",rule:"unique",message:`The "${i}" entity name is already used in the data domain.`,help:"The name must be unique. This includes references to other data domains.",severity:"error",key:r.key,kind:r.kind,parentKind:$});for(let r of t.listEntities({foreignOnly:!0}))r.info.name?.toLowerCase()===i&&r.key!==e.key&&t.addIssue({field:"name",rule:"unique",message:`The "${i}" entity name is already used in the foreign data domain.`,help:"The name must be unique. This includes references to other data domains.",severity:"error",key:r.key,kind:r.kind,parent:r.domain.key,parentKind:$})}}};function _o(c,e){let t=c.info.getLabel(),i=c.getParentInstance();if(!i)return;let r;if(i.kind===$)r=i.key;else{let a=i.getParentInstance();if(!a)return;r=a.key}let s=c.kind===be?"property":"association";if(!c.info.name){e.addIssue({field:"name",rule:"required",message:`The "${t}" ${s} has no name.`,help:`The ${s} must have a name.`,severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}});return}let o=c.info.name;o.length<2&&e.addIssue({field:"name",rule:"length",message:`The "${t}" ${s} name is too short.`,help:"The name must be at least 2 characters long.",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),o.length>59&&e.addIssue({field:"name",rule:"length",message:`The "${t}" ${s} name is too long.`,help:"The name must be at most 59 characters long.",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)||e.addIssue({field:"name",rule:"format",message:`The "${t}" ${s} name is invalid.`,help:"The name must start with a letter (a-z) or underscore (_). Subsequent characters can be letters, digits (0-9), or underscores (_).",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),/^[A-Z]/.test(o)&&e.addIssue({field:"name",rule:"snake_case",message:`The "${t}" ${s} name is not in snake case.`,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),Eo.has(o.toUpperCase())&&e.addIssue({field:"name",rule:"reserved",message:`The "${t}" ${s} name is a reserved keyword.`,help:"The name should not be a reserved keyword.",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}function St(c,e){let t=c;for(let i of e){if(typeof t!="object"||t===null)return!1;if(t.properties&&typeof t.properties=="object"&&i in t.properties){t=t.properties[i];continue}return!(t.properties&&t.additionalProperties===!1||t.type&&t.type!=="object"&&t.type!=="any")}return!0}var jr=class{validate(e,t){let i;if(typeof e=="string"?i=t.domain.findProperty(e):i=e,!i){t.addIssue({field:"*",rule:"exists",message:`The "${e}" property does not exist.`,help:"The property must be defined in the domain.",key:e,kind:be,severity:"error",parentKind:$});return}this.validateName(i,t),this.validateMutability(i,t),this.validatePrimaryKeyDefault(i,t),this.validateJsonIndex(i,t),this.validateSchema(i,t)}validateMutability(e,t){let i=e.getParentInstance();if(!i)return;let r=e.info.getLabel();e.readOnly&&e.immutable&&t.addIssue({field:"immutable",rule:"property_mutability_exclusive",message:`The property "${r}" cannot be both read-only and immutable.`,help:"A property must either be editable anytime, set once on creation (immutable), or managed by the system (read-only). These states are mutually exclusive.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind});let s=!!e.writeOnly||e.hasSemantic(g.Password);s&&e.readOnly&&t.addIssue({field:"writeOnly",rule:"property_write_read_conflict",message:`The property "${r}" cannot be both write-only and read-only.`,help:"A property cannot be both write-only and read-only at the same time.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind}),e.primary&&!e.readOnly&&!e.immutable&&t.addIssue({field:"primary",rule:"primary_key_mutable",message:`The primary key property "${r}" must be either read-only or immutable.`,help:"Primary keys identify entity records and cannot be mutable on update. Specify readOnly: true for server-generated IDs or immutable: true for client-assigned identifiers.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind}),e.primary&&s&&t.addIssue({field:"writeOnly",rule:"primary_key_write_only",message:`The primary key property "${r}" cannot be write-only.`,help:"Primary keys identify entity records in URLs and responses, so they cannot be hidden with writeOnly.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind})}validateName(e,t){_o(e,t)}validatePrimaryKeyDefault(e,t){if(e.primary){let i=e.getParentInstance();if(!i)return;let r=e.schema?.defaultValue;if(r){if(r.type!=="function"||r.value!=="random"){let s=`The primary key property "${e.info.getLabel()}" has an invalid default value.`;t.addIssue({field:"schema.defaultValue",rule:"primary_key_default",message:s,help:'Primary key properties can only have the "random" function as their default value.',severity:"error",key:e.key,kind:e.kind,parentKind:i.kind})}}else{let s=`The primary key property "${e.info.getLabel()}" has no default value.`,o=e.readOnly?'Without a default generator (e.g., the "random" function), the database sequence or server must generate primary key values automatically.':'Without a default generator (e.g., the "random" function), the client application must generate and supply primary key values manually.';t.addIssue({field:"schema.defaultValue",rule:"primary_key_no_default",message:s,help:o,severity:"warning",key:e.key,kind:e.kind,parentKind:i.kind})}}}validateJsonIndex(e,t){let i=e.jsonIndex;if(!i)return;let r=e.getParentInstance();if(r){if(e.type!=="json"){t.addIssue({field:"jsonIndex",rule:"json_index_type_mismatch",message:`Property "${e.info.getLabel()}" has a JSON index config but its type is "${e.type}".`,help:'JSON index configuration can only be defined for properties of type "json".',severity:"error",key:e.key,kind:e.kind,parentKind:r.kind});return}if(i.paths&&e.jsonSchema)for(let s of i.paths){if(!s.path){t.addIssue({field:"jsonIndex.paths",rule:"json_index_path_empty",message:`Property "${e.info.getLabel()}" has an empty JSON path in its index config.`,help:"JSON path index configurations must specify a non-empty path.",severity:"error",key:e.key,kind:e.kind,parentKind:r.kind});continue}let o=s.path.split(".");St(e.jsonSchema,o)||t.addIssue({field:"jsonIndex.paths",rule:"json_index_path_invalid",message:`JSON path "${s.path}" in index config for property "${e.info.getLabel()}" is not valid according to the property's JSON Schema.`,help:"All indexed JSON paths must exist in the property's JSON Schema definition.",severity:"error",key:e.key,kind:e.kind,parentKind:r.kind})}}}validateSchema(e,t){let i=e.schema;if(!i)return;let r=e.getParentInstance();if(!r)return;if(!["number","string","date","datetime","time"].includes(e.type)&&(i.minimum!==void 0||i.maximum!==void 0)){let a=i.minimum!==void 0?"schema.minimum":"schema.maximum",n=e.info.getLabel();t.addIssue({field:a,rule:"schema_boundary_unsupported_type",message:`The property "${n}" of type "${e.type}" cannot define minimum or maximum boundary constraints.`,help:'Boundary constraints (minimum and maximum) are only supported on "number", "string", "date", "datetime", and "time" properties.',severity:"error",key:e.key,kind:e.kind,parentKind:r.kind});return}let o=!1;i.minimum!==void 0&&this.validateBoundaryValue(e,"minimum",i.minimum,r.kind,t)&&(o=!0),i.maximum!==void 0&&this.validateBoundaryValue(e,"maximum",i.maximum,r.kind,t)&&(o=!0),!o&&i.minimum!==void 0&&i.maximum!==void 0&&this.validateBoundaryRange(e,r.kind,t)}validateBoundaryRange(e,t,i){let{schema:r,type:s}=e;if(!r||r.minimum===void 0||r.maximum===void 0)return;let{minimum:o,maximum:a,exclusiveMinimum:n,exclusiveMaximum:l}=r,d=e.info.getLabel();if(s==="number"||s==="string"){if(typeof o!="number"||typeof a!="number")return;if(o>a){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum value (${o}) greater than its maximum value (${a}).`,help:"The minimum constraint must be less than or equal to the maximum constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}o===a&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}else if(s==="date"){if(typeof o!="string"||typeof a!="string"||!this.isValidIsoDate(o)||!this.isValidIsoDate(a))return;if(o>a){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum date (${o}) later than its maximum date (${a}).`,help:"The minimum date constraint must be earlier than or equal to the maximum date constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}o===a&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum dates are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}else if(s==="datetime"){if(typeof o!="string"||typeof a!="string"||!this.isValidIsoDateTime(o)||!this.isValidIsoDateTime(a))return;let p=Date.parse(o),m=Date.parse(a);if(p>m){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum datetime (${o}) later than its maximum datetime (${a}).`,help:"The minimum datetime constraint must be earlier than or equal to the maximum datetime constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}p===m&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum datetimes are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}else if(s==="time"){if(typeof o!="string"||typeof a!="string"||!this.isValidIsoTime(o)||!this.isValidIsoTime(a))return;let p=this.isoTimeToSeconds(o),m=this.isoTimeToSeconds(a);if(p>m){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum time (${o}) later than its maximum time (${a}).`,help:"The minimum time constraint must be earlier than or equal to the maximum time constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}p===m&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum times are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}}validateBoundaryValue(e,t,i,r,s){let{type:o}=e,a=e.info.getLabel(),n=t==="minimum"?"schema_minimum_type":"schema_maximum_type",l=`schema.${t}`;if(o==="number"){if(typeof i!="number")return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "number". Expected a number.`,help:`The ${t} constraint for a number property must be a number.`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="string"){if(typeof i!="number"||!Number.isInteger(i)||i<0)return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "string". Expected a non-negative integer.`,help:`The ${t} constraint for a string property must be a non-negative integer representing the length.`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="date"){if(!this.isValidIsoDate(i))return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "date". Expected an ISO 8601 date string (YYYY-MM-DD).`,help:`The ${t} constraint for a date property must be an ISO 8601 full-date string (e.g. 2024-01-01).`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="datetime"){if(!this.isValidIsoDateTime(i))return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "datetime". Expected an ISO 8601 datetime string.`,help:`The ${t} constraint for a datetime property must be an ISO 8601 date-time string (e.g. 2024-01-01T00:00:00Z).`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="time"&&!this.isValidIsoTime(i))return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "time". Expected an ISO 8601 time string.`,help:`The ${t} constraint for a time property must be an ISO 8601 time string (e.g. 12:00:00).`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0;return!1}isValidIsoDate(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let[t,i,r]=e.split("-").map(Number),s=new Date(Date.UTC(t,i-1,r));return s.getUTCFullYear()===t&&s.getUTCMonth()===i-1&&s.getUTCDate()===r}isValidIsoDateTime(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/.test(e))return!1;let t=e.substring(0,10);return this.isValidIsoDate(t)?!isNaN(Date.parse(e)):!1}isValidIsoTime(e){if(typeof e!="string")return!1;let t=/^(\d{2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(e);if(!t)return!1;let i=Number(t[1]),r=Number(t[2]),s=t[3]!==void 0?Number(t[3]):0;return i>=0&&i<24&&r>=0&&r<60&&s>=0&&s<60}isoTimeToSeconds(e){let t=/^(\d{2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?(?:Z|[+-](\d{2}):?(\d{2}))?$/.exec(e);if(!t)return 0;let i=Number(t[1]),r=Number(t[2]),s=t[3]!==void 0?Number(t[3]):0,o=i*3600+r*60+s;if(t[4]!==void 0&&t[5]!==void 0){let a=e.includes("+")?1:-1,n=(Number(t[4])*3600+Number(t[5])*60)*a;o-=n}return o}};var Al=c=>{let e=c.trim();return e=e.match(/[A-Z]{2,}(?=[ A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)?.map(t=>t.toLowerCase()).join("_")||"",e};import El from"dompurify";var dc;function Kp(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}if(Kp()){let{JSDOM:c}=await import("jsdom"),{window:e}=new c("<!DOCTYPE html>");dc=El(e)}else dc=El;var _l=dc;function Bp(c){return _l.sanitize(c)}function xl(c,e="untitled_column"){let t=Bp(c);return t=Al(t),t=t.replace(/[\s-]+/g,"_"),t=t.replace(/[^a-z0-9_]/g,""),t=t.replace(/^_+|_+$/g,""),t||e}function Il(c,e,t="untitled_table"){let i=xl(c,t);return`${xl(e.slice(0,8))}_${i}`}function Pl(c){let{entityName:e,assocName:t,targetEntityName:i,pkName:r,useTargetTableInColumnName:s}=c;if(!e||!t||!r)throw new Error(`entityName, assocName, and pkName are required when computing foreign key column name (received entityName: "${e}", assocName: "${t}", pkName: "${r}")`);let o;return s&&i?o=`${e}_${t}_${i}_${r}`:o=`${e}_${t}_${r}`,pc(o)}function Gp(c,e=0){let t=3735928559^e,i=1103547991^e;for(let r=0,s;r<c.length;r++)s=c.charCodeAt(r),t=Math.imul(t^s,2654435761),i=Math.imul(i^s,1597334677);return t=Math.imul(t^t>>>16,2246822507)^Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&i)+(t>>>0)}function pc(c){if(c.length<=63)return c;let e=Gp(c).toString(16).padStart(8,"0").substring(0,8);return`${c.substring(0,54)}_${e}`}function Rl(c,e){let t=(typeof c=="string"?c:c?.getExposedName())?.trim();if(!t)throw new Error("sourceEntity is required when computing join table source foreign key column name");let i=typeof e=="string"?e.trim():e?.getExposedName()?.trim();if(!i)throw new Error("sourcePk is required when computing join table source foreign key column name");return pc(`${t}_${i}`)}function $l(c,e){let t=(typeof c=="string"?c:c?.getExposedName())?.trim();if(!t)throw new Error("assoc is required when computing join table target foreign key column name");let i=typeof e=="string"?e.trim():e?.getExposedName()?.trim();if(!i)throw new Error("targetPk is required when computing join table target foreign key column name");return pc(`${t}_${i}`)}var Cr=class{validate(e,t){let i;if(typeof e=="string"?i=t.findAssociation(e):i=e,!i){t.addIssue({field:"*",rule:"exists",message:`The "${e}" association does not exist.`,help:"The association must be defined in the domain.",key:e,kind:se,severity:"error",parentKind:$});return}this.validateName(i,t),this.validateTargets(i,t),this.validateSchema(i,t),this.validateJoinTableColumnCollision(i,t),this.validateLink(i,t)}validateName(e,t){_o(e,t)}validateTargets(e,t){let i=e.info.getLabel(),r=e.getParentInstance();if(!e.targets.length){t.addIssue({field:"targets",rule:"required",message:`The "${i}" association has no target.`,help:"An association must have at least one target.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$});return}e.isManyToMany()&&e.targets.length>1&&t.addIssue({field:"targets",rule:"mn_association_union_target_not_supported",message:`The "${i}" association is a Many-to-Many association and cannot have multiple target entities.`,help:"Many-to-Many associations must target exactly one entity because join tables do not support union or polymorphic targets.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$});for(let s of e.targets)t.findEntity(s.key,s.domain)||t.addIssue({field:"targets",rule:"exists",message:`The "${i}" association has an invalid target "${s.key}".`,help:"The target must be defined in the domain.",severity:"error",key:e.key,kind:e.kind,parent:r.key,parentKind:$})}validateSchema(e,t){let i=e.info.getLabel(),r=e.getParentInstance();e.multiple&&e.schema?.embedded===!0&&t.addIssue({field:"schema.embedded",rule:"embedded_not_supported_on_multiple_associations",message:`The "${i}" association has schema.embedded set to true but is multi-valued (multiple: true). Embedded hydration is not supported on multi-valued associations.`,help:'Remove "schema.embedded: true" or set multiple to false. Multi-valued associations must be accessed via sub-resource endpoints.',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$})}validateJoinTableColumnCollision(e,t){if(e.isLinked()||!e.isManyToMany())return;let i=e.getParentInstance();if(!i)return;let r=i.primaryKey();if(r)for(let s of e.targets){let a=t.findEntity(s.key,s.domain)?.primaryKey();if(!a)continue;let n=Rl(i,r),l=$l(e,a);if(n.toLowerCase()===l.toLowerCase()){let d=e.info.getLabel();t.addIssue({field:"name",rule:"association_join_table_column_collision",message:`The "${d}" association's join table foreign key column "${l}" collides with the source entity's foreign key column "${n}".`,help:"Rename the association so it does not match the source entity name.",severity:"error",key:e.key,kind:e.kind,parent:i.key,parentKind:$});break}}}validateLink(e,t){let i=e.link;if(!i)return;let r=e.info.getLabel(),s=e.getParentInstance();if(!i.key||!i.key.trim()){t.addIssue({field:"link.key",rule:"association_link_target_missing",message:`The "${r}" association is marked as linked but does not specify a target association key.`,help:'Provide a valid association key in the "link.key" property.',severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});return}if(i.key===e.key){t.addIssue({field:"link.key",rule:"association_link_self_reference",message:`The "${r}" association cannot link to itself.`,help:"Specify a different target association key to establish a reciprocal proxy.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});return}let o=!i.domain||i.domain===t.domain.key?t.domain:t.domain.dependencies.get(i.domain);if(!o){t.addIssue({field:"link.domain",rule:"association_link_domain_not_found",message:`The "${r}" association links to domain "${i.domain}", which is not loaded as a dependency in the current domain.`,help:"Add the foreign domain as a dependency or remove the domain qualification.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});return}let a=o.graph.node(i.key);if(!a){t.addIssue({field:"link.key",rule:"association_link_target_not_found",message:`The "${r}" association links to "${i.key}", but no matching element exists in the domain.`,help:"Ensure the target association key exists in the domain model.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});return}if(a.kind!==se){t.addIssue({field:"link.key",rule:"association_link_target_not_association",message:`The "${r}" association links to "${i.key}", which is a ${a.kind}, not a DomainAssociation.`,help:"Target association key must point to a DomainAssociation.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});return}let n=a;if(n.isLinked()){t.addIssue({field:"link.key",rule:"association_link_chained_proxy",message:`The "${r}" association links to "${n.info.getLabel()}", which is also a linked association. Chained association links are not permitted.`,help:"Point the link directly to the primary source of truth association.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});return}n.isManyToMany()||t.addIssue({field:"link.key",rule:"association_link_target_not_many_to_many",message:`The "${r}" association links to "${n.info.getLabel()}", which is not a Many-to-Many association. Reciprocal association links are only supported for Many-to-Many associations.`,help:"Ensure the primary association has multiple: true and an active M:N semantic (e.g. PeerRelation).",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:$});let l=n.getParentInstance();s&&l&&(n.targets.some(p=>{let m=p.domain??n.domain.key;return p.key===s.key&&m===s.domain.key})||t.addIssue({field:"link.key",rule:"association_link_target_mismatch",message:`The "${r}" association on entity "${s.info.getLabel()}" links to "${n.info.getLabel()}", but "${n.info.getLabel()}" does not target "${s.info.getLabel()}".`,help:`Ensure the linked primary association includes "${s.info.getLabel()}" in its targets list.`,severity:"error",key:e.key,kind:e.kind,parent:s.key,parentKind:$}),e.targets.length>0&&(e.targets.some(m=>{let h=m.domain??e.domain.key;return m.key===l.key&&h===l.domain.key})||t.addIssue({field:"targets",rule:"association_link_reciprocal_target_missing",message:`The "${r}" linked association must target the primary association's owner entity "${l.info.getLabel()}".`,help:`Add "${l.info.getLabel()}" to the targets of "${r}".`,severity:"error",key:e.key,kind:e.kind,parent:s.key,parentKind:$})))}};var Dr=class{semanticType=g.User;validate(e){let t=e.getUserEntities();t.length===0?e.addIssue({field:"semantics",rule:"recommended",message:"No entity with User taxonomy found in the domain.",help:"It is recommended to have an entity with the User taxonomy for authentication purposes.",severity:"warning",key:"user_semantic",kind:$,parentKind:$}):t.length>1&&e.addIssue({field:"semantics",rule:"one_user",message:"There is more than one entity with User taxonomy in the domain.",help:"There can be only one user in the system. Remove the additional User taxonomies.",severity:"error",key:"user_semantic",kind:$,parentKind:$});for(let i of t){let r=!1,s=!1,o=!1;for(let a of i.withInheritedProperties())if(a.hasSemantic(g.Username)&&(r=!0),a.hasSemantic(g.Password)&&(s=!0),a.hasSemantic(g.UserRole)&&(o=!0),r&&s&&o)break;r||e.addIssue({field:"semantics",rule:"has_username",message:"No username property on the User entity found.",help:'It is recommended to set the "username" property semantic for APIs supporting authentication.',severity:"warning",key:"user_semantic",kind:$,parentKind:$}),s||e.addIssue({field:"semantics",rule:"has_password",message:"No password property on the User entity found.",help:'It is recommended to set the "password" property semantic for APIs supporting authentication.',severity:"warning",key:"user_semantic",kind:$,parentKind:$}),o||e.addIssue({field:"semantics",rule:"has_user_role",message:"No role property on the User entity found.",help:'It is recommended to set the "User role" property semantic for APIs supporting authentication.',severity:"warning",key:"user_semantic",kind:$,parentKind:$})}for(let i of e.listEntities()){let r=!1,s=!1;for(let o of i.withInheritedProperties())o.hasSemantic(g.Username)&&(r=!0),o.hasSemantic(g.Password)&&(s=!0);(r||s)&&!i.hasSemantic(g.User)&&e.addIssue({field:"semantics",rule:"user_taxonomy_required",message:`The "${i.info.getLabel()}" entity has Username or Password properties but does not have the User taxonomy.`,help:"Entities containing authentication credentials like usernames or passwords must be tagged with the User taxonomy.",severity:"error",key:i.key,kind:i.kind,parentKind:$}),s&&!r&&e.addIssue({field:"semantics",rule:"username_required_for_password",message:`The "${i.info.getLabel()}" entity has Password credentials but lacks Username semantics.`,help:"An entity with Password credentials must also define a Username property for authentication.",severity:"error",key:i.key,kind:i.kind,parentKind:$})}}};var Lr=class{semanticType=[g.CreatedTimestamp,g.UpdatedTimestamp];validate(e){for(let t of e.listEntities()){let i=!1,r=!1;for(let s of t.withInheritedProperties())s.hasSemantic(g.CreatedTimestamp)&&(i=!0),s.hasSemantic(g.UpdatedTimestamp)&&(r=!0);i||e.addIssue({field:"semantics",rule:"recommended",message:`The "${t.info.getLabel()}" entity does not have a CreatedTimestamp taxonomy.`,help:"It is recommended to have a CreatedTimestamp property to track when the entity was created.",severity:"info",key:t.key,kind:t.kind,parentKind:$}),r||e.addIssue({field:"semantics",rule:"recommended",message:`The "${t.info.getLabel()}" entity does not have an UpdatedTimestamp taxonomy.`,help:"It is recommended to have an UpdatedTimestamp property to track when the entity was last modified.",severity:"info",key:t.key,kind:t.kind,parentKind:$})}}};var Mr=class{semanticType=[g.DeletedTimestamp,g.DeletedFlag];validate(e){for(let t of e.listEntities()){let i=!1;for(let r of t.withInheritedProperties())if(r.hasSemantic(g.DeletedTimestamp)||r.hasSemantic(g.DeletedFlag)){i=!0;break}i||e.addIssue({field:"semantics",rule:"recommended",message:`The "${t.info.getLabel()}" entity does not have soft delete taxonomy.`,help:"It is recommended to have either a DeletedTimestamp or DeletedFlag property for soft deletion.",severity:"info",key:t.key,kind:t.kind,parentKind:$})}}};var Ur=class{semanticType=["*:datatype","datatype"];validate(e){for(let t of e.listEntities())for(let i of t.withInheritedProperties())for(let r of i.semantics){let s=at[r.id];Ao(s)&&s.applicableDataTypes&&(s.applicableDataTypes.includes(i.type)||e.addIssue({field:"semantics",rule:"type_mismatch",message:`The "${i.info.getLabel()}" property has the "${s.displayName}" semantic applied, but its type "${i.type}" is not compatible.`,help:`The "${s.displayName}" semantic can only be applied to properties of type(s): ${s.applicableDataTypes.join(", ")}.`,severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$}))}}};var zr=class{semanticType=g.Currency;validate(e){let t=e.getPropertiesWithSemantic(g.Currency);for(let{property:i,entity:r}of t){let s=i.getSemantic(g.Currency);if(s){let o=s.config;i.type==="number"&&o?.allowedCurrencies&&o.allowedCurrencies.length>1&&e.addIssue({field:"semantics",rule:"currency_number_multiple",message:`The "${i.info.getLabel()}" property has the Currency semantic and is a Number, but allows multiple currencies.`,help:"Number properties cannot accept currency codes. Please change the property type to String, or restrict allowedCurrencies to exactly one currency.",severity:"error",key:i.key,kind:i.kind,parent:r.key,parentKind:$})}}}};var Vr=class{semanticType=g.GeospatialCoordinates;validate(e){for(let t of e.listEntities()){let i=new Map;for(let r of t.withInheritedProperties()){let s=r.getSemantic(g.GeospatialCoordinates);if(s){let o=s.config??{},a=!!o.enableDistanceQueries,n=!!o.enableBoundingBoxQueries,l=!!o.enablePolygonQueries,d=!!o.enableGeoClustering;if(a||n||l||d){let p=(o.apiEndpointPrefix||"/nearby").trim().toLowerCase(),m=i.get(p)??[];m.push(r.info.getLabel()),i.set(p,m)}}}for(let[r,s]of i.entries())s.length>1&&e.addIssue({field:"semantics",rule:"geospatial_endpoint_collision",message:`The "${t.info.getLabel()}" entity has multiple geospatial properties (${s.join(", ")}) sharing the same API endpoint prefix "${r}".`,help:"Each geospatial property on the same entity must use a unique apiEndpointPrefix to avoid query endpoint collisions (e.g., /nearby, /nearby-office).",severity:"error",key:t.key,kind:t.kind,parentKind:$})}}};function Fr(c,e,t){let i=e.getParentInstance();if(!i)return;let r=Array.from(e.listTargets()),s=[i,...r];for(let o of e.listProperties()){let a=o.info.name;if(a)for(let n of s)Array.from(n.withInheritedProperties()).find(d=>d.info.name===a)&&t.addIssue({field:"properties",rule:`${c}_property_collision`,message:`Property "${a}" on association "${e.info.getLabel()}" collides with a property of the same name on entity "${n.info.getLabel()}".`,help:`Rename the property "${a}" on the association to avoid conflicts when joining tables in the API (e.g., use a prefix like "${c.split("_")[0]}_${a}").`,severity:"error",key:o.key,kind:o.kind,parent:e.key,parentKind:se})}}function qr(c,e,t,i){let r=[],s=[];for(let o of t){let a=o.getSemantic(c);if(a)if(a.link){s.push(o),a.config&&Object.keys(a.config).length>0&&i.addIssue({field:"semantics",rule:"semantic_link_config_forbidden",message:`The association "${o.info.getLabel()}" has a semantic link set for "${c}", but also defines "config". Configuration should only be set on the primary semantic.`,help:'Remove the "config" property from the linked semantic definition.',severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:$});let n=i.findAssociation(a.link.key,a.link.domain);if(!n)i.addIssue({field:"semantics",rule:"semantic_link_target_not_found",message:`The association "${o.info.getLabel()}" has a semantic link targeting "${a.link.key}", but no matching association exists in the domain.`,help:"Update the link target key to point to an existing association with the primary semantic.",severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:$});else{let l=n.getSemantic(c);l?l.link&&i.addIssue({field:"semantics",rule:"semantic_link_target_is_link",message:`The association "${o.info.getLabel()}" links to "${n.info.getLabel()}", which is also a semantic link.`,help:"Point the link directly to the primary association with the source of truth configuration.",severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:$}):i.addIssue({field:"semantics",rule:"semantic_link_target_invalid",message:`The association "${o.info.getLabel()}" links to "${n.info.getLabel()}", but the target association does not have the "${c}" semantic.`,help:`Ensure the target association has the "${c}" semantic applied.`,severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:$})}}else r.push(o)}if(t.length>1){if(r.length===0)i.addIssue({field:"semantics",rule:"semantic_link_primary_missing",message:`All associations with the "${c}" semantic are defined as links, but no primary association exists.`,help:'Remove the "link" property from one association to designate it as the primary source of truth.',severity:"error",key:s[0].key,kind:s[0].kind,parent:s[0].getParentInstance()?.key,parentKind:$});else if(r.length>1)for(let o=1;o<r.length;o++){let a=r[o];i.addIssue({field:"semantics",rule:`${e}_link_required`,message:`Multiple associations have the "${c}" semantic, but "${a.info.getLabel()}" is missing a "link" to the primary association.`,help:'Define a "link" property pointing to the primary association key, and remove its "config".',severity:"error",key:a.key,kind:a.kind,parent:a.getParentInstance()?.key,parentKind:$})}}}var Kr=class{semanticType=g.Organization;validate(e){let t=e.getOrganizationEntities();if(t.length===0)return;t.length>1&&e.addIssue({field:"semantics",rule:"single_organization_entity",message:"Multiple entities marked with the Organization semantic found.",help:"Only one entity can be designated as the Organization per data domain. Remove the Organization semantic from additional entities.",severity:"error",key:"organization_semantic",kind:$,parentKind:$});let i=t[0],r=e.getUserEntity();if(!r){e.addIssue({field:"semantics",rule:"organization_requires_user",message:"An Organization entity is defined but no User entity exists.",help:"Multi-tenant organization structures require a User entity to establish memberships.",severity:"error",key:"organization_semantic",kind:$,parentKind:$});return}let s=Array.from(i.withInheritedAssociations()).find(l=>l.hasSemantic(g.OrganizationMembers)),o=Array.from(r.withInheritedAssociations()).find(l=>l.hasSemantic(g.OrganizationMembers));!s&&!o&&e.addIssue({field:"semantics",rule:"organization_members_assoc_missing",message:`Organization entity "${i.info.getLabel()}" is missing an association marked with Semantic#OrganizationMembers pointing to the User entity.`,help:"Please add an association from the Organization entity to the User entity (or vice versa) and apply the Semantic#OrganizationMembers tag.",severity:"error",key:"organization_semantic",kind:$,parentKind:$}),s&&(s.targets.length===1&&s.targets[0].key===r.key||e.addIssue({field:"semantics",rule:"organization_members_target_mismatch",message:`The association "${s.info.getLabel()}" marked with Semantic#OrganizationMembers must have exactly one target pointing to the User entity.`,help:"Ensure the OrganizationMembers association has a single target pointing to the User entity.",severity:"error",key:s.key,kind:s.kind,parent:i.key,parentKind:$})),o&&(o.targets.length===1&&o.targets[0].key===i.key||e.addIssue({field:"semantics",rule:"organization_members_user_target_mismatch",message:`The association "${o.info.getLabel()}" marked with Semantic#OrganizationMembers on User entity must target the Organization entity.`,help:"Change the target of the OrganizationMembers association on the User entity to point to Organization.",severity:"error",key:o.key,kind:o.kind,parent:r.key,parentKind:$}));let a=[s,o].filter(Boolean);a.length>0&&qr(g.OrganizationMembers,"organization_members",a,e);let n=a.find(l=>!l.getSemantic(g.OrganizationMembers)?.link);if(n){Fr("organization_members",n,e);let l=n.getParentInstance(),d=Array.from(n.listProperties()).filter(p=>p.hasSemantic(g.OrganizationRole));if(d.length===0)e.addIssue({field:"semantics",rule:"organization_role_missing",message:`Association "${n.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${l?.info.getLabel()}" is missing a property marked with Semantic#OrganizationRole.`,help:"Please add a string property to the OrganizationMembers association to track membership roles and mark it with Semantic#OrganizationRole.",severity:"error",key:n.key,kind:n.kind,parent:l?.key,parentKind:$});else if(d.length>1)e.addIssue({field:"semantics",rule:"organization_role_multiple",message:`Association "${n.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${l?.info.getLabel()}" has multiple properties marked with Semantic#OrganizationRole. Only one property can be marked as OrganizationRole per association.`,help:"Ensure only one property on the OrganizationMembers association has the Semantic#OrganizationRole tag. If you need multiple roles, they must not all be marked as the primary OrganizationRole.",severity:"error",key:n.key,kind:n.kind,parent:l?.key,parentKind:$});else{let p=d[0],m=p.schema?.enum;(!m||!Array.isArray(m)||m.length===0)&&e.addIssue({field:"semantics",rule:"organization_role_enum_missing",message:`The organization role property "${p.info.getLabel()}" on association "${n.info.getLabel()}" should define an enum of allowed roles (e.g. ['owner', 'editor', 'viewer']).`,help:"Define an enum array inside the schema of the OrganizationRole property to set valid roles.",severity:"warning",key:p.key,kind:p.kind,parent:n.key,parentKind:se})}}}};var Br=class{semanticType=g.Project;validate(e){let t=e.getProjectEntities();if(t.length===0)return;t.length>1&&e.addIssue({field:"semantics",rule:"single_project_entity",message:"Multiple entities marked with the Project semantic found.",help:"Only one entity can be designated as the Project per data domain. Remove the Project semantic from additional entities.",severity:"error",key:"project_semantic",kind:$,parentKind:$});let i=e.getUserEntity(),r=i?Array.from(i.withInheritedAssociations()).filter(s=>s.hasSemantic(g.ProjectMembers)):[];for(let s of r)s.targets.length===1&&t.some(a=>a.key===s.targets[0].key)||e.addIssue({field:"semantics",rule:"project_members_user_target_mismatch",message:`The association "${s.info.getLabel()}" marked with Semantic#ProjectMembers on User entity must target the Project entity.`,help:"Change the target of the ProjectMembers association on User entity to point to Project.",severity:"error",key:s.key,kind:s.kind,parent:i?.key,parentKind:$});for(let s of t){let o=Array.from(s.withInheritedAssociations()).find(d=>d.hasSemantic(g.ProjectMembers)),a=r.find(d=>d.targets.some(p=>p.key===s.key));o&&(i&&o.targets.length===1&&o.targets[0].key===i?.key||e.addIssue({field:"semantics",rule:"project_members_target_mismatch",message:`The association "${o.info.getLabel()}" marked with Semantic#ProjectMembers must have exactly one target pointing to the User entity.`,help:"Ensure the ProjectMembers association has a single target pointing to the User entity.",severity:"error",key:o.key,kind:o.kind,parent:s.key,parentKind:$}));let n=[o,a].filter(Boolean),l=n.find(d=>!d.getSemantic(g.ProjectMembers)?.link);if(l){Fr("project_members",l,e);let d=l.getParentInstance(),p=Array.from(l.listProperties()).filter(m=>m.hasSemantic(g.ProjectRole));if(p.length===0)e.addIssue({field:"semantics",rule:"project_role_missing",message:`Association "${l.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${d?.info.getLabel()}" is missing a property marked with Semantic#ProjectRole.`,help:"Please add a string property to the ProjectMembers association to track membership roles and mark it with Semantic#ProjectRole.",severity:"error",key:l.key,kind:l.kind,parent:d?.key,parentKind:$});else if(p.length>1)e.addIssue({field:"semantics",rule:"project_role_multiple",message:`Association "${l.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${d?.info.getLabel()}" has multiple properties marked with Semantic#ProjectRole. Only one property can be marked as ProjectRole per association.`,help:"Ensure only one property on the ProjectMembers association has the Semantic#ProjectRole tag. If you need multiple roles, they must not all be marked as the primary ProjectRole.",severity:"error",key:l.key,kind:l.kind,parent:d?.key,parentKind:$});else{let m=p[0],h=m.schema?.enum;(!h||!Array.isArray(h)||h.length===0)&&e.addIssue({field:"semantics",rule:"project_role_enum_missing",message:`The project role property "${m.info.getLabel()}" on association "${l.info.getLabel()}" should define an enum of allowed roles (e.g. ['owner', 'editor', 'viewer']).`,help:"Define an enum array inside the schema of the project role property to set valid roles.",severity:"warning",key:m.key,kind:m.kind,parent:l.key,parentKind:se})}}n.length>0&&qr(g.ProjectMembers,"project_members",n,e)}}};var Gr=class{semanticType=["*:preconditions","association_preconditions"];validate(e){for(let t of e.listEntities())for(let i of t.listAssociations())for(let r of i.semantics)try{i.checkPreconditions(r.id)}catch(s){let o=s instanceof Error?s.message:String(s);e.addIssue({field:"semantics",rule:"association_semantic_precondition_unmet",message:o,help:"Ensure the association meets all cardinality and entity pairing preconditions for this semantic.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$})}}};var Jr=class{semanticType=[g.Name,g.Title];validate(e){for(let t of e.listEntities()){let i=Array.from(t.withInheritedProperties()).filter(s=>s.hasSemantic(g.Name));if(i.length>1){let s=i.map(o=>`"${o.info.getLabel()}"`).join(", ");e.addIssue({field:"properties",rule:"entity_multiple_name_semantics",message:`The entity "${t.info.getLabel()}" has multiple properties annotated with SemanticType.Name (${s}).`,help:"An entity can have at most one property annotated with SemanticType.Name to uniquely identify the record's label.",severity:"error",key:t.key,kind:t.kind,parentKind:$})}let r=Array.from(t.withInheritedProperties()).filter(s=>s.hasSemantic(g.Title));if(r.length>1){let s=r.map(o=>`"${o.info.getLabel()}"`).join(", ");e.addIssue({field:"properties",rule:"entity_multiple_title_semantics",message:`The entity "${t.info.getLabel()}" has multiple properties annotated with SemanticType.Title (${s}).`,help:"An entity can have at most one property annotated with SemanticType.Title to represent the title of the work.",severity:"error",key:t.key,kind:t.kind,parentKind:$})}}}};var Wr=class{semanticType=[g.Tags,g.Categories];validate(e){for(let t of e.listEntities())for(let i of t.listAssociations()){if(i.hasSemantic(g.Tags)&&(i.multiple||e.addIssue({field:"multiple",rule:"tags_multiple_required",message:`The "${i.info.getLabel()}" association has Tags semantic but is not multi-valued (multiple: false).`,help:"Tags semantics can only be applied to multi-valued (array) associations.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$}),!i.isLinked()))for(let r of i.targets){let s=e.findEntity(r.key,r.domain);if(s){Array.from(s.withInheritedProperties()).some(n=>n.hasSemantic(g.Name))||e.addIssue({field:"semantics",rule:"tags_target_missing_name_semantic",message:`The target entity "${s.info.getLabel()}" of Tags association "${i.info.getLabel()}" does not have a property annotated with SemanticType.Name.`,help:"Entities used as Tag targets must define exactly one property annotated with SemanticType.Name to serve as the label.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$});let a=Array.from(s.withInheritedAssociations()).find(n=>n.targets.some(l=>l.key===s.key&&(!l.domain||l.domain===s.domain.key)));a&&e.addIssue({field:"semantics",rule:"tags_target_has_self_reference",message:`Entity "${s.info.getLabel()}" cannot be used as a Tags target because it has a self-referential association "${a.info.getLabel()}". Tags are flat by design. Use SemanticType.Categories for hierarchical taxonomy.`,help:`Remove the self-referential association from "${s.info.getLabel()}" or use SemanticType.Categories instead of SemanticType.Tags.`,severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$})}}if(i.hasSemantic(g.Categories)&&(!i.isLinked()&&i.targets.length>1&&e.addIssue({field:"targets",rule:"categories_union_target_not_supported",message:`The "${i.info.getLabel()}" association has Categories semantic and cannot have multiple target entities.`,help:"Categories associations must target exactly one entity because category classification requires a single taxonomy target.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$}),!i.isLinked()))for(let r of i.targets){let s=e.findEntity(r.key,r.domain);s&&(Array.from(s.withInheritedProperties()).some(a=>a.hasSemantic(g.Name))||e.addIssue({field:"semantics",rule:"categories_target_missing_name_semantic",message:`The target entity "${s.info.getLabel()}" of Categories association "${i.info.getLabel()}" does not have a property annotated with SemanticType.Name.`,help:"Entities used as Category targets must define exactly one property annotated with SemanticType.Name to serve as the label.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:$}))}}}};var Ol=["recommendation","cross_sell","prerequisite","alternative","reference","assignment","compatibility","custom"];var Hr=class{semanticType=g.PeerRelation;validate(e){let t=e.getAssociationsWithSemantic(g.PeerRelation);for(let i of t)i.isLinked()||this.validateAssociation(i,e)}validateAssociation(e,t){if(e.isLinked())return;let i=e.info.getLabel(),r=e.getParentInstance();e.multiple||t.addIssue({field:"multiple",rule:"semantic_peer_relation_not_multiple",message:`The "${i}" association has PeerRelation semantic but is not multi-valued (multiple: false).`,help:"PeerRelation semantics can only be applied to multi-valued (array) associations.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$});let o=e.getSemantic(g.PeerRelation)?.config;o?.nature?Ol.includes(o.nature)?o.nature==="prerequisite"&&o.symmetry==="mutual"?t.addIssue({field:"config.symmetry",rule:"semantic_peer_relation_mutual_prerequisite_conflict",message:`The "${i}" association cannot have nature "prerequisite" with symmetry "mutual". Prerequisites must be directed.`,help:'Change symmetry to "directed" or select a different relationship nature.',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$}):o.nature==="custom"&&(!o.customNature||!o.customNature.trim())&&t.addIssue({field:"config.customNature",rule:"semantic_peer_relation_custom_nature_required",message:`The "${i}" association has nature "custom" but "customNature" is empty.`,help:'Provide a descriptive domain identifier in "customNature" (e.g., "wine_pairing", "co_author").',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$}):t.addIssue({field:"config.nature",rule:"semantic_peer_relation_invalid_nature",message:`The "${i}" association has PeerRelation semantic with an invalid nature "${o.nature}".`,help:'Specify a valid relation nature such as "recommendation", "cross_sell", "prerequisite", "alternative", "reference", "assignment", "compatibility", or "custom".',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$}):t.addIssue({field:"config.nature",rule:"semantic_peer_relation_missing_nature",message:`The "${i}" association has PeerRelation semantic but is missing the required "nature" configuration.`,help:'Specify a valid relation nature such as "recommendation", "cross_sell", "prerequisite", "alternative", "reference", "assignment", "compatibility", or "custom".',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$})}};var Yr=class{semanticType=g.RelationalResourceOwner;validate(e){let t=e.getAssociationsWithSemantic(g.RelationalResourceOwner);for(let i of t)this.validateAssociation(i,e)}validateAssociation(e,t){if(!e.hasSemantic(g.RelationalResourceOwner))return;let i=e.info.getLabel(),r=e.getParentInstance();for(let s of e.targets){let o=t.findEntity(s.key,s.domain);o&&t.domain.resolveOwnershipPath(o.key)===null&&t.addIssue({field:"semantics",rule:"relational_owner_path_valid",message:`The target entity "${o.info.getLabel()}" of the relational resource owner association "${i}" does not have a valid ownership path to a User.`,help:"Ensure the target entity has a direct owner (Resource Owner Identifier) or transitively inherits ownership through another relational owner association.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:$})}}};var Xr=class{validators=[];byType=new Map;constructor(){this.register(new Dr),this.register(new Lr),this.register(new Mr),this.register(new Ur),this.register(new zr),this.register(new Vr),this.register(new Kr),this.register(new Br),this.register(new Gr),this.register(new Jr),this.register(new Wr),this.register(new Hr),this.register(new Yr)}register(e){let t=Array.isArray(e.semanticType)?e.semanticType:[e.semanticType],i=new Set;for(let r of t){let s=this.byType.get(r);s&&s!==e&&i.add(s),this.byType.set(r,e)}for(let r of i)if(!Array.from(this.byType.values()).includes(r)){let o=this.validators.indexOf(r);o!==-1&&this.validators.splice(o,1)}this.validators.includes(e)||this.validators.push(e)}unregister(e){let t=this.byType.get(e);if(!t)return!1;if(this.byType.delete(e),!Array.from(this.byType.values()).includes(t)){let r=this.validators.indexOf(t);r!==-1&&this.validators.splice(r,1)}return!0}get(e){return this.byType.get(e)}list(){return this.validators}validate(e,t){let i=this.get(e);i&&i.validate(t)}validateAll(e){for(let t of this.validators)t.validate(e)}};var Zi=class{domain;semanticRegistry;report=[];#e=0;#t=0;#i=0;#r=!1;entityValidator=new Tr;propertyValidator=new jr;associationValidator=new Cr;get infoCount(){return this.#r||this.computeIssueCounters(),this.#e}get warningCount(){return this.#r||this.computeIssueCounters(),this.#t}get errorCount(){return this.#r||this.computeIssueCounters(),this.#i}constructor(e,t=new Xr){this.domain=e,this.semanticRegistry=t}validate(){this.#r=!1,this.report=[];let e=new Zt(this.domain),t=!1;for(let i of e.listEntities()){t=!0,this.entityValidator.validate(i,e);for(let r of i.properties)r.domain.key===this.domain.key&&this.propertyValidator.validate(r,e);for(let r of i.associations)r.domain.key===this.domain.key&&this.associationValidator.validate(r,e)}return t?(this.semanticRegistry.validateAll(e),this.report=e.report,this.report):(this.report=e.report,this.report)}validateEntity(e){let t=new Zt(this.domain);return this.entityValidator.validate(e,t),t.report}validateProperty(e){let t=new Zt(this.domain);return this.propertyValidator.validate(e,t),t.report}validateAssociation(e){let t=new Zt(this.domain);return this.associationValidator.validate(e,t),t.report}validateSemantics(){let e=new Zt(this.domain);return this.semanticRegistry.validateAll(e),e.report}computeIssueCounters(){this.#e=this.report.filter(e=>e.severity==="info").length,this.#t=this.report.filter(e=>e.severity==="warning").length,this.#i=this.report.filter(e=>e.severity==="error").length,this.#r=!0}};var lt=class{root;get domain(){return this.root}#e;get key(){return this.#e}#t;get namespace(){return this.#t}constructor(e,t){this.root=e,this.#e=t,this.#t=e.key}};var Jp="http://a.ml/",Qt=`${Jp}vocabularies/`,re=`${Qt}document#`,we=`${Qt}core#`,ae=`${Qt}security#`,V=`${Qt}apiContract#`,Zr=`${Qt}apiBinding#`,H=`${Qt}shapes#`,xe=`${Qt}data#`,At=`${Qt}document-source-maps#`,Qr="http://www.w3.org/",fe=`${Qr}ns/shacl#`,Ye=`${Qr}2001/XMLSchema#`,xo=`${Qr}1999/02/22-rdf-syntax-ns#`,uc=`${Qr}2000/01/rdf-schema#`,u={aml:{key:"http://a.ml/",vocabularies:{key:Qt,document:{key:re,Module:`${re}Module`,Document:`${re}Document`,Fragment:`${re}Fragment`,Unit:`${re}Unit`,SecuritySchemeFragment:`${re}SecuritySchemeFragment`,UserDocumentation:`${re}UserDocumentation`,DataType:`${re}DataType`,NamedExamples:`${re}NamedExamples`,DomainElement:`${re}DomainElement`,DomainProperty:`${re}DomainProperty`,ParametrizedDeclaration:`${re}ParametrizedDeclaration`,AbstractDeclaration:`${re}AbstractDeclaration`,VariableValue:`${re}VariableValue`,ExternalFragment:`${re}ExternalFragment`,ExternalDomainElement:`${re}ExternalDomainElement`,RootDomainElement:`${re}RootDomainElement`,APIContractProcessingData:`${re}APIContractProcessingData`,BaseUnitProcessingData:`${re}BaseUnitProcessingData`,customDomainProperties:`${re}customDomainProperties`,encodes:`${re}encodes`,declares:`${re}declares`,references:`${re}references`,examples:`${re}examples`,linkTarget:`${re}link-target`,linkLabel:`${re}link-label`,referenceId:`${re}reference-id`,structuredValue:`${re}structuredValue`,raw:`${re}raw`,extends:`${re}extends`,value:`${re}value`,name:`${re}name`,strict:`${re}strict`,deprecated:`${re}deprecated`,location:`${re}location`,variable:`${re}variable`,target:`${re}target`,dataNode:`${re}dataNode`,root:`${re}root`,usage:`${re}usage`,version:`${re}version`},core:{key:we,CreativeWork:`${we}CreativeWork`,Parameter:`${we}Parameter`,Organization:`${we}Organization`,License:`${we}License`,Operation:`${we}Operation`,Response:`${we}Response`,Payload:`${we}Payload`,Request:`${we}Request`,version:`${we}version`,urlTemplate:`${we}urlTemplate`,displayName:`${we}displayName`,title:`${we}title`,name:`${we}name`,description:`${we}description`,documentation:`${we}documentation`,summary:`${we}summary`,provider:`${we}provider`,email:`${we}email`,url:`${we}url`,termsOfService:`${we}termsOfService`,license:`${we}license`,mediaType:`${we}mediaType`,extensionName:`${we}extensionName`,deprecated:`${we}deprecated`},security:{key:ae,ParametrizedSecurityScheme:`${ae}ParametrizedSecurityScheme`,SecuritySchemeFragment:`${ae}SecuritySchemeFragment`,SecurityScheme:`${ae}SecurityScheme`,OAuth1Settings:`${ae}OAuth1Settings`,OAuth2Settings:`${ae}OAuth2Settings`,OAuth2Flow:`${ae}OAuth2Flow`,Scope:`${ae}Scope`,Settings:`${ae}Settings`,HttpSettings:`${ae}HttpSettings`,ApiKeySettings:`${ae}ApiKeySettings`,OpenIdConnectSettings:`${ae}OpenIdConnectSettings`,SecurityRequirement:`${ae}SecurityRequirement`,security:`${ae}security`,scheme:`${ae}scheme`,schemes:`${ae}schemes`,settings:`${ae}settings`,name:`${ae}name`,type:`${ae}type`,scope:`${ae}scope`,accessTokenUri:`${ae}accessTokenUri`,authorizationUri:`${ae}authorizationUri`,authorizationGrant:`${ae}authorizationGrant`,flows:`${ae}flows`,flow:`${ae}flow`,signature:`${ae}signature`,tokenCredentialsUri:`${ae}tokenCredentialsUri`,requestTokenUri:`${ae}requestTokenUri`,refreshUri:`${ae}refreshUri`,securityRequirement:`${ae}SecurityRequirement`,openIdConnectUrl:`${ae}openIdConnectUrl`,bearerFormat:`${ae}bearerFormat`,in:`${ae}in`},apiContract:{key:V,Payload:`${V}Payload`,Request:`${V}Request`,Response:`${V}Response`,EndPoint:`${V}EndPoint`,Parameter:`${V}Parameter`,Operation:`${V}Operation`,WebAPI:`${V}WebAPI`,API:`${V}API`,AsyncAPI:`${V}AsyncAPI`,UserDocumentationFragment:`${V}UserDocumentationFragment`,Example:`${V}Example`,Server:`${V}Server`,ResourceType:`${V}ResourceType`,Trait:`${V}Trait`,TraitFragment:`${V}TraitFragment`,ParametrizedResourceType:`${V}ParametrizedResourceType`,ParametrizedTrait:`${V}ParametrizedTrait`,Callback:`${V}Callback`,TemplatedLink:`${V}TemplatedLink`,IriTemplateMapping:`${V}IriTemplateMapping`,Tag:`${V}Tag`,Message:`${V}Message`,DomainExtension:`${V}DomainExtension`,Encoding:`${V}Encoding`,header:`${V}header`,parameter:`${V}parameter`,paramName:`${V}paramName`,uriParameter:`${V}uriParameter`,cookieParameter:`${V}cookieParameter`,variable:`${V}variable`,payload:`${V}payload`,server:`${V}server`,path:`${V}path`,url:`${V}url`,scheme:`${V}scheme`,endpoint:`${V}endpoint`,queryString:`${V}queryString`,accepts:`${V}accepts`,guiSummary:`${V}guiSummary`,binding:`${V}binding`,response:`${V}response`,returns:`${V}returns`,expects:`${V}expects`,examples:`${V}examples`,supportedOperation:`${V}supportedOperation`,messageId:`${V}messageId`,statusCode:`${V}statusCode`,method:`${V}method`,required:`${V}required`,callback:`${V}callback`,expression:`${V}expression`,link:`${V}link`,linkExpression:`${V}linkExpression`,templateVariable:`${V}templateVariable`,mapping:`${V}mapping`,operationId:`${V}operationId`,protocol:`${V}protocol`,protocolVersion:`${V}protocolVersion`,headerSchema:`${V}headerSchema`,contentType:`${V}contentType`,allowEmptyValue:`${V}allowEmptyValue`,style:`${V}style`,explode:`${V}explode`,allowReserved:`${V}allowReserved`,tag:`${V}tag`,tags:`${V}tags`},apiBinding:{key:Zr,binding:`${Zr}binding`,bindings:`${Zr}bindings`,messageKey:`${Zr}messageKey`,type:`${Zr}type`},shapes:{key:H,Shape:`${H}Shape`,ScalarShape:`${H}ScalarShape`,ArrayShape:`${H}ArrayShape`,UnionShape:`${H}UnionShape`,NilShape:`${H}NilShape`,FileShape:`${H}FileShape`,AnyShape:`${H}AnyShape`,SchemaShape:`${H}SchemaShape`,MatrixShape:`${H}MatrixShape`,TupleShape:`${H}TupleShape`,RecursiveShape:`${H}RecursiveShape`,DataTypeFragment:`${H}DataTypeFragment`,XMLSerializer:`${H}XMLSerializer`,number:`${H}number`,integer:`${H}integer`,long:`${H}long`,double:`${H}double`,boolean:`${H}boolean`,float:`${H}float`,nil:`${H}nil`,password:`${H}password`,int32:`${H}int32`,int64:`${H}int64`,uint32:`${H}uint32`,uint64:`${H}uint64`,sint32:`${H}sint32`,sint64:`${H}sint64`,fixed32:`${H}fixed32`,fixed64:`${H}fixed64`,sfixed32:`${H}sfixed32`,sfixed64:`${H}sfixed64`,dateTimeOnly:`${H}dateTimeOnly`,range:`${H}range`,items:`${H}items`,anyOf:`${H}anyOf`,fileType:`${H}fileType`,schema:`${H}schema`,xmlSerialization:`${H}xmlSerialization`,xmlName:`${H}xmlName`,xmlAttribute:`${H}xmlAttribute`,xmlWrapped:`${H}xmlWrapped`,xmlNamespace:`${H}xmlNamespace`,xmlPrefix:`${H}xmlPrefix`,readOnly:`${H}readOnly`,writeOnly:`${H}writeOnly`,deprecated:`${H}deprecated`,fixPoint:`${H}fixPoint`,discriminator:`${H}discriminator`,discriminatorValue:`${H}discriminatorValue`,format:`${H}format`,multipleOf:`${H}multipleOf`,uniqueItems:`${H}uniqueItems`},data:{key:xe,Scalar:`${xe}Scalar`,Object:`${xe}Object`,Array:`${xe}Array`,Node:`${xe}Node`,value:`${xe}value`,type:`${xe}type`,description:`${xe}description`,required:`${xe}required`,displayName:`${xe}displayName`,minLength:`${xe}minLength`,maxLength:`${xe}maxLength`,default:`${xe}default`,multipleOf:`${xe}multipleOf`,minimum:`${xe}minimum`,maximum:`${xe}maximum`,enum:`${xe}enum`,pattern:`${xe}pattern`,items:`${xe}items`,format:`${xe}format`,example:`${xe}example`,examples:`${xe}examples`},docSourceMaps:{key:At,SourceMap:`${At}SourceMap`,sources:`${At}sources`,element:`${At}element`,value:`${At}value`,declaredElement:`${At}declared-element`,trackedElement:`${At}tracked-element`,parsedJsonSchema:`${At}parsed-json-schema`,autoGeneratedName:`${At}auto-generated-name`,lexical:`${At}lexical`,synthesizedField:`${At}synthesized-field`}}},w3:{key:Qr,shacl:{key:fe,Shape:`${fe}Shape`,NodeShape:`${fe}NodeShape`,SchemaShape:`${fe}SchemaShape`,PropertyShape:`${fe}PropertyShape`,in:`${fe}in`,defaultValue:`${fe}defaultValue`,defaultValueStr:`${fe}defaultValueStr`,pattern:`${fe}pattern`,minInclusive:`${fe}minInclusive`,maxInclusive:`${fe}maxInclusive`,multipleOf:`${fe}multipleOf`,minLength:`${fe}minLength`,maxLength:`${fe}maxLength`,fileType:`${fe}fileType`,and:`${fe}and`,property:`${fe}property`,name:`${fe}name`,raw:`${fe}raw`,datatype:`${fe}datatype`,minCount:`${fe}minCount`,maxCount:`${fe}maxCount`,xone:`${fe}xone`,not:`${fe}not`,or:`${fe}or`,closed:`${fe}closed`,path:`${fe}path`,additionalPropertiesSchema:`${fe}additionalPropertiesSchema`},xmlSchema:{key:Ye,boolean:`${Ye}boolean`,string:`${Ye}string`,number:`${Ye}number`,integer:`${Ye}integer`,long:`${Ye}long`,double:`${Ye}double`,float:`${Ye}float`,nil:`${Ye}nil`,dateTime:`${Ye}dateTime`,time:`${Ye}time`,date:`${Ye}date`,base64Binary:`${Ye}base64Binary`,byte:`${Ye}byte`},rdfSyntax:{key:xo,Seq:`${xo}Seq`,Property:`${xo}Property`,member:`${xo}member`},rdfSchema:{key:uc,Seq:`${uc}Seq`,member:`${uc}member`}}};function Qi(c,e=0){if(typeof c!="object")return c;let t="",i=new Array(e).fill(" ").join("");return Object.keys(c).forEach(r=>{t+=Array.isArray(c[r])?"":`${i}<${r}>`,Array.isArray(c[r])?c[r].forEach(s=>{t+=i,t+=`<${r}>
|
|
27
|
+
`))}};var go=class extends li{id;constructor(e,t,i,r=F()){super(t,i,r),this.id=e}async execute(){try{y.debug(`[auth:tokens] Deleting personal access token with ID="${this.id}"`),this.ensureAuth(),await this.client.users.deleteToken(this.id,{token:this.client.token}),y.debug(`[auth:tokens] Successfully deleted token ID="${this.id}"`),this.formatter.success(`Token '${this.id}' deleted successfully.`)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};function gl(c){let e=c.command("tokens").description("Manage personal access tokens");e.command("list").description("List all personal access tokens").action(async t=>{let i=new K({format:N.resolved.format});await new ho(t,i).execute()}),e.command("create").description("Create a new personal access token").option("--name <name>","Optional name to identify the token").option("--expires-at <expires>",'Optional expiration time (e.g. "30 days", "10 minutes", or timestamp)').action(async t=>{let i=new K({format:N.resolved.format});await new fo(t,i).execute()}),e.command("delete <id>").description("Delete a personal access token by ID").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new go(t,i,r).execute()})}function yl(c){let e=c.command("auth").description("Manage CLI authentication");gl(e),e.command("login").description("Authenticate with the API platform using OAuth2 (google, github, or linkedin)").addArgument(new Vp("provider","Authentication provider").choices(["google","github","linkedin"])).option("--profile <name>","Authentication profile alias","default").option("--api-url <url>","API base URL for this profile").action(async(i,r)=>{let s=new K({format:N.resolved.format});await new no(i,r,s).execute()}),e.command("logout").description("Log out and clear the stored profile credentials").option("--profile <name>","Authentication profile alias to log out from").action(i=>{let r=new K({format:N.resolved.format});new co(i,r).execute()}),e.command("status").description("Check current authentication status").action(async i=>{let r=new K({format:N.resolved.format});await new lo(i,r).execute()});let t=e.command("profile").description("Manage authentication profiles");t.command("list").description("List all configured authentication profiles").action(i=>{let r=new K({format:N.resolved.format});new po(i,r).execute()}),t.command("use <name>").description("Switch the active authentication profile").option("--verify","Verify the profile token is valid with the server").action(async(i,r)=>{let s=new K({format:N.resolved.format});await new uo(i,r,s).execute()}),t.command("delete <name>").description("Delete a configured authentication profile").action((i,r)=>{let s=new K({format:N.resolved.format});new mo(i,r,s).execute()})}var di=class extends Ae{client;constructor(e,t,i=F()){super(e,t),this.client=i}async fetchOrganizations(){return(await this.client.organizations.list({token:this.client.token})).data||[]}};var yo=class extends di{constructor(e,t,i=F()){super(e,t,i)}async execute(){y.debug("[orgs:list] Listing all authorized organizations...");try{let e=await this.fetchOrganizations();y.debug(`[orgs:list] Found ${e.length} organizations.`);let t=N.resolved,i=e.map(r=>({id:r.key,name:r.name,slug:r.slug,isDefault:r.key===t.org?"Yes":"No"}));this.formatter.list(i,["id","name","slug","isDefault"],{headers:["ID","NAME","SLUG","DEFAULT"]})}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};var bo=class extends di{oid;constructor(e,t,i,r=F()){super(t,i,r),this.oid=e}async execute(){y.debug(`[orgs:set-default] Setting default organization ID to '${this.oid}'...`);try{y.debug("[orgs:set-default] Validating organization ID in user's authorized list..."),(await this.fetchOrganizations()).some(i=>i.key===this.oid)||(y.debug(`[orgs:set-default] Organization ID '${this.oid}' not found.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Organization ID '${this.oid}' not found in your authorized list.`,detail:"Run `apinow orgs list` to see all authorized organizations and their IDs."}),process.exit(1)),y.debug(`[orgs:set-default] Organization ID validated. Writing 'org' property as '${this.oid}'...`),N.writeOrgToActiveProfile(this.oid),y.debug("[orgs:set-default] Configuration property written successfully."),this.formatter.success(`Default organization ID set to '${this.oid}'.`)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};var ko=class extends di{constructor(e,t,i=F()){super(e,t,i)}async execute(){y.debug("[orgs:default] Retrieving the default configured organization...");try{let e=N.resolved;e.org||(y.debug("[orgs:default] No default organization configured in local settings."),this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"No default organization configured.",detail:"Set one using `apinow orgs set-default <oid>`. Run `apinow orgs list` to list available organizations."}),process.exit(1)),y.debug(`[orgs:default] Fetching organization list to validate configured org '${e.org}'...`);let i=(await this.fetchOrganizations()).find(r=>r.key===e.org);i||(y.debug(`[orgs:default] Configured org '${e.org}' not found in authorized list.`),this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Default organization ID '${e.org}' not found in your authorized list.`,detail:"Run `apinow orgs set-default <oid>` to configure a valid default organization."}),process.exit(1)),y.debug(`[orgs:default] Default organization validated successfully: ${i.name}`),this.formatter.object({id:i.key,name:i.name,slug:i.slug})}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}};function bl(c){let e=c.command("orgs").description("Manage organization configurations");e.command("list").description("List all organizations you belong to").action(async t=>{let i=new K({format:N.resolved.format});await new yo(t,i).execute()}),e.command("set-default <oid>").description("Set your default organization ID").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new bo(t,i,r).execute()}),e.command("default").alias("get-default").description("Get the default configured organization").action(async t=>{let i=new K({format:N.resolved.format});await new ko(t,i).execute()})}import kl from"node:fs";import Fp from"node:path";import{nanoid as qp}from"nanoid";var Z=class{constructor(e=F()){this.client=e}client;getFileMetaKind(e){let t=e.toLowerCase();if(t==="api"||t===Yt.toLowerCase())return Yt;if(t==="domain"||t===ni.toLowerCase())return ni;if(t==="folder"||t===ot.toLowerCase())return ot;throw new Error(`Unsupported file kind "${e}". Allowed: api, domain, folder`)}async list(e,t){let i={};if(t?.parent&&(i.parent=t.parent),t?.kind){let s=this.getFileMetaKind(t.kind);i.filter={field:"kind",operator:"eq",value:s}}return y.debug(`[FileManager:list] Listing files for org: ${e}, kind: ${t?.kind||"all"}, parent: ${t?.parent||"root"}`),(await this.client.files.list(e,i,{token:this.client.token})).data||[]}async search(e,t){let i=[];if(t?.kind){let s=Array.isArray(t.kind)?t.kind:[t.kind];for(let o of s)i.push(this.getFileMetaKind(o))}return y.debug(`[FileManager:search] Searching files for org: ${e}, kinds: ${i.join(",")||"all"}, parent: ${t?.parent||"all"}`),(await this.client.files.search(e,{kind:i.length>0?i:void 0,parent:t?.parent,query:t?.query,limit:t?.limit,cursor:t?.cursor},{token:this.client.token})).data||[]}async read(e,t){return y.debug(`[FileManager:read] Reading metadata for file ID '${t}' in org '${e}'...`),await this.client.files.read(e,t,{token:this.client.token})}async readMedia(e,t){y.debug(`[FileManager:readMedia] Reading media content for file ID '${t}' in org '${e}'...`);let i=await this.client.files.readMedia(e,t,{token:this.client.token});return{media:i.media,meta:i.meta}}async create(e,t){let i=this.getFileMetaKind(t.kind),r=Xt.createSchema({kind:i,info:{name:t.name},key:t.key}),s={};t.parent&&(s.parent=t.parent),y.debug(`[FileManager:create] Creating file metadata '${t.name}' (kind: ${i})...`);let o=await this.client.files.createMeta(r,e,s,{token:this.client.token}),a=o.key;return y.debug(`[FileManager:create] Created file metadata successfully. Key: ${a}`),t.mediaContent!==void 0&&(y.debug(`[FileManager:create] Uploading file media for key '${a}'...`),await this.client.files.createMedia(t.mediaContent,e,a,{},{token:this.client.token}),y.debug("[FileManager:create] Media uploaded successfully.")),o}async patchMedia(e,t,i){y.debug(`[FileManager:patchMedia] Sending ${i.patchOps.length} patch op(s) for file ID '${t}' (current version: ${i.version})...`);let r={id:qp(),timestamp:Date.now(),patch:i.patchOps,version:i.version};return await this.client.files.patchMedia(e,t,r,{token:this.client.token})}async parseMediaInput(e){if(e.mediaPath&&e.stdin)throw new Error("Cannot specify both media path and STDIN.");let t;if(e.mediaPath){let i=Fp.resolve(e.mediaPath);if(y.debug(`[FileManager:parseMediaInput] Reading media file from: ${i}`),!kl.existsSync(i))throw new Error(`Media file not found at path: ${i}`);t=kl.readFileSync(i,"utf8")}else e.stdin&&(y.debug("[FileManager:parseMediaInput] Reading media from STDIN..."),t=await this.readStdin());if(t!==void 0)return this.validateParsedMedia(t)}validateParsedMedia(e){let t;try{t=JSON.parse(e)}catch{throw new Error("invalid API now platform file")}if(!t||typeof t!="object"||Array.isArray(t)||!("key"in t)||typeof t.key!="string"||!t.key.trim())throw new Error("invalid API now platform file");let i=t.key;return{content:t,key:i}}async readStdin(){return new Promise((e,t)=>{let i="";process.stdin.setEncoding("utf8"),process.stdin.on("data",r=>{i+=r}),process.stdin.on("end",()=>{e(i)}),process.stdin.on("error",r=>{t(r)})})}};var pi=class extends Ae{fileManager;constructor(e,t,i=new Z){super(e,t),this.fileManager=i}async resolveFileId(e,t="Select a file to read:"){let i=this.options.id;if(!i&&process.stdout.isTTY){y.debug("[files] ID not provided, fetching files list for interactive selection...");try{let r=await this.fileManager.list(e);r.length>0&&(i=await Ce(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.kind})`,value:s.key}))))}catch{}}return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --id <fid>."}),process.exit(1)),i}};var vo=class extends pi{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[files:list] Listing files for org: ${e}, kind: ${this.options.kind||"all"}, parent: ${this.options.parent||"root"}`);try{let t=await this.fileManager.list(e,{kind:this.options.kind,parent:this.options.parent});y.debug(`[files:list] Found ${t.length} files.`);let i=t.map(r=>({id:r.key,name:r.info?.name||"",kind:r.kind,isShortcut:r.isShortcut?"Yes":"No"}));this.formatter.list(i,["id","name","kind","isShortcut"],{headers:["ID","NAME","KIND","SHORTCUT"]})}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var wo=class extends pi{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[files:create] Creating file with options: name=${this.options.name}, kind=${this.options.kind}, org=${e}, parent=${this.options.parent}, media=${this.options.media}, stdin=${this.options.stdin}`),this.options.media&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let t=this.options.name;!t&&process.stdout.isTTY&&(t=await pe("Enter file name:")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));let i=this.options.kind;!i&&process.stdout.isTTY&&(i=await Ce("Select file kind:",[{name:"API Domain / Schema (domain)",value:"domain"},{name:"API Schema (api)",value:"api"},{name:"Folder (folder)",value:"folder"}])),i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Kind is required.",detail:"Specify --kind <kind> (allowed: api, domain, folder)."}),process.exit(1));try{let r=await this.fileManager.parseMediaInput({mediaPath:this.options.media,stdin:this.options.stdin}),s=await this.fileManager.create(e,{name:t,kind:i,parent:this.options.parent,mediaContent:r?.content,key:r?.key});this.formatter.success("File created successfully!",s)}catch(r){r instanceof Error&&(r.message.startsWith("Media file not found")||r.message==="Cannot specify both media path and STDIN.")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:r.message}),process.exit(1));let o=U(r);this.formatter.error({code:"CLI_ERR_API_FAILURE",...o}),process.exit(1)}}};var So=class extends pi{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[files:read] Reading file with options: id=${this.options.id}, org=${e}, meta=${this.options.meta}, media=${this.options.media}`);let t=await this.resolveFileId(e);try{if(this.options.media){y.debug(`[files:read] Fetching media content for file ID '${t}'...`);let r=(await this.fileManager.readMedia(e,t)).media;y.debug("[files:read] Media retrieved successfully."),this.formatter.format==="json"?console.log(JSON.stringify(r,null,2)):console.log(typeof r=="object"&&r!==null?JSON.stringify(r,null,2):r)}else{y.debug(`[files:read] Fetching metadata for file ID '${t}'...`);let i=await this.fileManager.read(e,t);y.debug("[files:read] Metadata retrieved successfully."),this.formatter.object(i)}}catch(i){let r=U(i);this.formatter.error(r),process.exit(1)}}};function vl(c){let e=c.command("files").description("Manage files and metadata");e.command("list").description("List files in an organization").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--kind <kind>","Filter by file kind (e.g. domain, api, folder)").option("--parent <parent>","Filter by parent folder ID").action(async t=>{let i=new K({format:N.resolved.format});await new vo(t,i).execute()}),e.command("create").description("Create a new file metadata record (and optionally upload media)").option("--name <name>","Name of the file").option("--kind <kind>","Kind of the file (e.g., domain, api)").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Parent folder ID").option("--media <path>","Local path to the file content/media to upload").option("--stdin","Read media content from STDIN").action(async t=>{let i=new K({format:N.resolved.format});await new wo(t,i).execute()}),e.command("read").description("Read file metadata or media content").option("--id <fid>","File ID").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--meta","Read file metadata (default)").option("--media","Read file media/content").action(async t=>{let i=new K({format:N.resolved.format});await new So(t,i).execute()})}import{InvalidArgumentError as wl}from"commander";function Yi(c){if(!/^\d+$/.test(c.trim()))throw new wl("Must be a positive integer.");let e=parseInt(c,10);if(e<1)throw new wl("Must be a positive integer.");return e}var g;(function(c){c.User="Semantic#User",c.Address="Semantic#Address",c.Organization="Semantic#Organization",c.Project="Semantic#Project",c.AbstractManyToMany="Semantic#AbstractManyToMany",c.Password="Semantic#Password",c.Username="Semantic#Username",c.CreatedTimestamp="Semantic#CreatedTimestamp",c.UpdatedTimestamp="Semantic#UpdatedTimestamp",c.DeletedTimestamp="Semantic#DeletedTimestamp",c.DeletedFlag="Semantic#DeletedFlag",c.PublicUniqueName="Semantic#PublicUniqueName",c.Title="Semantic#Title",c.Name="Semantic#Name",c.UserRole="Semantic#UserRole",c.OrganizationRole="Semantic#OrganizationRole",c.ProjectRole="Semantic#ProjectRole",c.AssociationRole="Semantic#AssociationRole",c.Status="Semantic#Status",c.Version="Semantic#Version",c.ImageURL="Semantic#ImageURL",c.FileURL="Semantic#FileURL",c.Markdown="Semantic#Markdown",c.HTML="Semantic#HTML",c.GeospatialCoordinates="Semantic#GeospatialCoordinates",c.Email="Semantic#Email",c.Phone="Semantic#Phone",c.Currency="Semantic#Currency",c.URL="Semantic#URL",c.SKU="Semantic#SKU",c.Description="Semantic#Description",c.Summary="Semantic#Summary",c.Calculated="Semantic#Calculated",c.Derived="Semantic#Derived",c.ClientIPAddress="Semantic#ClientIPAddress",c.StreetAddress="Semantic#StreetAddress",c.StreetAddressSupplemental="Semantic#StreetAddressSupplemental",c.City="Semantic#City",c.PostalCode="Semantic#PostalCode",c.Country="Semantic#Country",c.Region="Semantic#Region",c.ResourceOwnerIdentifier="Semantic#ResourceOwnerIdentifier",c.RelationalResourceOwner="Semantic#RelationalResourceOwner",c.OrganizationMembers="Semantic#OrganizationMembers",c.ProjectMembers="Semantic#ProjectMembers",c.OrganizationResource="Semantic#OrganizationResource",c.ProjectResource="Semantic#ProjectResource",c.CreatedBy="Semantic#CreatedBy",c.UpdatedBy="Semantic#UpdatedBy",c.DeletedBy="Semantic#DeletedBy",c.Tags="Semantic#Tags",c.Categories="Semantic#Categories",c.PeerRelation="Semantic#PeerRelation"})(g||(g={}));var q;(function(c){c.Entity="Entity",c.Property="Property",c.Association="Association"})(q||(q={}));var J;(function(c){c.Identity="Identity & Authentication",c.Lifecycle="Timestamps & Versioning",c.Content="Content & Media",c.Business="Business Data",c.Organization="Classification & Organization",c.Location="Location & Geography",c.Contact="Contact Information",c.Computed="Computed Values"})(J||(J={}));var Sl=c=>c.scope===q.Entity,Ao=c=>c.scope===q.Property,Xi=c=>c.scope===q.Association,at={[g.User]:{id:g.User,displayName:"User Entity",scope:q.Entity,description:"System users and accounts",category:J.Identity,hasConfig:!1},[g.Password]:{id:g.Password,displayName:"User Password",scope:q.Property,description:"Secure password field",category:J.Identity,applicableDataTypes:["string"],hasConfig:!0},[g.Username]:{id:g.Username,displayName:"Username",scope:q.Property,description:"User authentication identifier",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.UserRole]:{id:g.UserRole,displayName:"User Role Field",scope:q.Property,description:"User permissions and access level",category:J.Identity,applicableDataTypes:["string"],hasConfig:!0},[g.ResourceOwnerIdentifier]:{id:g.ResourceOwnerIdentifier,displayName:"Resource Owner Identifier",scope:q.Association,description:"Links record to owner user",category:J.Identity,hasConfig:!1},[g.RelationalResourceOwner]:{id:g.RelationalResourceOwner,displayName:"Relational Resource Owner",scope:q.Association,description:"Specifies that the target entity of this association acts as the relational owner context for ownership verification.",category:J.Identity,hasConfig:!1},[g.Organization]:{id:g.Organization,displayName:"Organization Entity",scope:q.Entity,description:"Applied to the top-level Organization entity",category:J.Identity,hasConfig:!0},[g.AbstractManyToMany]:{id:g.AbstractManyToMany,displayName:"Abstract Many-To-Many",scope:q.Association,description:"Hidden parent semantic for all M:N relationships",category:J.Organization,hasConfig:!1,isHidden:!0,isManyToMany:!0},[g.OrganizationMembers]:{id:g.OrganizationMembers,displayName:"Organization Members",scope:q.Association,description:"Applied to the association pointing from Organization to User",category:J.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Organization Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:g.Organization,target:g.User},{parent:g.User,target:g.Organization}],unmetMessage:"Organization Members semantic can only be applied to an association connecting an Organization entity and a User entity."}],properties:[{meta:{required:!0},value:{info:{name:"organization_role",displayName:"Organization Role",description:"The role of the user in the organization"},semantics:[{id:g.OrganizationRole}],type:"string",index:!0,required:!0,schema:{enum:["owner","admin","editor","viewer"],defaultValue:{type:"literal",value:"viewer"}}}},{meta:{required:!1},value:{info:{name:"organization_status",displayName:"Organization Status",description:"The status of the user in the organization"},semantics:[{id:g.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[g.Project]:{id:g.Project,displayName:"Project Entity",scope:q.Entity,description:"Applied to a Project entity",category:J.Identity,hasConfig:!1},[g.ProjectMembers]:{id:g.ProjectMembers,displayName:"Project Members",scope:q.Association,description:"Applied to the association pointing from Project to User",category:J.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Project Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:g.Project,target:g.User},{parent:g.User,target:g.Project}],unmetMessage:"Project Members semantic can only be applied to an association connecting a Project entity and a User entity."}],properties:[{meta:{required:!0},value:{info:{name:"project_role",displayName:"Project Role",description:"The role of the user in the project"},semantics:[{id:g.ProjectRole}],type:"string",index:!0,required:!0,schema:{enum:["owner","admin","editor","viewer"],defaultValue:{type:"literal",value:"viewer"}}}},{meta:{required:!1},value:{info:{name:"project_status",displayName:"Project Status",description:"The status of the user in the project"},semantics:[{id:g.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[g.OrganizationRole]:{id:g.OrganizationRole,displayName:"Organization Role Property",scope:q.Property,description:"Represents a membership role inside an organization",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.ProjectRole]:{id:g.ProjectRole,displayName:"Project Role Property",scope:q.Property,description:"Represents a membership role inside a project",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.AssociationRole]:{id:g.AssociationRole,displayName:"Association Role Property",scope:q.Property,description:"Represents a membership access role on a many-to-many association",category:J.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.OrganizationResource]:{id:g.OrganizationResource,displayName:"Organization Resources",scope:q.Association,description:"Represents resources owned by an organization",category:J.Identity,hasConfig:!1},[g.ProjectResource]:{id:g.ProjectResource,displayName:"Project Resources",scope:q.Association,description:"Represents resources owned by a project",category:J.Identity,hasConfig:!1},[g.CreatedBy]:{id:g.CreatedBy,displayName:"Created By",scope:q.Association,description:"Links record to the user who created it",category:J.Identity,hasConfig:!1},[g.UpdatedBy]:{id:g.UpdatedBy,displayName:"Updated By",scope:q.Association,description:"Links record to the user who last updated it",category:J.Identity,hasConfig:!1},[g.DeletedBy]:{id:g.DeletedBy,displayName:"Deleted By",scope:q.Association,description:"Links record to the user who soft-deleted it",category:J.Identity,hasConfig:!1},[g.CreatedTimestamp]:{id:g.CreatedTimestamp,displayName:"Creation Timestamp",scope:q.Property,description:"When record was created",category:J.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.UpdatedTimestamp]:{id:g.UpdatedTimestamp,displayName:"Update Timestamp",scope:q.Property,description:"When record was last modified",category:J.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.DeletedTimestamp]:{id:g.DeletedTimestamp,displayName:"Soft Delete Timestamp",scope:q.Property,description:"When record was marked deleted",category:J.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.DeletedFlag]:{id:g.DeletedFlag,displayName:"Soft Delete Flag",scope:q.Property,description:"Mark record as deleted",category:J.Lifecycle,applicableDataTypes:["boolean"],hasConfig:!1},[g.Address]:{id:g.Address,displayName:"Address Entity",scope:q.Entity,description:"Physical address entity",category:J.Contact,hasConfig:!1},[g.StreetAddress]:{id:g.StreetAddress,displayName:"Street Address",scope:q.Property,description:"Street address line",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.StreetAddressSupplemental]:{id:g.StreetAddressSupplemental,displayName:"Street Address Supplemental",scope:q.Property,description:"Supplemental street address line (e.g., Unit, Suite, Apartment, Floor)",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.City]:{id:g.City,displayName:"City",scope:q.Property,description:"City or locality",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.PostalCode]:{id:g.PostalCode,displayName:"Postal Code",scope:q.Property,description:"Postal or zip code",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Country]:{id:g.Country,displayName:"Country",scope:q.Property,description:"Country name or code",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Region]:{id:g.Region,displayName:"Region",scope:q.Property,description:"State, province, or region",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.Version]:{id:g.Version,displayName:"Version Number",scope:q.Property,description:"Auto-incrementing version counter",category:J.Lifecycle,applicableDataTypes:["number"],hasConfig:!1},[g.Title]:{id:g.Title,displayName:"Record Title",scope:q.Property,description:"Main title or heading",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Name]:{id:g.Name,displayName:"Name",scope:q.Property,description:"A person or pet name",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Description]:{id:g.Description,displayName:"Description",scope:q.Property,description:"Detailed description text",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Summary]:{id:g.Summary,displayName:"Summary",scope:q.Property,description:"Brief summary text",category:J.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Markdown]:{id:g.Markdown,displayName:"Markdown Content",scope:q.Property,description:"Formatted text content",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.HTML]:{id:g.HTML,displayName:"HTML Content",scope:q.Property,description:"Rich HTML content",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.ImageURL]:{id:g.ImageURL,displayName:"Image URL",scope:q.Property,description:"Link to image file",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.FileURL]:{id:g.FileURL,displayName:"File URL",scope:q.Property,description:"Link to file attachment",category:J.Content,applicableDataTypes:["string"],hasConfig:!0},[g.Status]:{id:g.Status,displayName:"Record Status",scope:q.Property,description:"Current state of record",category:J.Business,applicableDataTypes:["string"],hasConfig:!0},[g.Currency]:{id:g.Currency,displayName:"Currency",scope:q.Property,description:"Monetary value with currency",category:J.Business,applicableDataTypes:["number","string"],hasConfig:!0},[g.SKU]:{id:g.SKU,displayName:"SKU",scope:q.Property,description:"Product identification code",category:J.Business,applicableDataTypes:["string"],hasConfig:!0},[g.Email]:{id:g.Email,displayName:"Email",scope:q.Property,description:"Email address",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Phone]:{id:g.Phone,displayName:"Phone",scope:q.Property,description:"Phone number",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.URL]:{id:g.URL,displayName:"URL",scope:q.Property,description:"Web address or link",category:J.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.ClientIPAddress]:{id:g.ClientIPAddress,displayName:"Client IP Address",scope:q.Property,description:"Automatically populated client IP address",category:J.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.PublicUniqueName]:{id:g.PublicUniqueName,displayName:"Public Unique Name (Slug)",scope:q.Property,description:"URL-friendly unique identifier",category:J.Organization,applicableDataTypes:["string"],hasConfig:!0},[g.Tags]:{id:g.Tags,displayName:"Tags",scope:q.Association,description:"Enable tagging functionality",category:J.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Tags semantic can only be applied to multi-valued (array) associations."}]},[g.Categories]:{id:g.Categories,displayName:"Categories",scope:q.Association,description:"Enable categorization functionality",category:J.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany},[g.PeerRelation]:{id:g.PeerRelation,displayName:"Peer Relation",scope:q.Association,description:"Models peer, pairing, prerequisite, or recommendation relationships between domain entities",category:J.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:g.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Peer Relation semantic can only be applied to multi-valued (array) associations."}]},[g.GeospatialCoordinates]:{id:g.GeospatialCoordinates,displayName:"Geospatial Coordinates",scope:q.Property,description:"Location coordinates",category:J.Location,applicableDataTypes:["string"],hasConfig:!0},[g.Calculated]:{id:g.Calculated,displayName:"Calculated",scope:q.Property,description:"Auto-calculated field value",category:J.Computed,applicableDataTypes:["string","number","boolean","date","datetime","time","binary"],hasConfig:!0},[g.Derived]:{id:g.Derived,displayName:"Derived",scope:q.Property,description:"Value derived from other fields",category:J.Computed,applicableDataTypes:["string"],hasConfig:!0}};var Zt=class{domain;report=[];cachedEntitiesByDomainKey=new Map;cachedAssociationsByDomainKey=new Map;cachedLocalEntities;cachedForeignEntities;cachedAllEntities;cachedEntitiesBySemantic=new Map;cachedAssociationsBySemantic=new Map;cachedPropertiesBySemantic=new Map;constructor(e){this.domain=e}addIssue(e){this.report.push(e)}addIssues(e){e.length>0&&this.report.push(...e)}findEntity(e,t){let i=`${t??this.domain.key}:${e}`;if(this.cachedEntitiesByDomainKey.has(i))return this.cachedEntitiesByDomainKey.get(i)??void 0;let r=this.domain.findEntity(e,t);return this.cachedEntitiesByDomainKey.set(i,r??null),r}findAssociation(e,t){let i=`${t??this.domain.key}:${e}`;if(this.cachedAssociationsByDomainKey.has(i))return this.cachedAssociationsByDomainKey.get(i)??void 0;let r=this.domain.findAssociation(e,t);return this.cachedAssociationsByDomainKey.set(i,r??null),r}listEntities(e){return e?.foreignOnly?(this.cachedForeignEntities||(this.cachedForeignEntities=Array.from(this.domain.listEntities({foreignOnly:!0}))),this.cachedForeignEntities):e?.includeForeign?(this.cachedAllEntities||(this.cachedAllEntities=Array.from(this.domain.listEntities({includeForeign:!0}))),this.cachedAllEntities):(this.cachedLocalEntities||(this.cachedLocalEntities=Array.from(this.domain.listEntities()).filter(t=>t.domain.key===this.domain.key)),this.cachedLocalEntities)}getEntitiesWithSemantic(e){let t=this.cachedEntitiesBySemantic.get(e);if(t)return t;let i=this.listEntities().filter(r=>r.hasSemantic(e));return this.cachedEntitiesBySemantic.set(e,i),i}getUserEntities(){return this.getEntitiesWithSemantic(g.User)}getUserEntity(){let e=this.getUserEntities();return e.length===1?e[0]:void 0}getOrganizationEntities(){return this.getEntitiesWithSemantic(g.Organization)}getOrganizationEntity(){let e=this.getOrganizationEntities();return e.length===1?e[0]:void 0}getProjectEntities(){return this.getEntitiesWithSemantic(g.Project)}getProjectEntity(){let e=this.getProjectEntities();return e.length===1?e[0]:void 0}getAssociationsWithSemantic(e){let t=this.cachedAssociationsBySemantic.get(e);if(t)return t;let i=[];for(let r of this.listEntities())for(let s of r.listAssociations())s.hasSemantic(e)&&i.push(s);return this.cachedAssociationsBySemantic.set(e,i),i}getPropertiesWithSemantic(e){let t=this.cachedPropertiesBySemantic.get(e);if(t)return t;let i=[];for(let r of this.listEntities())for(let s of r.withInheritedProperties())s.hasSemantic(e)&&i.push({property:s,entity:r});return this.cachedPropertiesBySemantic.set(e,i),i}clearCache(){this.cachedEntitiesByDomainKey.clear(),this.cachedAssociationsByDomainKey.clear(),this.cachedLocalEntities=void 0,this.cachedForeignEntities=void 0,this.cachedAllEntities=void 0,this.cachedEntitiesBySemantic.clear(),this.cachedAssociationsBySemantic.clear(),this.cachedPropertiesBySemantic.clear()}};var Eo=new Set(["IN","EXISTS","SELECT","FROM","WHERE","AND","OR","NOT","NULL","TRUE","FALSE","BETWEEN","LIKE","INTO","JOIN","INNER JOIN","LEFT JOIN","RIGHT JOIN","FULL JOIN","CROSS JOIN","UNION","INTERSECT","EXCEPT","ORDER BY","GROUP BY","HAVING","DISTINCT","LIMIT","OFFSET","INSERT","UPDATE","DELETE","CREATE","ALTER","DROP","TRUNCATE","RENAME","GRANT","REVOKE","CASCADE","RESTRICT","FETCH","FIRST","NEXT","ROWS","ONLY","WINDOW","OVER","PARTITION BY","PRECEDING","FOLLOWING","UNBOUNDED","CURRENT ROW","FILTER","WITH","RECURSIVE","COLLATE"]);var Tr=class{validate(e,t){let i;if(typeof e=="string"?i=t.findEntity(e):i=e,!i){t.addIssue({field:"*",rule:"exists",message:`The "${e}" entity does not exist.`,help:"The entity must be defined in the domain.",key:e,kind:O,severity:"error",parentKind:O});return}this.validatePrimaryKey(i,t),this.minimumRequiredProperties(i,t),this.validateName(i,t),this.uniqueName(i,t)}validatePrimaryKey(e,t){e.primaryKey()||t.addIssue({field:"properties",rule:"primary_key",message:`The "${e.info.getLabel()}" entity has no identifier.`,help:"An entity that can exists by itself must have identifier defined.",severity:"error",key:e.key,kind:e.kind,parentKind:O})}hasPropertiesInherited(e){if(e.hasProperties())return!0;for(let t of e.listParents())if(this.hasPropertiesInherited(t))return!0;return!1}hasAssociationsInherited(e){if(e.hasAssociations())return!0;for(let t of e.listParents())if(this.hasAssociationsInherited(t))return!0;return!1}minimumRequiredProperties(e,t){let i=this.hasPropertiesInherited(e),r=this.hasAssociationsInherited(e);!i&&!r&&t.addIssue({field:"properties",rule:"required",message:`The "${e.info.getLabel()}" entity has no properties. It will be ignored.`,help:"Entities that have no properties are ignored in the data domain. No schema will be generated for it.",severity:"warning",key:e.key,kind:e.kind,parentKind:O})}validateName(e,t){let i=e.info.getLabel();if(!e.info.name){t.addIssue({field:"name",rule:"required",message:`The "${i}" entity has no name.`,help:"An entity must have a name.",severity:"error",key:e.key,kind:e.kind,parentKind:O});return}let r=e.info.name;r.length<2&&t.addIssue({field:"name",rule:"length",message:`The "${i}" entity name is too short.`,help:"The name must be at least 2 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:O}),r.length>31&&t.addIssue({field:"name",rule:"length",message:`The "${i}" entity name is too long.`,help:"The name must be at most 31 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:O}),/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)||t.addIssue({field:"name",rule:"format",message:`The "${i}" entity name is invalid.`,help:"The name must start with a letter (a-z) or underscore (_). Subsequent characters can be letters, digits (0-9), or underscores (_).",severity:"error",key:e.key,kind:e.kind,parentKind:O}),/^[A-Z]/.test(r)&&t.addIssue({field:"name",rule:"snake_case",message:`The "${i}" entity name is not in snake case.`,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:e.key,kind:e.kind,parentKind:O}),Eo.has(r.toUpperCase())&&t.addIssue({field:"name",rule:"reserved",message:`The "${i}" entity name is a reserved keyword.`,help:"The name should not be a reserved keyword.",severity:"error",key:e.key,kind:e.kind,parentKind:O}),/^verify[-_].*$/i.test(r)&&t.addIssue({field:"name",rule:"reserved_pattern",message:`The "${i}" entity name matches the reserved pattern "verify-*".`,help:'Entity names starting with "verify-" are reserved for system verification endpoints (e.g. verify-email, verify-phone).',severity:"error",key:e.key,kind:e.kind,parentKind:O})}uniqueName(e,t){let i=e.info.name?.toLowerCase();if(i){for(let r of t.listEntities())r.info.name?.toLowerCase()===i&&r.key!==e.key&&t.addIssue({field:"name",rule:"unique",message:`The "${i}" entity name is already used in the data domain.`,help:"The name must be unique. This includes references to other data domains.",severity:"error",key:r.key,kind:r.kind,parentKind:O});for(let r of t.listEntities({foreignOnly:!0}))r.info.name?.toLowerCase()===i&&r.key!==e.key&&t.addIssue({field:"name",rule:"unique",message:`The "${i}" entity name is already used in the foreign data domain.`,help:"The name must be unique. This includes references to other data domains.",severity:"error",key:r.key,kind:r.kind,parent:r.domain.key,parentKind:O})}}};function _o(c,e){let t=c.info.getLabel(),i=c.getParentInstance();if(!i)return;let r;if(i.kind===O)r=i.key;else{let a=i.getParentInstance();if(!a)return;r=a.key}let s=c.kind===be?"property":"association";if(!c.info.name){e.addIssue({field:"name",rule:"required",message:`The "${t}" ${s} has no name.`,help:`The ${s} must have a name.`,severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}});return}let o=c.info.name;o.length<2&&e.addIssue({field:"name",rule:"length",message:`The "${t}" ${s} name is too short.`,help:"The name must be at least 2 characters long.",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),o.length>59&&e.addIssue({field:"name",rule:"length",message:`The "${t}" ${s} name is too long.`,help:"The name must be at most 59 characters long.",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)||e.addIssue({field:"name",rule:"format",message:`The "${t}" ${s} name is invalid.`,help:"The name must start with a letter (a-z) or underscore (_). Subsequent characters can be letters, digits (0-9), or underscores (_).",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),/^[A-Z]/.test(o)&&e.addIssue({field:"name",rule:"snake_case",message:`The "${t}" ${s} name is not in snake case.`,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),Eo.has(o.toUpperCase())&&e.addIssue({field:"name",rule:"reserved",message:`The "${t}" ${s} name is a reserved keyword.`,help:"The name should not be a reserved keyword.",severity:"error",key:c.key,kind:c.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}function St(c,e){let t=c;for(let i of e){if(typeof t!="object"||t===null)return!1;if(t.properties&&typeof t.properties=="object"&&i in t.properties){t=t.properties[i];continue}return!(t.properties&&t.additionalProperties===!1||t.type&&t.type!=="object"&&t.type!=="any")}return!0}var jr=class{validate(e,t){let i;if(typeof e=="string"?i=t.domain.findProperty(e):i=e,!i){t.addIssue({field:"*",rule:"exists",message:`The "${e}" property does not exist.`,help:"The property must be defined in the domain.",key:e,kind:be,severity:"error",parentKind:O});return}this.validateName(i,t),this.validateMutability(i,t),this.validatePrimaryKeyDefault(i,t),this.validateJsonIndex(i,t),this.validateSchema(i,t)}validateMutability(e,t){let i=e.getParentInstance();if(!i)return;let r=e.info.getLabel();e.readOnly&&e.immutable&&t.addIssue({field:"immutable",rule:"property_mutability_exclusive",message:`The property "${r}" cannot be both read-only and immutable.`,help:"A property must either be editable anytime, set once on creation (immutable), or managed by the system (read-only). These states are mutually exclusive.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind});let s=!!e.writeOnly||e.hasSemantic(g.Password);s&&e.readOnly&&t.addIssue({field:"writeOnly",rule:"property_write_read_conflict",message:`The property "${r}" cannot be both write-only and read-only.`,help:"A property cannot be both write-only and read-only at the same time.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind}),e.primary&&!e.readOnly&&!e.immutable&&t.addIssue({field:"primary",rule:"primary_key_mutable",message:`The primary key property "${r}" must be either read-only or immutable.`,help:"Primary keys identify entity records and cannot be mutable on update. Specify readOnly: true for server-generated IDs or immutable: true for client-assigned identifiers.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind}),e.primary&&s&&t.addIssue({field:"writeOnly",rule:"primary_key_write_only",message:`The primary key property "${r}" cannot be write-only.`,help:"Primary keys identify entity records in URLs and responses, so they cannot be hidden with writeOnly.",severity:"error",key:e.key,kind:e.kind,parentKind:i.kind})}validateName(e,t){_o(e,t)}validatePrimaryKeyDefault(e,t){if(e.primary){let i=e.getParentInstance();if(!i)return;let r=e.schema?.defaultValue;if(r){if(r.type!=="function"||r.value!=="random"){let s=`The primary key property "${e.info.getLabel()}" has an invalid default value.`;t.addIssue({field:"schema.defaultValue",rule:"primary_key_default",message:s,help:'Primary key properties can only have the "random" function as their default value.',severity:"error",key:e.key,kind:e.kind,parentKind:i.kind})}}else{let s=`The primary key property "${e.info.getLabel()}" has no default value.`,o=e.readOnly?'Without a default generator (e.g., the "random" function), the database sequence or server must generate primary key values automatically.':'Without a default generator (e.g., the "random" function), the client application must generate and supply primary key values manually.';t.addIssue({field:"schema.defaultValue",rule:"primary_key_no_default",message:s,help:o,severity:"warning",key:e.key,kind:e.kind,parentKind:i.kind})}}}validateJsonIndex(e,t){let i=e.jsonIndex;if(!i)return;let r=e.getParentInstance();if(r){if(e.type!=="json"){t.addIssue({field:"jsonIndex",rule:"json_index_type_mismatch",message:`Property "${e.info.getLabel()}" has a JSON index config but its type is "${e.type}".`,help:'JSON index configuration can only be defined for properties of type "json".',severity:"error",key:e.key,kind:e.kind,parentKind:r.kind});return}if(i.paths&&e.jsonSchema)for(let s of i.paths){if(!s.path){t.addIssue({field:"jsonIndex.paths",rule:"json_index_path_empty",message:`Property "${e.info.getLabel()}" has an empty JSON path in its index config.`,help:"JSON path index configurations must specify a non-empty path.",severity:"error",key:e.key,kind:e.kind,parentKind:r.kind});continue}let o=s.path.split(".");St(e.jsonSchema,o)||t.addIssue({field:"jsonIndex.paths",rule:"json_index_path_invalid",message:`JSON path "${s.path}" in index config for property "${e.info.getLabel()}" is not valid according to the property's JSON Schema.`,help:"All indexed JSON paths must exist in the property's JSON Schema definition.",severity:"error",key:e.key,kind:e.kind,parentKind:r.kind})}}}validateSchema(e,t){let i=e.schema;if(!i)return;let r=e.getParentInstance();if(!r)return;if(!["number","string","date","datetime","time"].includes(e.type)&&(i.minimum!==void 0||i.maximum!==void 0)){let a=i.minimum!==void 0?"schema.minimum":"schema.maximum",n=e.info.getLabel();t.addIssue({field:a,rule:"schema_boundary_unsupported_type",message:`The property "${n}" of type "${e.type}" cannot define minimum or maximum boundary constraints.`,help:'Boundary constraints (minimum and maximum) are only supported on "number", "string", "date", "datetime", and "time" properties.',severity:"error",key:e.key,kind:e.kind,parentKind:r.kind});return}let o=!1;i.minimum!==void 0&&this.validateBoundaryValue(e,"minimum",i.minimum,r.kind,t)&&(o=!0),i.maximum!==void 0&&this.validateBoundaryValue(e,"maximum",i.maximum,r.kind,t)&&(o=!0),!o&&i.minimum!==void 0&&i.maximum!==void 0&&this.validateBoundaryRange(e,r.kind,t)}validateBoundaryRange(e,t,i){let{schema:r,type:s}=e;if(!r||r.minimum===void 0||r.maximum===void 0)return;let{minimum:o,maximum:a,exclusiveMinimum:n,exclusiveMaximum:l}=r,d=e.info.getLabel();if(s==="number"||s==="string"){if(typeof o!="number"||typeof a!="number")return;if(o>a){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum value (${o}) greater than its maximum value (${a}).`,help:"The minimum constraint must be less than or equal to the maximum constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}o===a&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}else if(s==="date"){if(typeof o!="string"||typeof a!="string"||!this.isValidIsoDate(o)||!this.isValidIsoDate(a))return;if(o>a){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum date (${o}) later than its maximum date (${a}).`,help:"The minimum date constraint must be earlier than or equal to the maximum date constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}o===a&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum dates are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}else if(s==="datetime"){if(typeof o!="string"||typeof a!="string"||!this.isValidIsoDateTime(o)||!this.isValidIsoDateTime(a))return;let p=Date.parse(o),m=Date.parse(a);if(p>m){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum datetime (${o}) later than its maximum datetime (${a}).`,help:"The minimum datetime constraint must be earlier than or equal to the maximum datetime constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}p===m&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum datetimes are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}else if(s==="time"){if(typeof o!="string"||typeof a!="string"||!this.isValidIsoTime(o)||!this.isValidIsoTime(a))return;let p=this.isoTimeToSeconds(o),m=this.isoTimeToSeconds(a);if(p>m){i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has a minimum time (${o}) later than its maximum time (${a}).`,help:"The minimum time constraint must be earlier than or equal to the maximum time constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t});return}p===m&&(n||l)&&i.addIssue({field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${d}" has exclusive boundaries that result in an empty range (${o} to ${a}).`,help:"When minimum and maximum times are equal, exclusive bounds create an unsatisfiable constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t})}}validateBoundaryValue(e,t,i,r,s){let{type:o}=e,a=e.info.getLabel(),n=t==="minimum"?"schema_minimum_type":"schema_maximum_type",l=`schema.${t}`;if(o==="number"){if(typeof i!="number")return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "number". Expected a number.`,help:`The ${t} constraint for a number property must be a number.`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="string"){if(typeof i!="number"||!Number.isInteger(i)||i<0)return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "string". Expected a non-negative integer.`,help:`The ${t} constraint for a string property must be a non-negative integer representing the length.`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="date"){if(!this.isValidIsoDate(i))return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "date". Expected an ISO 8601 date string (YYYY-MM-DD).`,help:`The ${t} constraint for a date property must be an ISO 8601 full-date string (e.g. 2024-01-01).`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="datetime"){if(!this.isValidIsoDateTime(i))return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "datetime". Expected an ISO 8601 datetime string.`,help:`The ${t} constraint for a datetime property must be an ISO 8601 date-time string (e.g. 2024-01-01T00:00:00Z).`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0}else if(o==="time"&&!this.isValidIsoTime(i))return s.addIssue({field:l,rule:n,message:`The property "${a}" has an invalid ${t} value for type "time". Expected an ISO 8601 time string.`,help:`The ${t} constraint for a time property must be an ISO 8601 time string (e.g. 12:00:00).`,severity:"error",key:e.key,kind:e.kind,parentKind:r}),!0;return!1}isValidIsoDate(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}$/.test(e))return!1;let[t,i,r]=e.split("-").map(Number),s=new Date(Date.UTC(t,i-1,r));return s.getUTCFullYear()===t&&s.getUTCMonth()===i-1&&s.getUTCDate()===r}isValidIsoDateTime(e){if(typeof e!="string"||!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})$/.test(e))return!1;let t=e.substring(0,10);return this.isValidIsoDate(t)?!isNaN(Date.parse(e)):!1}isValidIsoTime(e){if(typeof e!="string")return!1;let t=/^(\d{2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?(?:Z|[+-]\d{2}:?\d{2})?$/.exec(e);if(!t)return!1;let i=Number(t[1]),r=Number(t[2]),s=t[3]!==void 0?Number(t[3]):0;return i>=0&&i<24&&r>=0&&r<60&&s>=0&&s<60}isoTimeToSeconds(e){let t=/^(\d{2}):(\d{2})(?::(\d{2}(?:\.\d+)?))?(?:Z|[+-](\d{2}):?(\d{2}))?$/.exec(e);if(!t)return 0;let i=Number(t[1]),r=Number(t[2]),s=t[3]!==void 0?Number(t[3]):0,o=i*3600+r*60+s;if(t[4]!==void 0&&t[5]!==void 0){let a=e.includes("+")?1:-1,n=(Number(t[4])*3600+Number(t[5])*60)*a;o-=n}return o}};var Al=c=>{let e=c.trim();return e=e.match(/[A-Z]{2,}(?=[ A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g)?.map(t=>t.toLowerCase()).join("_")||"",e};import El from"dompurify";var dc;function Kp(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}if(Kp()){let{JSDOM:c}=await import("jsdom"),{window:e}=new c("<!DOCTYPE html>");dc=El(e)}else dc=El;var _l=dc;function Bp(c){return _l.sanitize(c)}function xl(c,e="untitled_column"){let t=Bp(c);return t=Al(t),t=t.replace(/[\s-]+/g,"_"),t=t.replace(/[^a-z0-9_]/g,""),t=t.replace(/^_+|_+$/g,""),t||e}function Il(c,e,t="untitled_table"){let i=xl(c,t);return`${xl(e.slice(0,8))}_${i}`}function Pl(c){let{entityName:e,assocName:t,targetEntityName:i,pkName:r,useTargetTableInColumnName:s}=c;if(!e||!t||!r)throw new Error(`entityName, assocName, and pkName are required when computing foreign key column name (received entityName: "${e}", assocName: "${t}", pkName: "${r}")`);let o;return s&&i?o=`${e}_${t}_${i}_${r}`:o=`${e}_${t}_${r}`,pc(o)}function Gp(c,e=0){let t=3735928559^e,i=1103547991^e;for(let r=0,s;r<c.length;r++)s=c.charCodeAt(r),t=Math.imul(t^s,2654435761),i=Math.imul(i^s,1597334677);return t=Math.imul(t^t>>>16,2246822507)^Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507)^Math.imul(t^t>>>13,3266489909),4294967296*(2097151&i)+(t>>>0)}function pc(c){if(c.length<=63)return c;let e=Gp(c).toString(16).padStart(8,"0").substring(0,8);return`${c.substring(0,54)}_${e}`}function Rl(c,e){let t=(typeof c=="string"?c:c?.getExposedName())?.trim();if(!t)throw new Error("sourceEntity is required when computing join table source foreign key column name");let i=typeof e=="string"?e.trim():e?.getExposedName()?.trim();if(!i)throw new Error("sourcePk is required when computing join table source foreign key column name");return pc(`${t}_${i}`)}function $l(c,e){let t=(typeof c=="string"?c:c?.getExposedName())?.trim();if(!t)throw new Error("assoc is required when computing join table target foreign key column name");let i=typeof e=="string"?e.trim():e?.getExposedName()?.trim();if(!i)throw new Error("targetPk is required when computing join table target foreign key column name");return pc(`${t}_${i}`)}var Cr=class{validate(e,t){let i;if(typeof e=="string"?i=t.findAssociation(e):i=e,!i){t.addIssue({field:"*",rule:"exists",message:`The "${e}" association does not exist.`,help:"The association must be defined in the domain.",key:e,kind:se,severity:"error",parentKind:O});return}this.validateName(i,t),this.validateTargets(i,t),this.validateSchema(i,t),this.validateJoinTableColumnCollision(i,t),this.validateLink(i,t)}validateName(e,t){_o(e,t)}validateTargets(e,t){let i=e.info.getLabel(),r=e.getParentInstance();if(!e.targets.length){t.addIssue({field:"targets",rule:"required",message:`The "${i}" association has no target.`,help:"An association must have at least one target.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O});return}e.isManyToMany()&&e.targets.length>1&&t.addIssue({field:"targets",rule:"mn_association_union_target_not_supported",message:`The "${i}" association is a Many-to-Many association and cannot have multiple target entities.`,help:"Many-to-Many associations must target exactly one entity because join tables do not support union or polymorphic targets.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O});for(let s of e.targets)t.findEntity(s.key,s.domain)||t.addIssue({field:"targets",rule:"exists",message:`The "${i}" association has an invalid target "${s.key}".`,help:"The target must be defined in the domain.",severity:"error",key:e.key,kind:e.kind,parent:r.key,parentKind:O})}validateSchema(e,t){let i=e.info.getLabel(),r=e.getParentInstance();e.multiple&&e.schema?.embedded===!0&&t.addIssue({field:"schema.embedded",rule:"embedded_not_supported_on_multiple_associations",message:`The "${i}" association has schema.embedded set to true but is multi-valued (multiple: true). Embedded hydration is not supported on multi-valued associations.`,help:'Remove "schema.embedded: true" or set multiple to false. Multi-valued associations must be accessed via sub-resource endpoints.',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O})}validateJoinTableColumnCollision(e,t){if(e.isLinked()||!e.isManyToMany())return;let i=e.getParentInstance();if(!i)return;let r=i.primaryKey();if(r)for(let s of e.targets){let a=t.findEntity(s.key,s.domain)?.primaryKey();if(!a)continue;let n=Rl(i,r),l=$l(e,a);if(n.toLowerCase()===l.toLowerCase()){let d=e.info.getLabel();t.addIssue({field:"name",rule:"association_join_table_column_collision",message:`The "${d}" association's join table foreign key column "${l}" collides with the source entity's foreign key column "${n}".`,help:"Rename the association so it does not match the source entity name.",severity:"error",key:e.key,kind:e.kind,parent:i.key,parentKind:O});break}}}validateLink(e,t){let i=e.link;if(!i)return;let r=e.info.getLabel(),s=e.getParentInstance();if(!i.key||!i.key.trim()){t.addIssue({field:"link.key",rule:"association_link_target_missing",message:`The "${r}" association is marked as linked but does not specify a target association key.`,help:'Provide a valid association key in the "link.key" property.',severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});return}if(i.key===e.key){t.addIssue({field:"link.key",rule:"association_link_self_reference",message:`The "${r}" association cannot link to itself.`,help:"Specify a different target association key to establish a reciprocal proxy.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});return}let o=!i.domain||i.domain===t.domain.key?t.domain:t.domain.dependencies.get(i.domain);if(!o){t.addIssue({field:"link.domain",rule:"association_link_domain_not_found",message:`The "${r}" association links to domain "${i.domain}", which is not loaded as a dependency in the current domain.`,help:"Add the foreign domain as a dependency or remove the domain qualification.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});return}let a=o.graph.node(i.key);if(!a){t.addIssue({field:"link.key",rule:"association_link_target_not_found",message:`The "${r}" association links to "${i.key}", but no matching element exists in the domain.`,help:"Ensure the target association key exists in the domain model.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});return}if(a.kind!==se){t.addIssue({field:"link.key",rule:"association_link_target_not_association",message:`The "${r}" association links to "${i.key}", which is a ${a.kind}, not a DomainAssociation.`,help:"Target association key must point to a DomainAssociation.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});return}let n=a;if(n.isLinked()){t.addIssue({field:"link.key",rule:"association_link_chained_proxy",message:`The "${r}" association links to "${n.info.getLabel()}", which is also a linked association. Chained association links are not permitted.`,help:"Point the link directly to the primary source of truth association.",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});return}n.isManyToMany()||t.addIssue({field:"link.key",rule:"association_link_target_not_many_to_many",message:`The "${r}" association links to "${n.info.getLabel()}", which is not a Many-to-Many association. Reciprocal association links are only supported for Many-to-Many associations.`,help:"Ensure the primary association has multiple: true and an active M:N semantic (e.g. PeerRelation).",severity:"error",key:e.key,kind:e.kind,parent:s?.key,parentKind:O});let l=n.getParentInstance();s&&l&&(n.targets.some(p=>{let m=p.domain??n.domain.key;return p.key===s.key&&m===s.domain.key})||t.addIssue({field:"link.key",rule:"association_link_target_mismatch",message:`The "${r}" association on entity "${s.info.getLabel()}" links to "${n.info.getLabel()}", but "${n.info.getLabel()}" does not target "${s.info.getLabel()}".`,help:`Ensure the linked primary association includes "${s.info.getLabel()}" in its targets list.`,severity:"error",key:e.key,kind:e.kind,parent:s.key,parentKind:O}),e.targets.length>0&&(e.targets.some(m=>{let h=m.domain??e.domain.key;return m.key===l.key&&h===l.domain.key})||t.addIssue({field:"targets",rule:"association_link_reciprocal_target_missing",message:`The "${r}" linked association must target the primary association's owner entity "${l.info.getLabel()}".`,help:`Add "${l.info.getLabel()}" to the targets of "${r}".`,severity:"error",key:e.key,kind:e.kind,parent:s.key,parentKind:O})))}};var Dr=class{semanticType=g.User;validate(e){let t=e.getUserEntities();t.length===0?e.addIssue({field:"semantics",rule:"recommended",message:"No entity with User taxonomy found in the domain.",help:"It is recommended to have an entity with the User taxonomy for authentication purposes.",severity:"warning",key:"user_semantic",kind:O,parentKind:O}):t.length>1&&e.addIssue({field:"semantics",rule:"one_user",message:"There is more than one entity with User taxonomy in the domain.",help:"There can be only one user in the system. Remove the additional User taxonomies.",severity:"error",key:"user_semantic",kind:O,parentKind:O});for(let i of t){let r=!1,s=!1,o=!1;for(let a of i.withInheritedProperties())if(a.hasSemantic(g.Username)&&(r=!0),a.hasSemantic(g.Password)&&(s=!0),a.hasSemantic(g.UserRole)&&(o=!0),r&&s&&o)break;r||e.addIssue({field:"semantics",rule:"has_username",message:"No username property on the User entity found.",help:'It is recommended to set the "username" property semantic for APIs supporting authentication.',severity:"warning",key:"user_semantic",kind:O,parentKind:O}),s||e.addIssue({field:"semantics",rule:"has_password",message:"No password property on the User entity found.",help:'It is recommended to set the "password" property semantic for APIs supporting authentication.',severity:"warning",key:"user_semantic",kind:O,parentKind:O}),o||e.addIssue({field:"semantics",rule:"has_user_role",message:"No role property on the User entity found.",help:'It is recommended to set the "User role" property semantic for APIs supporting authentication.',severity:"warning",key:"user_semantic",kind:O,parentKind:O})}for(let i of e.listEntities()){let r=!1,s=!1;for(let o of i.withInheritedProperties())o.hasSemantic(g.Username)&&(r=!0),o.hasSemantic(g.Password)&&(s=!0);(r||s)&&!i.hasSemantic(g.User)&&e.addIssue({field:"semantics",rule:"user_taxonomy_required",message:`The "${i.info.getLabel()}" entity has Username or Password properties but does not have the User taxonomy.`,help:"Entities containing authentication credentials like usernames or passwords must be tagged with the User taxonomy.",severity:"error",key:i.key,kind:i.kind,parentKind:O}),s&&!r&&e.addIssue({field:"semantics",rule:"username_required_for_password",message:`The "${i.info.getLabel()}" entity has Password credentials but lacks Username semantics.`,help:"An entity with Password credentials must also define a Username property for authentication.",severity:"error",key:i.key,kind:i.kind,parentKind:O})}}};var Lr=class{semanticType=[g.CreatedTimestamp,g.UpdatedTimestamp];validate(e){for(let t of e.listEntities()){let i=!1,r=!1;for(let s of t.withInheritedProperties())s.hasSemantic(g.CreatedTimestamp)&&(i=!0),s.hasSemantic(g.UpdatedTimestamp)&&(r=!0);i||e.addIssue({field:"semantics",rule:"recommended",message:`The "${t.info.getLabel()}" entity does not have a CreatedTimestamp taxonomy.`,help:"It is recommended to have a CreatedTimestamp property to track when the entity was created.",severity:"info",key:t.key,kind:t.kind,parentKind:O}),r||e.addIssue({field:"semantics",rule:"recommended",message:`The "${t.info.getLabel()}" entity does not have an UpdatedTimestamp taxonomy.`,help:"It is recommended to have an UpdatedTimestamp property to track when the entity was last modified.",severity:"info",key:t.key,kind:t.kind,parentKind:O})}}};var Mr=class{semanticType=[g.DeletedTimestamp,g.DeletedFlag];validate(e){for(let t of e.listEntities()){let i=!1;for(let r of t.withInheritedProperties())if(r.hasSemantic(g.DeletedTimestamp)||r.hasSemantic(g.DeletedFlag)){i=!0;break}i||e.addIssue({field:"semantics",rule:"recommended",message:`The "${t.info.getLabel()}" entity does not have soft delete taxonomy.`,help:"It is recommended to have either a DeletedTimestamp or DeletedFlag property for soft deletion.",severity:"info",key:t.key,kind:t.kind,parentKind:O})}}};var Ur=class{semanticType=["*:datatype","datatype"];validate(e){for(let t of e.listEntities())for(let i of t.withInheritedProperties())for(let r of i.semantics){let s=at[r.id];Ao(s)&&s.applicableDataTypes&&(s.applicableDataTypes.includes(i.type)||e.addIssue({field:"semantics",rule:"type_mismatch",message:`The "${i.info.getLabel()}" property has the "${s.displayName}" semantic applied, but its type "${i.type}" is not compatible.`,help:`The "${s.displayName}" semantic can only be applied to properties of type(s): ${s.applicableDataTypes.join(", ")}.`,severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O}))}}};var zr=class{semanticType=g.Currency;validate(e){let t=e.getPropertiesWithSemantic(g.Currency);for(let{property:i,entity:r}of t){let s=i.getSemantic(g.Currency);if(s){let o=s.config;i.type==="number"&&o?.allowedCurrencies&&o.allowedCurrencies.length>1&&e.addIssue({field:"semantics",rule:"currency_number_multiple",message:`The "${i.info.getLabel()}" property has the Currency semantic and is a Number, but allows multiple currencies.`,help:"Number properties cannot accept currency codes. Please change the property type to String, or restrict allowedCurrencies to exactly one currency.",severity:"error",key:i.key,kind:i.kind,parent:r.key,parentKind:O})}}}};var Vr=class{semanticType=g.GeospatialCoordinates;validate(e){for(let t of e.listEntities()){let i=new Map;for(let r of t.withInheritedProperties()){let s=r.getSemantic(g.GeospatialCoordinates);if(s){let o=s.config??{},a=!!o.enableDistanceQueries,n=!!o.enableBoundingBoxQueries,l=!!o.enablePolygonQueries,d=!!o.enableGeoClustering;if(a||n||l||d){let p=(o.apiEndpointPrefix||"/nearby").trim().toLowerCase(),m=i.get(p)??[];m.push(r.info.getLabel()),i.set(p,m)}}}for(let[r,s]of i.entries())s.length>1&&e.addIssue({field:"semantics",rule:"geospatial_endpoint_collision",message:`The "${t.info.getLabel()}" entity has multiple geospatial properties (${s.join(", ")}) sharing the same API endpoint prefix "${r}".`,help:"Each geospatial property on the same entity must use a unique apiEndpointPrefix to avoid query endpoint collisions (e.g., /nearby, /nearby-office).",severity:"error",key:t.key,kind:t.kind,parentKind:O})}}};function Fr(c,e,t){let i=e.getParentInstance();if(!i)return;let r=Array.from(e.listTargets()),s=[i,...r];for(let o of e.listProperties()){let a=o.info.name;if(a)for(let n of s)Array.from(n.withInheritedProperties()).find(d=>d.info.name===a)&&t.addIssue({field:"properties",rule:`${c}_property_collision`,message:`Property "${a}" on association "${e.info.getLabel()}" collides with a property of the same name on entity "${n.info.getLabel()}".`,help:`Rename the property "${a}" on the association to avoid conflicts when joining tables in the API (e.g., use a prefix like "${c.split("_")[0]}_${a}").`,severity:"error",key:o.key,kind:o.kind,parent:e.key,parentKind:se})}}function qr(c,e,t,i){let r=[],s=[];for(let o of t){let a=o.getSemantic(c);if(a)if(a.link){s.push(o),a.config&&Object.keys(a.config).length>0&&i.addIssue({field:"semantics",rule:"semantic_link_config_forbidden",message:`The association "${o.info.getLabel()}" has a semantic link set for "${c}", but also defines "config". Configuration should only be set on the primary semantic.`,help:'Remove the "config" property from the linked semantic definition.',severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:O});let n=i.findAssociation(a.link.key,a.link.domain);if(!n)i.addIssue({field:"semantics",rule:"semantic_link_target_not_found",message:`The association "${o.info.getLabel()}" has a semantic link targeting "${a.link.key}", but no matching association exists in the domain.`,help:"Update the link target key to point to an existing association with the primary semantic.",severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:O});else{let l=n.getSemantic(c);l?l.link&&i.addIssue({field:"semantics",rule:"semantic_link_target_is_link",message:`The association "${o.info.getLabel()}" links to "${n.info.getLabel()}", which is also a semantic link.`,help:"Point the link directly to the primary association with the source of truth configuration.",severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:O}):i.addIssue({field:"semantics",rule:"semantic_link_target_invalid",message:`The association "${o.info.getLabel()}" links to "${n.info.getLabel()}", but the target association does not have the "${c}" semantic.`,help:`Ensure the target association has the "${c}" semantic applied.`,severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:O})}}else r.push(o)}if(t.length>1){if(r.length===0)i.addIssue({field:"semantics",rule:"semantic_link_primary_missing",message:`All associations with the "${c}" semantic are defined as links, but no primary association exists.`,help:'Remove the "link" property from one association to designate it as the primary source of truth.',severity:"error",key:s[0].key,kind:s[0].kind,parent:s[0].getParentInstance()?.key,parentKind:O});else if(r.length>1)for(let o=1;o<r.length;o++){let a=r[o];i.addIssue({field:"semantics",rule:`${e}_link_required`,message:`Multiple associations have the "${c}" semantic, but "${a.info.getLabel()}" is missing a "link" to the primary association.`,help:'Define a "link" property pointing to the primary association key, and remove its "config".',severity:"error",key:a.key,kind:a.kind,parent:a.getParentInstance()?.key,parentKind:O})}}}var Kr=class{semanticType=g.Organization;validate(e){let t=e.getOrganizationEntities();if(t.length===0)return;t.length>1&&e.addIssue({field:"semantics",rule:"single_organization_entity",message:"Multiple entities marked with the Organization semantic found.",help:"Only one entity can be designated as the Organization per data domain. Remove the Organization semantic from additional entities.",severity:"error",key:"organization_semantic",kind:O,parentKind:O});let i=t[0],r=e.getUserEntity();if(!r){e.addIssue({field:"semantics",rule:"organization_requires_user",message:"An Organization entity is defined but no User entity exists.",help:"Multi-tenant organization structures require a User entity to establish memberships.",severity:"error",key:"organization_semantic",kind:O,parentKind:O});return}let s=Array.from(i.withInheritedAssociations()).find(l=>l.hasSemantic(g.OrganizationMembers)),o=Array.from(r.withInheritedAssociations()).find(l=>l.hasSemantic(g.OrganizationMembers));!s&&!o&&e.addIssue({field:"semantics",rule:"organization_members_assoc_missing",message:`Organization entity "${i.info.getLabel()}" is missing an association marked with Semantic#OrganizationMembers pointing to the User entity.`,help:"Please add an association from the Organization entity to the User entity (or vice versa) and apply the Semantic#OrganizationMembers tag.",severity:"error",key:"organization_semantic",kind:O,parentKind:O}),s&&(s.targets.length===1&&s.targets[0].key===r.key||e.addIssue({field:"semantics",rule:"organization_members_target_mismatch",message:`The association "${s.info.getLabel()}" marked with Semantic#OrganizationMembers must have exactly one target pointing to the User entity.`,help:"Ensure the OrganizationMembers association has a single target pointing to the User entity.",severity:"error",key:s.key,kind:s.kind,parent:i.key,parentKind:O})),o&&(o.targets.length===1&&o.targets[0].key===i.key||e.addIssue({field:"semantics",rule:"organization_members_user_target_mismatch",message:`The association "${o.info.getLabel()}" marked with Semantic#OrganizationMembers on User entity must target the Organization entity.`,help:"Change the target of the OrganizationMembers association on the User entity to point to Organization.",severity:"error",key:o.key,kind:o.kind,parent:r.key,parentKind:O}));let a=[s,o].filter(Boolean);a.length>0&&qr(g.OrganizationMembers,"organization_members",a,e);let n=a.find(l=>!l.getSemantic(g.OrganizationMembers)?.link);if(n){Fr("organization_members",n,e);let l=n.getParentInstance(),d=Array.from(n.listProperties()).filter(p=>p.hasSemantic(g.OrganizationRole));if(d.length===0)e.addIssue({field:"semantics",rule:"organization_role_missing",message:`Association "${n.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${l?.info.getLabel()}" is missing a property marked with Semantic#OrganizationRole.`,help:"Please add a string property to the OrganizationMembers association to track membership roles and mark it with Semantic#OrganizationRole.",severity:"error",key:n.key,kind:n.kind,parent:l?.key,parentKind:O});else if(d.length>1)e.addIssue({field:"semantics",rule:"organization_role_multiple",message:`Association "${n.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${l?.info.getLabel()}" has multiple properties marked with Semantic#OrganizationRole. Only one property can be marked as OrganizationRole per association.`,help:"Ensure only one property on the OrganizationMembers association has the Semantic#OrganizationRole tag. If you need multiple roles, they must not all be marked as the primary OrganizationRole.",severity:"error",key:n.key,kind:n.kind,parent:l?.key,parentKind:O});else{let p=d[0],m=p.schema?.enum;(!m||!Array.isArray(m)||m.length===0)&&e.addIssue({field:"semantics",rule:"organization_role_enum_missing",message:`The organization role property "${p.info.getLabel()}" on association "${n.info.getLabel()}" should define an enum of allowed roles (e.g. ['owner', 'editor', 'viewer']).`,help:"Define an enum array inside the schema of the OrganizationRole property to set valid roles.",severity:"warning",key:p.key,kind:p.kind,parent:n.key,parentKind:se})}}}};var Br=class{semanticType=g.Project;validate(e){let t=e.getProjectEntities();if(t.length===0)return;t.length>1&&e.addIssue({field:"semantics",rule:"single_project_entity",message:"Multiple entities marked with the Project semantic found.",help:"Only one entity can be designated as the Project per data domain. Remove the Project semantic from additional entities.",severity:"error",key:"project_semantic",kind:O,parentKind:O});let i=e.getUserEntity(),r=i?Array.from(i.withInheritedAssociations()).filter(s=>s.hasSemantic(g.ProjectMembers)):[];for(let s of r)s.targets.length===1&&t.some(a=>a.key===s.targets[0].key)||e.addIssue({field:"semantics",rule:"project_members_user_target_mismatch",message:`The association "${s.info.getLabel()}" marked with Semantic#ProjectMembers on User entity must target the Project entity.`,help:"Change the target of the ProjectMembers association on User entity to point to Project.",severity:"error",key:s.key,kind:s.kind,parent:i?.key,parentKind:O});for(let s of t){let o=Array.from(s.withInheritedAssociations()).find(d=>d.hasSemantic(g.ProjectMembers)),a=r.find(d=>d.targets.some(p=>p.key===s.key));o&&(i&&o.targets.length===1&&o.targets[0].key===i?.key||e.addIssue({field:"semantics",rule:"project_members_target_mismatch",message:`The association "${o.info.getLabel()}" marked with Semantic#ProjectMembers must have exactly one target pointing to the User entity.`,help:"Ensure the ProjectMembers association has a single target pointing to the User entity.",severity:"error",key:o.key,kind:o.kind,parent:s.key,parentKind:O}));let n=[o,a].filter(Boolean),l=n.find(d=>!d.getSemantic(g.ProjectMembers)?.link);if(l){Fr("project_members",l,e);let d=l.getParentInstance(),p=Array.from(l.listProperties()).filter(m=>m.hasSemantic(g.ProjectRole));if(p.length===0)e.addIssue({field:"semantics",rule:"project_role_missing",message:`Association "${l.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${d?.info.getLabel()}" is missing a property marked with Semantic#ProjectRole.`,help:"Please add a string property to the ProjectMembers association to track membership roles and mark it with Semantic#ProjectRole.",severity:"error",key:l.key,kind:l.kind,parent:d?.key,parentKind:O});else if(p.length>1)e.addIssue({field:"semantics",rule:"project_role_multiple",message:`Association "${l.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${d?.info.getLabel()}" has multiple properties marked with Semantic#ProjectRole. Only one property can be marked as ProjectRole per association.`,help:"Ensure only one property on the ProjectMembers association has the Semantic#ProjectRole tag. If you need multiple roles, they must not all be marked as the primary ProjectRole.",severity:"error",key:l.key,kind:l.kind,parent:d?.key,parentKind:O});else{let m=p[0],h=m.schema?.enum;(!h||!Array.isArray(h)||h.length===0)&&e.addIssue({field:"semantics",rule:"project_role_enum_missing",message:`The project role property "${m.info.getLabel()}" on association "${l.info.getLabel()}" should define an enum of allowed roles (e.g. ['owner', 'editor', 'viewer']).`,help:"Define an enum array inside the schema of the project role property to set valid roles.",severity:"warning",key:m.key,kind:m.kind,parent:l.key,parentKind:se})}}n.length>0&&qr(g.ProjectMembers,"project_members",n,e)}}};var Gr=class{semanticType=["*:preconditions","association_preconditions"];validate(e){for(let t of e.listEntities())for(let i of t.listAssociations())for(let r of i.semantics)try{i.checkPreconditions(r.id)}catch(s){let o=s instanceof Error?s.message:String(s);e.addIssue({field:"semantics",rule:"association_semantic_precondition_unmet",message:o,help:"Ensure the association meets all cardinality and entity pairing preconditions for this semantic.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O})}}};var Jr=class{semanticType=[g.Name,g.Title];validate(e){for(let t of e.listEntities()){let i=Array.from(t.withInheritedProperties()).filter(s=>s.hasSemantic(g.Name));if(i.length>1){let s=i.map(o=>`"${o.info.getLabel()}"`).join(", ");e.addIssue({field:"properties",rule:"entity_multiple_name_semantics",message:`The entity "${t.info.getLabel()}" has multiple properties annotated with SemanticType.Name (${s}).`,help:"An entity can have at most one property annotated with SemanticType.Name to uniquely identify the record's label.",severity:"error",key:t.key,kind:t.kind,parentKind:O})}let r=Array.from(t.withInheritedProperties()).filter(s=>s.hasSemantic(g.Title));if(r.length>1){let s=r.map(o=>`"${o.info.getLabel()}"`).join(", ");e.addIssue({field:"properties",rule:"entity_multiple_title_semantics",message:`The entity "${t.info.getLabel()}" has multiple properties annotated with SemanticType.Title (${s}).`,help:"An entity can have at most one property annotated with SemanticType.Title to represent the title of the work.",severity:"error",key:t.key,kind:t.kind,parentKind:O})}}}};var Wr=class{semanticType=[g.Tags,g.Categories];validate(e){for(let t of e.listEntities())for(let i of t.listAssociations()){if(i.hasSemantic(g.Tags)&&(i.multiple||e.addIssue({field:"multiple",rule:"tags_multiple_required",message:`The "${i.info.getLabel()}" association has Tags semantic but is not multi-valued (multiple: false).`,help:"Tags semantics can only be applied to multi-valued (array) associations.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O}),!i.isLinked()))for(let r of i.targets){let s=e.findEntity(r.key,r.domain);if(s){Array.from(s.withInheritedProperties()).some(n=>n.hasSemantic(g.Name))||e.addIssue({field:"semantics",rule:"tags_target_missing_name_semantic",message:`The target entity "${s.info.getLabel()}" of Tags association "${i.info.getLabel()}" does not have a property annotated with SemanticType.Name.`,help:"Entities used as Tag targets must define exactly one property annotated with SemanticType.Name to serve as the label.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O});let a=Array.from(s.withInheritedAssociations()).find(n=>n.targets.some(l=>l.key===s.key&&(!l.domain||l.domain===s.domain.key)));a&&e.addIssue({field:"semantics",rule:"tags_target_has_self_reference",message:`Entity "${s.info.getLabel()}" cannot be used as a Tags target because it has a self-referential association "${a.info.getLabel()}". Tags are flat by design. Use SemanticType.Categories for hierarchical taxonomy.`,help:`Remove the self-referential association from "${s.info.getLabel()}" or use SemanticType.Categories instead of SemanticType.Tags.`,severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O})}}if(i.hasSemantic(g.Categories)&&(!i.isLinked()&&i.targets.length>1&&e.addIssue({field:"targets",rule:"categories_union_target_not_supported",message:`The "${i.info.getLabel()}" association has Categories semantic and cannot have multiple target entities.`,help:"Categories associations must target exactly one entity because category classification requires a single taxonomy target.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O}),!i.isLinked()))for(let r of i.targets){let s=e.findEntity(r.key,r.domain);s&&(Array.from(s.withInheritedProperties()).some(a=>a.hasSemantic(g.Name))||e.addIssue({field:"semantics",rule:"categories_target_missing_name_semantic",message:`The target entity "${s.info.getLabel()}" of Categories association "${i.info.getLabel()}" does not have a property annotated with SemanticType.Name.`,help:"Entities used as Category targets must define exactly one property annotated with SemanticType.Name to serve as the label.",severity:"error",key:i.key,kind:i.kind,parent:t.key,parentKind:O}))}}}};var Ol=["recommendation","cross_sell","prerequisite","alternative","reference","assignment","compatibility","custom"];var Hr=class{semanticType=g.PeerRelation;validate(e){let t=e.getAssociationsWithSemantic(g.PeerRelation);for(let i of t)i.isLinked()||this.validateAssociation(i,e)}validateAssociation(e,t){if(e.isLinked())return;let i=e.info.getLabel(),r=e.getParentInstance();e.multiple||t.addIssue({field:"multiple",rule:"semantic_peer_relation_not_multiple",message:`The "${i}" association has PeerRelation semantic but is not multi-valued (multiple: false).`,help:"PeerRelation semantics can only be applied to multi-valued (array) associations.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O});let o=e.getSemantic(g.PeerRelation)?.config;o?.nature?Ol.includes(o.nature)?o.nature==="prerequisite"&&o.symmetry==="mutual"?t.addIssue({field:"config.symmetry",rule:"semantic_peer_relation_mutual_prerequisite_conflict",message:`The "${i}" association cannot have nature "prerequisite" with symmetry "mutual". Prerequisites must be directed.`,help:'Change symmetry to "directed" or select a different relationship nature.',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O}):o.nature==="custom"&&(!o.customNature||!o.customNature.trim())&&t.addIssue({field:"config.customNature",rule:"semantic_peer_relation_custom_nature_required",message:`The "${i}" association has nature "custom" but "customNature" is empty.`,help:'Provide a descriptive domain identifier in "customNature" (e.g., "wine_pairing", "co_author").',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O}):t.addIssue({field:"config.nature",rule:"semantic_peer_relation_invalid_nature",message:`The "${i}" association has PeerRelation semantic with an invalid nature "${o.nature}".`,help:'Specify a valid relation nature such as "recommendation", "cross_sell", "prerequisite", "alternative", "reference", "assignment", "compatibility", or "custom".',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O}):t.addIssue({field:"config.nature",rule:"semantic_peer_relation_missing_nature",message:`The "${i}" association has PeerRelation semantic but is missing the required "nature" configuration.`,help:'Specify a valid relation nature such as "recommendation", "cross_sell", "prerequisite", "alternative", "reference", "assignment", "compatibility", or "custom".',severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O})}};var Yr=class{semanticType=g.RelationalResourceOwner;validate(e){let t=e.getAssociationsWithSemantic(g.RelationalResourceOwner);for(let i of t)this.validateAssociation(i,e)}validateAssociation(e,t){if(!e.hasSemantic(g.RelationalResourceOwner))return;let i=e.info.getLabel(),r=e.getParentInstance();for(let s of e.targets){let o=t.findEntity(s.key,s.domain);o&&t.domain.resolveOwnershipPath(o.key)===null&&t.addIssue({field:"semantics",rule:"relational_owner_path_valid",message:`The target entity "${o.info.getLabel()}" of the relational resource owner association "${i}" does not have a valid ownership path to a User.`,help:"Ensure the target entity has a direct owner (Resource Owner Identifier) or transitively inherits ownership through another relational owner association.",severity:"error",key:e.key,kind:e.kind,parent:r?.key,parentKind:O})}}};var Xr=class{validators=[];byType=new Map;constructor(){this.register(new Dr),this.register(new Lr),this.register(new Mr),this.register(new Ur),this.register(new zr),this.register(new Vr),this.register(new Kr),this.register(new Br),this.register(new Gr),this.register(new Jr),this.register(new Wr),this.register(new Hr),this.register(new Yr)}register(e){let t=Array.isArray(e.semanticType)?e.semanticType:[e.semanticType],i=new Set;for(let r of t){let s=this.byType.get(r);s&&s!==e&&i.add(s),this.byType.set(r,e)}for(let r of i)if(!Array.from(this.byType.values()).includes(r)){let o=this.validators.indexOf(r);o!==-1&&this.validators.splice(o,1)}this.validators.includes(e)||this.validators.push(e)}unregister(e){let t=this.byType.get(e);if(!t)return!1;if(this.byType.delete(e),!Array.from(this.byType.values()).includes(t)){let r=this.validators.indexOf(t);r!==-1&&this.validators.splice(r,1)}return!0}get(e){return this.byType.get(e)}list(){return this.validators}validate(e,t){let i=this.get(e);i&&i.validate(t)}validateAll(e){for(let t of this.validators)t.validate(e)}};var Zi=class{domain;semanticRegistry;report=[];#e=0;#t=0;#i=0;#r=!1;entityValidator=new Tr;propertyValidator=new jr;associationValidator=new Cr;get infoCount(){return this.#r||this.computeIssueCounters(),this.#e}get warningCount(){return this.#r||this.computeIssueCounters(),this.#t}get errorCount(){return this.#r||this.computeIssueCounters(),this.#i}constructor(e,t=new Xr){this.domain=e,this.semanticRegistry=t}validate(){this.#r=!1,this.report=[];let e=new Zt(this.domain),t=!1;for(let i of e.listEntities()){t=!0,this.entityValidator.validate(i,e);for(let r of i.properties)r.domain.key===this.domain.key&&this.propertyValidator.validate(r,e);for(let r of i.associations)r.domain.key===this.domain.key&&this.associationValidator.validate(r,e)}return t?(this.semanticRegistry.validateAll(e),this.report=e.report,this.report):(this.report=e.report,this.report)}validateEntity(e){let t=new Zt(this.domain);return this.entityValidator.validate(e,t),t.report}validateProperty(e){let t=new Zt(this.domain);return this.propertyValidator.validate(e,t),t.report}validateAssociation(e){let t=new Zt(this.domain);return this.associationValidator.validate(e,t),t.report}validateSemantics(){let e=new Zt(this.domain);return this.semanticRegistry.validateAll(e),e.report}computeIssueCounters(){this.#e=this.report.filter(e=>e.severity==="info").length,this.#t=this.report.filter(e=>e.severity==="warning").length,this.#i=this.report.filter(e=>e.severity==="error").length,this.#r=!0}};var lt=class{root;get domain(){return this.root}#e;get key(){return this.#e}#t;get namespace(){return this.#t}constructor(e,t){this.root=e,this.#e=t,this.#t=e.key}};var Jp="http://a.ml/",Qt=`${Jp}vocabularies/`,re=`${Qt}document#`,we=`${Qt}core#`,ae=`${Qt}security#`,V=`${Qt}apiContract#`,Zr=`${Qt}apiBinding#`,H=`${Qt}shapes#`,xe=`${Qt}data#`,At=`${Qt}document-source-maps#`,Qr="http://www.w3.org/",fe=`${Qr}ns/shacl#`,Ye=`${Qr}2001/XMLSchema#`,xo=`${Qr}1999/02/22-rdf-syntax-ns#`,uc=`${Qr}2000/01/rdf-schema#`,u={aml:{key:"http://a.ml/",vocabularies:{key:Qt,document:{key:re,Module:`${re}Module`,Document:`${re}Document`,Fragment:`${re}Fragment`,Unit:`${re}Unit`,SecuritySchemeFragment:`${re}SecuritySchemeFragment`,UserDocumentation:`${re}UserDocumentation`,DataType:`${re}DataType`,NamedExamples:`${re}NamedExamples`,DomainElement:`${re}DomainElement`,DomainProperty:`${re}DomainProperty`,ParametrizedDeclaration:`${re}ParametrizedDeclaration`,AbstractDeclaration:`${re}AbstractDeclaration`,VariableValue:`${re}VariableValue`,ExternalFragment:`${re}ExternalFragment`,ExternalDomainElement:`${re}ExternalDomainElement`,RootDomainElement:`${re}RootDomainElement`,APIContractProcessingData:`${re}APIContractProcessingData`,BaseUnitProcessingData:`${re}BaseUnitProcessingData`,customDomainProperties:`${re}customDomainProperties`,encodes:`${re}encodes`,declares:`${re}declares`,references:`${re}references`,examples:`${re}examples`,linkTarget:`${re}link-target`,linkLabel:`${re}link-label`,referenceId:`${re}reference-id`,structuredValue:`${re}structuredValue`,raw:`${re}raw`,extends:`${re}extends`,value:`${re}value`,name:`${re}name`,strict:`${re}strict`,deprecated:`${re}deprecated`,location:`${re}location`,variable:`${re}variable`,target:`${re}target`,dataNode:`${re}dataNode`,root:`${re}root`,usage:`${re}usage`,version:`${re}version`},core:{key:we,CreativeWork:`${we}CreativeWork`,Parameter:`${we}Parameter`,Organization:`${we}Organization`,License:`${we}License`,Operation:`${we}Operation`,Response:`${we}Response`,Payload:`${we}Payload`,Request:`${we}Request`,version:`${we}version`,urlTemplate:`${we}urlTemplate`,displayName:`${we}displayName`,title:`${we}title`,name:`${we}name`,description:`${we}description`,documentation:`${we}documentation`,summary:`${we}summary`,provider:`${we}provider`,email:`${we}email`,url:`${we}url`,termsOfService:`${we}termsOfService`,license:`${we}license`,mediaType:`${we}mediaType`,extensionName:`${we}extensionName`,deprecated:`${we}deprecated`},security:{key:ae,ParametrizedSecurityScheme:`${ae}ParametrizedSecurityScheme`,SecuritySchemeFragment:`${ae}SecuritySchemeFragment`,SecurityScheme:`${ae}SecurityScheme`,OAuth1Settings:`${ae}OAuth1Settings`,OAuth2Settings:`${ae}OAuth2Settings`,OAuth2Flow:`${ae}OAuth2Flow`,Scope:`${ae}Scope`,Settings:`${ae}Settings`,HttpSettings:`${ae}HttpSettings`,ApiKeySettings:`${ae}ApiKeySettings`,OpenIdConnectSettings:`${ae}OpenIdConnectSettings`,SecurityRequirement:`${ae}SecurityRequirement`,security:`${ae}security`,scheme:`${ae}scheme`,schemes:`${ae}schemes`,settings:`${ae}settings`,name:`${ae}name`,type:`${ae}type`,scope:`${ae}scope`,accessTokenUri:`${ae}accessTokenUri`,authorizationUri:`${ae}authorizationUri`,authorizationGrant:`${ae}authorizationGrant`,flows:`${ae}flows`,flow:`${ae}flow`,signature:`${ae}signature`,tokenCredentialsUri:`${ae}tokenCredentialsUri`,requestTokenUri:`${ae}requestTokenUri`,refreshUri:`${ae}refreshUri`,securityRequirement:`${ae}SecurityRequirement`,openIdConnectUrl:`${ae}openIdConnectUrl`,bearerFormat:`${ae}bearerFormat`,in:`${ae}in`},apiContract:{key:V,Payload:`${V}Payload`,Request:`${V}Request`,Response:`${V}Response`,EndPoint:`${V}EndPoint`,Parameter:`${V}Parameter`,Operation:`${V}Operation`,WebAPI:`${V}WebAPI`,API:`${V}API`,AsyncAPI:`${V}AsyncAPI`,UserDocumentationFragment:`${V}UserDocumentationFragment`,Example:`${V}Example`,Server:`${V}Server`,ResourceType:`${V}ResourceType`,Trait:`${V}Trait`,TraitFragment:`${V}TraitFragment`,ParametrizedResourceType:`${V}ParametrizedResourceType`,ParametrizedTrait:`${V}ParametrizedTrait`,Callback:`${V}Callback`,TemplatedLink:`${V}TemplatedLink`,IriTemplateMapping:`${V}IriTemplateMapping`,Tag:`${V}Tag`,Message:`${V}Message`,DomainExtension:`${V}DomainExtension`,Encoding:`${V}Encoding`,header:`${V}header`,parameter:`${V}parameter`,paramName:`${V}paramName`,uriParameter:`${V}uriParameter`,cookieParameter:`${V}cookieParameter`,variable:`${V}variable`,payload:`${V}payload`,server:`${V}server`,path:`${V}path`,url:`${V}url`,scheme:`${V}scheme`,endpoint:`${V}endpoint`,queryString:`${V}queryString`,accepts:`${V}accepts`,guiSummary:`${V}guiSummary`,binding:`${V}binding`,response:`${V}response`,returns:`${V}returns`,expects:`${V}expects`,examples:`${V}examples`,supportedOperation:`${V}supportedOperation`,messageId:`${V}messageId`,statusCode:`${V}statusCode`,method:`${V}method`,required:`${V}required`,callback:`${V}callback`,expression:`${V}expression`,link:`${V}link`,linkExpression:`${V}linkExpression`,templateVariable:`${V}templateVariable`,mapping:`${V}mapping`,operationId:`${V}operationId`,protocol:`${V}protocol`,protocolVersion:`${V}protocolVersion`,headerSchema:`${V}headerSchema`,contentType:`${V}contentType`,allowEmptyValue:`${V}allowEmptyValue`,style:`${V}style`,explode:`${V}explode`,allowReserved:`${V}allowReserved`,tag:`${V}tag`,tags:`${V}tags`},apiBinding:{key:Zr,binding:`${Zr}binding`,bindings:`${Zr}bindings`,messageKey:`${Zr}messageKey`,type:`${Zr}type`},shapes:{key:H,Shape:`${H}Shape`,ScalarShape:`${H}ScalarShape`,ArrayShape:`${H}ArrayShape`,UnionShape:`${H}UnionShape`,NilShape:`${H}NilShape`,FileShape:`${H}FileShape`,AnyShape:`${H}AnyShape`,SchemaShape:`${H}SchemaShape`,MatrixShape:`${H}MatrixShape`,TupleShape:`${H}TupleShape`,RecursiveShape:`${H}RecursiveShape`,DataTypeFragment:`${H}DataTypeFragment`,XMLSerializer:`${H}XMLSerializer`,number:`${H}number`,integer:`${H}integer`,long:`${H}long`,double:`${H}double`,boolean:`${H}boolean`,float:`${H}float`,nil:`${H}nil`,password:`${H}password`,int32:`${H}int32`,int64:`${H}int64`,uint32:`${H}uint32`,uint64:`${H}uint64`,sint32:`${H}sint32`,sint64:`${H}sint64`,fixed32:`${H}fixed32`,fixed64:`${H}fixed64`,sfixed32:`${H}sfixed32`,sfixed64:`${H}sfixed64`,dateTimeOnly:`${H}dateTimeOnly`,range:`${H}range`,items:`${H}items`,anyOf:`${H}anyOf`,fileType:`${H}fileType`,schema:`${H}schema`,xmlSerialization:`${H}xmlSerialization`,xmlName:`${H}xmlName`,xmlAttribute:`${H}xmlAttribute`,xmlWrapped:`${H}xmlWrapped`,xmlNamespace:`${H}xmlNamespace`,xmlPrefix:`${H}xmlPrefix`,readOnly:`${H}readOnly`,writeOnly:`${H}writeOnly`,deprecated:`${H}deprecated`,fixPoint:`${H}fixPoint`,discriminator:`${H}discriminator`,discriminatorValue:`${H}discriminatorValue`,format:`${H}format`,multipleOf:`${H}multipleOf`,uniqueItems:`${H}uniqueItems`},data:{key:xe,Scalar:`${xe}Scalar`,Object:`${xe}Object`,Array:`${xe}Array`,Node:`${xe}Node`,value:`${xe}value`,type:`${xe}type`,description:`${xe}description`,required:`${xe}required`,displayName:`${xe}displayName`,minLength:`${xe}minLength`,maxLength:`${xe}maxLength`,default:`${xe}default`,multipleOf:`${xe}multipleOf`,minimum:`${xe}minimum`,maximum:`${xe}maximum`,enum:`${xe}enum`,pattern:`${xe}pattern`,items:`${xe}items`,format:`${xe}format`,example:`${xe}example`,examples:`${xe}examples`},docSourceMaps:{key:At,SourceMap:`${At}SourceMap`,sources:`${At}sources`,element:`${At}element`,value:`${At}value`,declaredElement:`${At}declared-element`,trackedElement:`${At}tracked-element`,parsedJsonSchema:`${At}parsed-json-schema`,autoGeneratedName:`${At}auto-generated-name`,lexical:`${At}lexical`,synthesizedField:`${At}synthesized-field`}}},w3:{key:Qr,shacl:{key:fe,Shape:`${fe}Shape`,NodeShape:`${fe}NodeShape`,SchemaShape:`${fe}SchemaShape`,PropertyShape:`${fe}PropertyShape`,in:`${fe}in`,defaultValue:`${fe}defaultValue`,defaultValueStr:`${fe}defaultValueStr`,pattern:`${fe}pattern`,minInclusive:`${fe}minInclusive`,maxInclusive:`${fe}maxInclusive`,multipleOf:`${fe}multipleOf`,minLength:`${fe}minLength`,maxLength:`${fe}maxLength`,fileType:`${fe}fileType`,and:`${fe}and`,property:`${fe}property`,name:`${fe}name`,raw:`${fe}raw`,datatype:`${fe}datatype`,minCount:`${fe}minCount`,maxCount:`${fe}maxCount`,xone:`${fe}xone`,not:`${fe}not`,or:`${fe}or`,closed:`${fe}closed`,path:`${fe}path`,additionalPropertiesSchema:`${fe}additionalPropertiesSchema`},xmlSchema:{key:Ye,boolean:`${Ye}boolean`,string:`${Ye}string`,number:`${Ye}number`,integer:`${Ye}integer`,long:`${Ye}long`,double:`${Ye}double`,float:`${Ye}float`,nil:`${Ye}nil`,dateTime:`${Ye}dateTime`,time:`${Ye}time`,date:`${Ye}date`,base64Binary:`${Ye}base64Binary`,byte:`${Ye}byte`},rdfSyntax:{key:xo,Seq:`${xo}Seq`,Property:`${xo}Property`,member:`${xo}member`},rdfSchema:{key:uc,Seq:`${uc}Seq`,member:`${uc}member`}}};function Qi(c,e=0){if(typeof c!="object")return c;let t="",i=new Array(e).fill(" ").join("");return Object.keys(c).forEach(r=>{t+=Array.isArray(c[r])?"":`${i}<${r}>`,Array.isArray(c[r])?c[r].forEach(s=>{t+=i,t+=`<${r}>
|
|
28
28
|
`,t+=Qi({...s},e+1),t+=i,t+=`</${r}>
|
|
29
29
|
`}):typeof c[r]=="object"?(t+=`
|
|
30
30
|
`,t+=Qi({...c[r]},e+1),t+=i):t+=`${c[r]}`,t+=Array.isArray(c[r])?"":`</${r}>
|
|
@@ -36,7 +36,7 @@ Creating organization "${i}" with slug "${r}"...`);try{let a=(await c.organizati
|
|
|
36
36
|
`,size:r=this[ut].number({min:1,max:7})}=t;return new Array(r).fill("").map(()=>this.paragraph()).join(i)}syllable(e={}){let{syntax:t}=this[Mo],i={...e},r=i.length||this[ut].number({min:2,max:3}),s=t&&t.consonants||ve.syntax.consonants,o=t&&t.vowels||ve.syntax.vowels,a=s+o,n="",l;for(let d=0;d<r;d++)d===0?l=this[ut].character({pool:a}):l&&o.includes(l)?l=this[ut].character({pool:s}):l=this[ut].character({pool:o}),n+=l;return i.capitalize&&(n=this.capitalize(n)),n}lorem(){let e=["word","words","sentence","sentences","paragraph","paragraphs"],t=this[Lo].pickOne(e);return this[t]()}};var mt=Symbol("typesValue"),os=Symbol("localeValue"),$i=class{[mt];[os];constructor(e={}){this[mt]=new dt(e.seed),this[os]=e.locale||ve}seed(e){this[mt].seed(e)}locale(e){this[os]=e||ve}date(e){return this[mt].datetime(e)}amPm(){return this[mt].boolean()?"am":"pm"}timestamp(e){return this[mt].datetime(e).getTime()}hour(e={}){let t={...e};if(typeof t.min!="number"&&(t.min=t.twentyFour?0:1),typeof t.max!="number"&&(t.max=t.twentyFour?23:12),t.min<0)throw new RangeError(`Provided value ${t.min} for min is less than 0.`);if(t.max>23&&t.twentyFour||t.max>12&&!t.twentyFour)throw new RangeError(`Provided value ${t.max} for max is greater than ${t.twentyFour?23:12}.`);if(t.min>t.max)throw new RangeError(`The min value (${t.min}) cannot be greater than max value (${t.max}).`);return this[mt].number({min:t.min,max:t.max})}minute(e={}){let{min:t=0,max:i=59}=e;if(t<0)throw new RangeError(`Provided value ${t} for min is less than 0.`);if(i>59)throw new RangeError(`Provided value ${i} for max is greater than 59.`);if(t>i)throw new RangeError(`The min value (${t}) cannot be greater than max value (${i}).`);return this[mt].number({min:t,max:i})}millisecond(){return this[mt].number({max:999})}second(){return this[mt].number({max:59})}month(e={}){let{min:t=1,max:i=12}=e;if(t<1)throw new RangeError(`Provided value ${t} for min is less than 1.`);if(i>12)throw new RangeError(`Provided value ${i} for max is greater than 12.`);if(t>i)throw new RangeError(`The min value (${t}) cannot be greater than max value (${i}).`);return this[mt].number({min:t,max:i})}monthName(e={}){let t=this.month(e);return this.months(e.abbr)[t-1]}months(e=!1){let{time:t}=this[os],i;return t&&t.month&&t.month.abbr&&t.month.abbr.length>0?i=t.month:i=ve.time.month,e?i.abbr:i.names}weekdays(e=!1){let{time:t}=this[os],i;return t&&t.weekday&&t.weekday.abbr&&t.weekday.abbr.length>0?i=t.weekday:i=ve.time.weekday,e?i.abbr:i.names}weekday(e={}){let{min:t=1,max:i=7}=e;if(t<1)throw new RangeError(`Provided value ${t} for min is less than 1.`);if(i>7)throw new RangeError(`Provided value ${i} for max is greater than 7.`);if(t>i)throw new RangeError(`The min value (${t}) cannot be greater than max value (${i}).`);return this[mt].number({min:t,max:i})}weekdayName(e={}){let t=this.weekday(e);return this.weekdays(e.abbr)[t-1]}midnight(e=Date.now()){let t=new Date(e);return t.setHours(0,0,0,0),t.getTime()}dateOnly(e){let t=this.date(e),i=t.getFullYear(),r=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0");return`${i}-${r}-${s}`}timeOnly(e){let t=this.date(e),i=t.getHours().toString().padStart(2,"0"),r=t.getMinutes().toString().padStart(2,"0"),s=t.getSeconds().toString().padStart(2,"0");return`${i}:${r}:${s}`}dateTime(e="rfc3339",t){let i=this.date(t);if(e==="rfc2616")return i.toUTCString();if(e==="rfc3339"){let r=i.getUTCFullYear(),s=(i.getUTCMonth()+1).toString().padStart(2,"0"),o=i.getUTCDate().toString().padStart(2,"0"),a=i.getUTCHours().toString().padStart(2,"0"),n=i.getUTCMinutes().toString().padStart(2,"0"),l=i.getUTCSeconds().toString().padStart(2,"0"),d=i.getUTCMilliseconds().toString().padStart(3,"0");return`${r}-${s}-${o}T${a}:${n}:${l}.${d}Z`}return""}dateTimeOnly(e){let t=this.date(e),i=t.getFullYear(),r=(t.getMonth()+1).toString().padStart(2,"0"),s=t.getDate().toString().padStart(2,"0"),o=t.getHours().toString().padStart(2,"0"),a=t.getMinutes().toString().padStart(2,"0"),n=t.getSeconds().toString().padStart(2,"0");return`${i}-${r}-${s}T${o}:${a}:${n}`}};var z;(function(c){c[c.ROOT=0]="ROOT",c[c.GROUP=1]="GROUP",c[c.POSITION=2]="POSITION",c[c.SET=3]="SET",c[c.RANGE=4]="RANGE",c[c.REPETITION=5]="REPETITION",c[c.REFERENCE=6]="REFERENCE",c[c.CHAR=7]="CHAR"})(z||(z={}));var mm=()=>({type:z.POSITION,value:"b"}),hm=()=>({type:z.POSITION,value:"B"}),fm=()=>({type:z.POSITION,value:"^"}),gm=()=>({type:z.POSITION,value:"$"}),Tc=()=>[{type:z.RANGE,from:48,to:57}],nd=()=>[{type:z.CHAR,value:95},{type:z.RANGE,from:97,to:122},{type:z.RANGE,from:65,to:90},...Tc()],cd=()=>[{type:z.CHAR,value:9},{type:z.CHAR,value:10},{type:z.CHAR,value:11},{type:z.CHAR,value:12},{type:z.CHAR,value:13},{type:z.CHAR,value:32},{type:z.CHAR,value:160},{type:z.CHAR,value:5760},{type:z.CHAR,value:6158},{type:z.CHAR,value:8192},{type:z.CHAR,value:8193},{type:z.CHAR,value:8194},{type:z.CHAR,value:8195},{type:z.CHAR,value:8196},{type:z.CHAR,value:8197},{type:z.CHAR,value:8198},{type:z.CHAR,value:8199},{type:z.CHAR,value:8200},{type:z.CHAR,value:8201},{type:z.CHAR,value:8202},{type:z.CHAR,value:8232},{type:z.CHAR,value:8233},{type:z.CHAR,value:8239},{type:z.CHAR,value:8287},{type:z.CHAR,value:12288},{type:z.CHAR,value:65279}],ym=()=>[{type:z.CHAR,value:10},{type:z.CHAR,value:13},{type:z.CHAR,value:8232},{type:z.CHAR,value:8233}],ld=()=>({type:z.SET,set:nd(),not:!1}),dd=()=>({type:z.SET,set:nd(),not:!0}),pd=()=>({type:z.SET,set:Tc(),not:!1}),ud=()=>({type:z.SET,set:Tc(),not:!0}),md=()=>({type:z.SET,set:cd(),not:!1}),hd=()=>({type:z.SET,set:cd(),not:!0}),bm=()=>({type:z.SET,set:ym(),not:!0}),km={0:0,t:9,n:10,v:11,f:12,r:13},vm=c=>{let e=/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;return c.replace(e,(t,i,r,s,o,a,n,l)=>{if(r)return t;let d=i?8:s?parseInt(s,16):o?parseInt(o,16):a?parseInt(a,8):n?"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?".indexOf(n):km[l],p=String.fromCharCode(d);return/[[{}^$.|?*+()]/.test(p)&&(p=`\\${p}`),p})},wm=(c,e)=>{let t=[],i=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g,r,s;for(;(r=i.exec(c))!==null;)if(r[1])t.push(ld());else if(r[2])t.push(pd());else if(r[3])t.push(md());else if(r[4])t.push(dd());else if(r[5])t.push(ud());else if(r[6])t.push(hd());else if(r[7])t.push({type:z.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:r[10].charCodeAt(0)});else if(s=r[12])t.push({type:z.CHAR,value:s.charCodeAt(0)});else return[t,i.lastIndex];throw new SyntaxError(`Invalid regular expression: /${e}/: Unterminated character class`)},zo=(c,e)=>{throw new SyntaxError(`Invalid regular expression: /${c}/: ${e}`)},fd=c=>{let e=0,t={type:z.ROOT,stack:[]},i=t,r=t.stack,s=[],o=n=>zo(c,`Nothing to repeat at column ${n-1}`),a=vm(c);for(;e<a.length;){let n=a[e++];switch(n){case"\\":switch(n=a[e++],n){case"b":r.push(mm());break;case"B":r.push(hm());break;case"w":r.push(ld());break;case"W":r.push(dd());break;case"d":r.push(pd());break;case"D":r.push(ud());break;case"s":r.push(md());break;case"S":r.push(hd());break;default:/\d/.test(n)?r.push({type:z.REFERENCE,value:parseInt(n,10)}):r.push({type:z.CHAR,value:n.charCodeAt(0)})}break;case"^":r.push(fm());break;case"$":r.push(gm());break;case"[":{let l=!1;a[e]==="^"&&(l=!0,e++);let[d,p]=wm(a.slice(e),c);e+=p,r.push({type:z.SET,set:d,not:l});break}case".":r.push(bm());break;case"(":{let l={type:z.GROUP,stack:[],remember:!0};a[e]==="?"&&(n=a[e+1],e+=2,n==="="?l.followedBy=!0:n==="!"?l.notFollowedBy=!0:n!==":"&&zo(c,`Invalid group, character '${n}' after '?' at column ${e-1}`),l.remember=!1),r.push(l),s.push(i),i=l,r=l.stack;break}case")":s.length===0&&zo(c,`Unmatched ) at column ${e-1}`),i=s.pop(),r=i.options?i.options[i.options.length-1]:i.stack;break;case"|":i.options||(i.options=[i.stack],delete i.stack);{let l=[];i.options.push(l),r=l}break;case"{":{let l=/^(\d+)(,(\d+)?)?\}/.exec(a.slice(e));if(l){r.length===0&&o(e);let d=parseInt(l[1],10),p=l[2]?l[3]?parseInt(l[3],10):1/0:d;e+=l[0].length,r.push({type:z.REPETITION,min:d,max:p,value:r.pop()})}else r.push({type:z.CHAR,value:123});break}case"?":r.length===0&&o(e),r.push({type:z.REPETITION,min:0,max:1,value:r.pop()});break;case"+":r.length===0&&o(e),r.push({type:z.REPETITION,min:1,max:1/0,value:r.pop()});break;case"*":r.length===0&&o(e),r.push({type:z.REPETITION,min:0,max:1/0,value:r.pop()});break;default:r.push({type:z.CHAR,value:n.charCodeAt(0)})}}return s.length!==0&&zo(c,"Unterminated group"),t};var as=class c{types;constructor(e={}){this.types=new dt(e.seed)}seed(e){this.types.seed(e)}fromPattern(e,t={}){let i,r;e instanceof globalThis.RegExp?(r=e.ignoreCase,i=e.source):(r=t.flags?.includes("i")??!1,i=e);let s=10;typeof t.max=="number"&&(s=t.max);let o=fd(i),a=Array.from({length:95},(n,l)=>l+32);return this._gen(o,[],r,a,s)}_gen(e,t,i,r,s){let o,a,n,l;switch(e.type){case z.ROOT:case z.GROUP:if(e.followedBy||e.notFollowedBy)return"";for(e.remember&&e.groupNumber===void 0&&(e.groupNumber=t.push(null)-1),o=e.options?this._choice(e.options):e.stack,a="",n=0,l=o.length;n<l;n++)a+=this._gen(o[n],t,i,r,s);return e.remember&&(t[e.groupNumber]=a),a;case z.POSITION:return"";case z.SET:{let d=this._processSet(e,i,r);return d.length?String.fromCharCode(this._choice(d)):""}case z.REPETITION:{let d=e.max===1/0?Math.max(e.min,s):e.max,p=this.types.number({min:e.min,max:d});for(a="",n=0;n<p;n++)a+=this._gen(e.value,t,i,r,s);return a}case z.REFERENCE:return t[e.value-1]||"";case z.CHAR:{let d=i&&this._coin()?c._toCaseInverse(e.value):e.value;return String.fromCharCode(d)}}return""}_processSet(e,t,i){if(e.type===z.CHAR)return[e.value];if(e.type===z.RANGE){let s=[];for(let o=e.from;o<=e.to;o++)s.push(o);return s}let r=new Set;for(let s of e.set){let o=this._processSet(s,t,i);if(o.forEach(a=>r.add(a)),t)for(let a of o){let n=a,l=c._toCaseInverse(n);n!==l&&r.add(l)}}return e.not?i.filter(s=>!r.has(s)):Array.from(r)}static _toCaseInverse(e){return e>=97&&e<=122?e-32:e>=65&&e<=90?e+32:e}_coin(){return this.types.number({min:0,max:1})===0}_choice(e){return e[this.types.number({min:0,max:e.length-1})]}};var gi=class c{static types=new dt;static person=new Do;static lorem=new Uo;static regExp=new as;static readInputValue(e,t,i={}){let{required:r}=e,{defaultValueStr:s,values:o}=t;if(!(!r&&i.requiredOnly===!0)){if(s)return c.readTypedValue(s,t.dataType);if(Array.isArray(o)&&o.length){let a=o[0];return c.readTypedValue(a.value,a.dataType)}if(i.fromExamples){let a;if(Array.isArray(e.examples)&&e.examples.length?a=e.examples.filter(n=>typeof n!="string"):Array.isArray(t.examples)&&t.examples.length&&(a=t.examples),a&&a.length)return c.inputValueFromExamples(a)}return c.generateDefaultValue(t)}}static readInputValues(e,t,i={}){if(!e.required&&i.requiredOnly===!0)return[];let{defaultValue:r}=t;if(r){let a=new nt().processNode(r);if(Array.isArray(a))return a}let s=t;if(i.fromExamples){let o;return Array.isArray(e.examples)&&e.examples.length?o=e.examples.filter(a=>typeof a!="string"):Array.isArray(s.examples)&&s.examples.length&&(o=s.examples),c.arrayValuesFromExamples(o)}return[]}static inputValueFromExamples(e){if(!Array.isArray(e)||!e.length)return;let[t]=e,{structuredValue:i}=t;if(i&&i.types.includes(u.aml.vocabularies.data.Scalar)){let r=i;return c.readTypedValue(r.value,r.dataType)}}static arrayValuesFromExamples(e){let t=[];if(!Array.isArray(e)||!e.length)return t;let[i]=e;if(!i.structuredValue||!i.structuredValue.types.includes(u.aml.vocabularies.data.Array))return t;let r=i.structuredValue,{members:s}=r;return!Array.isArray(s)||!s.length||s.forEach(o=>{let a=o;if(!a.value)return;let n=c.readTypedValue(a.value,a.dataType);typeof r<"u"&&r!==null&&t.push(n)}),t}static generateDefaultValue(e){let{dataType:t}=e;return this.defaultValue(t)}static generateMockedValue(e){let{dataType:t}=e;switch(t){case u.w3.xmlSchema.string:case u.aml.vocabularies.shapes.password:return this.generateStringValue(e);case u.w3.xmlSchema.number:case u.w3.xmlSchema.integer:case u.w3.xmlSchema.float:case u.w3.xmlSchema.long:case u.w3.xmlSchema.double:case u.aml.vocabularies.shapes.number:case u.aml.vocabularies.shapes.integer:case u.aml.vocabularies.shapes.float:case u.aml.vocabularies.shapes.long:case u.aml.vocabularies.shapes.double:return this.generateNumberValue(e);case u.aml.vocabularies.shapes.boolean:case u.w3.xmlSchema.boolean:return this.types.boolean();case u.aml.vocabularies.shapes.nil:case u.w3.xmlSchema.nil:return null;case u.w3.xmlSchema.date:return new $i().dateOnly();case u.w3.xmlSchema.dateTime:return new $i().dateTime(e.format==="date-time"?"rfc3339":e.format);case u.aml.vocabularies.shapes.dateTimeOnly:return new $i().dateTimeOnly();case u.w3.xmlSchema.time:return new $i().timeOnly();default:return}}static defaultValue(e){switch(e){case u.w3.xmlSchema.string:case u.aml.vocabularies.shapes.password:return"";case u.w3.xmlSchema.number:case u.w3.xmlSchema.integer:case u.w3.xmlSchema.float:case u.w3.xmlSchema.long:case u.w3.xmlSchema.double:case u.aml.vocabularies.shapes.number:case u.aml.vocabularies.shapes.integer:case u.aml.vocabularies.shapes.float:case u.aml.vocabularies.shapes.long:case u.aml.vocabularies.shapes.double:return 0;case u.aml.vocabularies.shapes.boolean:case u.w3.xmlSchema.boolean:return!1;case u.aml.vocabularies.shapes.nil:case u.w3.xmlSchema.nil:return null;case u.w3.xmlSchema.date:return"";case u.w3.xmlSchema.dateTime:return"";case u.aml.vocabularies.shapes.dateTimeOnly:return"";case u.w3.xmlSchema.time:return"";default:return}}static generateNumberValue(e){let{minimum:t,maximum:i,format:r,multipleOf:s}=e,o={};typeof t=="number"&&(o.min=t),typeof i=="number"&&(o.max=i);let a;return r&&["float","double"].includes(r)?a=this.types.float.bind(this.types):r&&["uint32","uint64","fixed32","fixed64"].includes(r)&&(o.min=0,o.max&&o.max<0&&delete o.max),a||(a=this.types.number.bind(this.types)),typeof s=="number"&&(o.precision=s),a(o)}static generateStringValue(e){let{minLength:t,maxLength:i,name:r="",format:s,pattern:o}=e;if(o)return new as().fromPattern(o,{max:10});let a=r.toLowerCase();if(a==="description")return this.lorem.paragraph();if(s==="uuid")return this.types.uuid();if(a==="id"){let d={length:12},p=typeof t=="number";return p?d.length=t:!p&&typeof i=="number"&&(d.length=i),this.types.hash(d)}if(["name","fullname"].includes(a))return this.person.name();if(a==="firstname")return this.person.firstName();if(a==="lastname")return this.person.lastName();let n={},l=typeof t=="number";return l?n.length=t:!l&&typeof i=="number"&&(n.length=i),this.lorem.word(n)}static readTypedValue(e,t){return Po(e,t)}static readInputType(e){switch(e){case u.aml.vocabularies.shapes.number:case u.aml.vocabularies.shapes.integer:case u.aml.vocabularies.shapes.float:case u.aml.vocabularies.shapes.long:case u.aml.vocabularies.shapes.double:case u.w3.xmlSchema.number:case u.w3.xmlSchema.integer:case u.w3.xmlSchema.float:case u.w3.xmlSchema.long:case u.w3.xmlSchema.double:return"number";case u.w3.xmlSchema.date:return"date";case u.w3.xmlSchema.time:return"time";case u.w3.xmlSchema.dateTime:case u.aml.vocabularies.shapes.dateTimeOnly:return"datetime-local";case u.aml.vocabularies.shapes.boolean:case u.w3.xmlSchema.boolean:return"boolean";case u.aml.vocabularies.shapes.password:return"password";default:return"text"}}static parseNumberInput(e,t){return mc(e,t)}static parseBooleanInput(e,t){return hc(e,t)}static parseDateOnlyInput(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return;let i=t.toJSON(),r=i.indexOf("T");return i.substring(0,r)}static parseTimeOnlyInput(e){let t=String(e).trim();if(/^\d\d:\d\d$/.test(t))return`${t}:00`;if(/^\d\d:\d\d:\d\d$/.test(t))return t}static parseDateTimeInput(e,t="rfc3339"){let i=new Date(e);if(!Number.isNaN(i.getTime())){if(t==="rfc2616")return i.toUTCString();if(["rfc3339","date-time"].includes(t))return i.toISOString()}}static parseDateTimeOnlyInput(e){let t=new Date(e);if(Number.isNaN(t.getTime()))return;let i=t.toJSON(),r=i.indexOf(".");return i.substring(0,r)}static parseArrayInput(e,t){let{items:i}=t;return i?c.parseUserInput(e,i):String(e)}static parseUserInput(e,t){if(!t||e===void 0||e===null)return e;let{types:i}=t;return i.includes(u.aml.vocabularies.shapes.ScalarShape)?c.parseScalarInput(e,t):i.includes(u.aml.vocabularies.shapes.ArrayShape)||i.includes(u.aml.vocabularies.shapes.MatrixShape)?c.parseArrayInput(e,t):e}static parseScalarInput(e,t){return this.parseScalar(e,t.dataType,t.format)}static parseScalar(e,t,i){switch(t){case u.aml.vocabularies.shapes.number:case u.aml.vocabularies.shapes.integer:case u.aml.vocabularies.shapes.float:case u.aml.vocabularies.shapes.long:case u.aml.vocabularies.shapes.double:case u.w3.xmlSchema.number:case u.w3.xmlSchema.integer:case u.w3.xmlSchema.float:case u.w3.xmlSchema.long:case u.w3.xmlSchema.double:return c.parseNumberInput(e);case u.aml.vocabularies.shapes.boolean:case u.w3.xmlSchema.boolean:return c.parseBooleanInput(e);case u.w3.xmlSchema.date:return c.parseDateOnlyInput(e);case u.w3.xmlSchema.time:return c.parseTimeOnlyInput(e);case u.w3.xmlSchema.dateTime:return c.parseDateTimeInput(e,i);case u.aml.vocabularies.shapes.dateTimeOnly:return c.parseDateTimeOnlyInput(e);default:return String(e)}}};var Oi=class{opts;constructor(e={}){this.opts=Object.freeze({...e})}_scalarValue(e){let{defaultValue:t,examples:i,values:r,inherits:s,dataType:o}=e;if(this.opts.renderExamples&&i&&i.length){let a=i.find(l=>!!l.structuredValue),n=this._exampleToObject(a);if(typeof n<"u")return gi.readTypedValue(n,o)}if(t)return new nt().processNode(t);if(r&&r.length){let a=r[0];if(a.value!==void 0)return gi.readTypedValue(a.value,o)}if(Array.isArray(s)&&s.length)for(let a=0,n=s.length;a<n;a+=1){let l=this._scalarValue(s[a]);if(l!==void 0)return l}return this.opts.renderMocked?gi.generateMockedValue(e):gi.generateDefaultValue(e)}_isNotRequiredUnion(e){let t=0,i=!1;return e.forEach(r=>{r.types.includes(u.aml.vocabularies.shapes.NilShape)?i=!0:r.types.includes(u.aml.vocabularies.shapes.ScalarShape)?r.dataType===u.w3.xmlSchema.nil?i=!0:t+=1:r.types.includes(u.aml.vocabularies.shapes.FileShape)&&(t+=1)}),i?t===e.length-1:!1}};var ns=class extends Oi{generate(e){let t;return e.types.includes(u.w3.shacl.PropertyShape)?t=this._propertyShapeObject(e):t=this.toObject(e),t!==null&&typeof t=="object"?this.serialize(t):t}toObject(e){let{types:t}=e;return t.includes(u.aml.vocabularies.shapes.ScalarShape)?this._scalarShapeObject(e):t.includes(u.w3.shacl.NodeShape)?this._nodeShapeObject(e):t.includes(u.aml.vocabularies.shapes.UnionShape)?this._unionShapeObject(e):t.includes(u.aml.vocabularies.shapes.FileShape)?this._fileShapeObject():t.includes(u.aml.vocabularies.shapes.SchemaShape)?this._schemaShapeObject():t.includes(u.aml.vocabularies.shapes.TupleShape)?this._tupleShapeObject(e):t.includes(u.aml.vocabularies.shapes.ArrayShape)||t.includes(u.aml.vocabularies.shapes.MatrixShape)?this._arrayShapeObject(e):this._anyShapeObject(e)}serialize(e){return JSON.stringify(e,null,2)}_scalarShapeObject(e){return this._scalarValue(e)}_nilShapeObject(){}_nodeShapeObject(e){let{inherits:t}=e,{examples:i=[]}=e;if(Array.isArray(t)&&t.length&&t.forEach(o=>{let a=o;Array.isArray(a.examples)&&a.examples.length&&(i=i.concat(a.examples))}),this.opts.renderExamples&&i.length){let o=i.find(n=>!!n.structuredValue),a=this._exampleToObject(o);if(a!==void 0)return a}let r={},{properties:s}=e;return Array.isArray(t)&&t.length&&t.forEach(o=>{let a=this.toObject(o);typeof a=="object"&&(r={...r,...a})}),s.forEach(o=>{let{name:a}=o,n=this._propertyShapeObject(o);typeof n<"u"&&a&&(r[a]=n)}),r}_unionShapeObject(e){return e.and&&e.and.length?this._allOfUnion(e):e.xone&&e.xone.length?this._oneOfUnion(e):this._anyOfUnion(e)}_anyOfUnion(e){let{anyOf:t=[],examples:i=[]}=e;Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(a=>{let n=a;Array.isArray(n.examples)&&n.examples.length&&(i=i.concat(n.examples));let l=a;Array.isArray(l.anyOf)&&l.anyOf.length&&(t=t.concat(l.anyOf))});let{opts:r}=this;if(this._isNotRequiredUnion(t))return;if(this.opts.renderExamples){let a=i.find(l=>!!l.structuredValue),n=this._exampleToObject(a);if(n!==void 0)return n}if(e.defaultValue)return this._unionDefaultValue(t,e.defaultValue);let{selectedUnions:s}=r,o;if(s&&s.length?o=t.find(a=>s.includes(a.id)):[o]=t,o)return this.toObject(o)}_oneOfUnion(e){let{examples:t=[]}=e,{xone:i=[]}=e;Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(a=>{let n=a;Array.isArray(n.examples)&&n.examples.length&&(t=t.concat(n.examples))});let{opts:r}=this;if(this.opts.renderExamples){let a=t.find(l=>!!l.structuredValue),n=this._exampleToObject(a);if(n!==void 0)return n}if(e.defaultValue)return this._unionDefaultValue(i,e.defaultValue);let{selectedUnions:s}=r,o;if(s&&s.length?o=i.find(a=>s.includes(a.id)):[o]=i,o)return this.toObject(o)}_allOfUnion(e){let{examples:t=[]}=e,{and:i=[]}=e;if(Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(s=>{let o=s;Array.isArray(o.examples)&&o.examples.length&&(t=t.concat(o.examples))}),this.opts.renderExamples){let s=t.find(a=>!!a.structuredValue),o=this._exampleToObject(s);if(o!==void 0)return o}let r={};return i.forEach(s=>{let o=this.toObject(s);typeof o=="object"&&(r={...r,...o})}),r}_unionDefaultValue(e,t){let r=new nt().generate(t),s=!1,o=!1,a=!1;if(e.forEach(n=>{if(n.types.includes(u.aml.vocabularies.shapes.NilShape)&&(a=!0),!n.types.includes(u.aml.vocabularies.shapes.ScalarShape))return;let l=n;o||(o=l.dataType===u.w3.xmlSchema.boolean),s||(s=[u.w3.xmlSchema.number,u.w3.xmlSchema.long,u.w3.xmlSchema.integer,u.w3.xmlSchema.float,u.w3.xmlSchema.double,u.aml.vocabularies.shapes.number,u.aml.vocabularies.shapes.long,u.aml.vocabularies.shapes.integer,u.aml.vocabularies.shapes.float,u.aml.vocabularies.shapes.double].includes(l.dataType)),a||(a=l.dataType===u.w3.xmlSchema.nil)}),s){let n=Number(r);if(!Number.isNaN(n))return n}if(o){if(r==="true")return!0;if(r==="false")return!1}return a&&(r==="null"||r==="nil")?null:r}_arrayShapeObject(e){let{items:t}=e,i=e.defaultValue||t&&t.defaultValue,{examples:r=[]}=e,s=t;if(Array.isArray(s.examples)&&(r=r.concat(s.examples)),this.opts.renderExamples&&r&&r.length){let o=r.find(n=>!!n.structuredValue),a=this._exampleToObject(o);if(Array.isArray(a))return a;if(typeof a<"u")return[a]}if(i){let a=new nt().processNode(i);if(Array.isArray(a))return a;if(a)return[a]}if(t){let o=this.toObject(t);if(typeof o<"u")return[o]}return[]}_tupleShapeObject(e){let{items:t,examples:i}=e;if(this.opts.renderExamples&&i&&i.length){let r=i.find(o=>!!o.structuredValue),s=this._exampleToObject(r);if(typeof s<"u")return[s]}if(e.defaultValue){let s=new nt().processNode(e.defaultValue);if(Array.isArray(s))return s}if(t.length){let r=[];return t.forEach(s=>{let o=this.toObject(s);typeof o<"u"&&r.push(o)}),r}return[]}_anyShapeObject(e){let{and:t=[],xone:i=[],or:r=[]}=e;if(t.length){let s={};return t.forEach(o=>{let a=this.toObject(o);typeof a=="object"&&(s={...s,...a})}),s}if(i.length){let{selectedUnions:s=[]}=this.opts,o=i.find(a=>s.includes(a.id));return o||(o=i[0]),this.toObject(o)}if(r.length){let{selectedUnions:s=[]}=this.opts,o=r.find(a=>s.includes(a.id));return o||(o=r[0]),this.toObject(o)}return this._scalarShapeObject(e)}_propertyShapeObject(e){let{minCount:t=0}=e;if(t===0&&!this.opts.renderOptional)return;let{range:i}=e;if(!i)return;let{types:r}=i;if(r.includes(u.aml.vocabularies.shapes.ScalarShape)){let s=i;return this._scalarShapeObject(s)}return this.toObject(i)}_exampleToObject(e){if(e&&e.structuredValue)return new nt().processNode(e.structuredValue)}_fileShapeObject(){}_schemaShapeObject(){}};var Ze=c=>c.replace(/[^a-zA-Z0-9-_.]/g,""),jc="unknown-type";function Mt(c){let{name:e,inherits:t=[],xmlSerialization:i}=c,r=i&&i.name?i.name:e||jc;if(r==="schema"&&t.length){let s=t.find(o=>o.name&&o.name!=="schema");s&&(r=s.name==="type"&&s.displayName||s.name)}return Ze(String(r))}var cs=class extends Oi{generate(e){let t;return e.types.includes(u.w3.shacl.PropertyShape)?t=this._propertyShapeObject(e):t=this.processNode(e,{},!0),t}processNode(e,t={},i=!1){let{types:r}=e;return r.includes(u.aml.vocabularies.shapes.ScalarShape)?this._scalarShapeObject(e,t):r.includes(u.w3.shacl.NodeShape)?this._nodeShapeObject(e,t):r.includes(u.aml.vocabularies.shapes.UnionShape)?this._unionShapeObject(e):r.includes(u.aml.vocabularies.shapes.FileShape)?this._fileShapeObject():r.includes(u.aml.vocabularies.shapes.SchemaShape)?this._schemaShapeObject():r.includes(u.aml.vocabularies.shapes.TupleShape)?this._tupleShapeObject():r.includes(u.aml.vocabularies.shapes.ArrayShape)||r.includes(u.aml.vocabularies.shapes.MatrixShape)?this._arrayShapeObject(e,t,i):this._anyShapeObject(e)}serialize(e){return e}_readCurrentUnion(e){let{selectedUnions:t}=this.opts;return fc(e,t)}_collectProperties(e){let{selectedUnions:t}=this.opts;return Ro(e,t)}_nodeShapeObject(e,t={}){let i=t.forceName||Mt(e),r=[],s=t.indent||0,o=this._collectExamples(e,{tagFill:new Array(s*2+0).fill(" ").join(""),indent:s+1,nodeName:i});if(o)return o;let a=[];if(this._collectProperties(e).forEach(p=>{let{range:m,minCount:h=0}=p;if(h===0&&!this.opts.renderOptional||!m)return;let f=m;if(f.xmlSerialization&&f.xmlSerialization.attribute&&f.types.includes(u.aml.vocabularies.shapes.ScalarShape)){let w=Ze(f.xmlSerialization.name?f.xmlSerialization.name:p.name||f.name||jc);f.xmlSerialization.prefix&&(w=`${f.xmlSerialization.prefix}:${w}`);let S=this._scalarValue(f);a.push(`${w}="${S}"`);return}let k=this._propertyShapeObject(p,{indent:s});if(typeof k<"u"){let w=t.noWrap?0:2,S=new Array(s*2+w).fill(" ").join("");r.push(Io(S,k))}}),t.noWrap)return r.join(`
|
|
37
37
|
`);let l=`<${i}`;a.length&&(l+=" ",l+=a.join(" ")),r.unshift(`${l}>`);let d=new Array(s*2).fill(" ").join("");return r.push(`${d}</${i}>`),r.join(`
|
|
38
38
|
`)}_scalarShapeObject(e,t={}){let{xmlSerialization:i,defaultValue:r}=e,s;r?s=new Ge().processNode(r):s=this._scalarValue(e);let o=t.forceName||Mt(e),a=[],n=[];if(i){let{namespace:d,prefix:p}=i;if(d){let m=p?`xmlns:${p}`:"xmlns";a.push(`${m}="${d}"`)}p&&(o=`${p}:${o}`)}let l=`<${o}`;return a.length&&(l+=" ",l+=a.join(" ")),l+=">",n.push(l),n.push(s),n.push(`</${o}>`),n.join("")}_nilShapeObject(e,t={}){let{xmlSerialization:i}=e,r="",s=t.forceName||Mt(e),o=[],a=[];if(i){let{namespace:l,prefix:d}=i;if(l){let p=d?`xmlns:${d}`:"xmlns";o.push(`${p}="${l}"`)}d&&(s=`${d}:${s}`)}let n=`<${s}`;return o.length&&(n+=" ",n+=o.join(" ")),n+=">",a.push(n),a.push(r),a.push(`</${s}>`),a.join("")}_propertyShapeObject(e,t={}){let{range:i,minCount:r=0}=e;if(r===0&&!this.opts.renderOptional||!i)return;let{types:s}=i;if(s.includes(u.aml.vocabularies.shapes.ScalarShape))return this._scalarShapeObject(i,{...t});if(s.includes(u.aml.vocabularies.shapes.NilShape)){let a=Mt(e);return this._nilShapeObject(i,{...t,forceName:a})}if(s.includes(u.aml.vocabularies.shapes.RecursiveShape))return;if(s.includes(u.w3.shacl.NodeShape))return this._nodePropertyObject(e,t);if(s.includes(u.aml.vocabularies.shapes.ArrayShape)||s.includes(u.aml.vocabularies.shapes.MatrixShape))return this._nodePropertyArray(e,t);let o=Mt(e);return this.processNode(i,{...t,forceName:o})}_collectExamples(e,t={}){if(!this.opts.renderExamples)return;let{isWrapped:i,nodeName:r,tagFill:s="",indent:o=0}=t,{examples:a=[]}=e,{inherits:n}=e;Array.isArray(n)&&n.length&&n.forEach(m=>{let h=m;if(h.types.includes(u.aml.vocabularies.shapes.UnionShape)){let k=h,{anyOf:w=[]}=k;h=this._readCurrentUnion(w)}let f=h;Array.isArray(f.examples)&&f.examples.length&&(a=a.concat(f.examples))});let l=a.filter(m=>!!m.structuredValue);if(!l.length)return;let d=[];i&&d.push(`${s}<${r}>`);let p=new Ge;return l.forEach(m=>{let h=p.generate(m.structuredValue,r,{indent:o+1});h!==void 0&&d.push(h)}),i&&d.push(`${s}</${r}>`),d.join(`
|
|
39
|
-
`)}_createTabs(e=0,t=0){return new Array(e*2+t).fill(" ").join("")}_nodePropertyObject(e,t={}){let i=[],r=Ze(String(e.name)),{indent:s=0}=t,o=this._createTabs(s),a,n=e.range,l=this._collectExamples(n,{tagFill:o,indent:s+1,nodeName:r}),d=[];if(l)a=l;else{let m=[];this._collectProperties(n).forEach(f=>{let{range:k,minCount:w=0}=f;if(w===0&&!this.opts.renderOptional)return;let S=k;if(S.xmlSerialization){let{prefix:A,attribute:_}=S.xmlSerialization;if(_&&S.types.includes(u.aml.vocabularies.shapes.ScalarShape)){let
|
|
39
|
+
`)}_createTabs(e=0,t=0){return new Array(e*2+t).fill(" ").join("")}_nodePropertyObject(e,t={}){let i=[],r=Ze(String(e.name)),{indent:s=0}=t,o=this._createTabs(s),a,n=e.range,l=this._collectExamples(n,{tagFill:o,indent:s+1,nodeName:r}),d=[];if(l)a=l;else{let m=[];this._collectProperties(n).forEach(f=>{let{range:k,minCount:w=0}=f;if(w===0&&!this.opts.renderOptional)return;let S=k;if(S.xmlSerialization){let{prefix:A,attribute:_}=S.xmlSerialization;if(_&&S.types.includes(u.aml.vocabularies.shapes.ScalarShape)){let $=Ze(S.xmlSerialization.name?S.xmlSerialization.name:f.name||S.name||jc);A&&($=`${A}:${$}`);let P=this._scalarValue(S);d.push(`${$}="${P}"`);return}}let E=this._propertyShapeObject(f,{indent:s});if(E!==void 0){let A=this._createTabs(s,2);m.push(Io(A,E))}}),a=m.join(`
|
|
40
40
|
`)}let p=`${o}<${r}`;return d.length&&(p+=" ",p+=d.join(" ")),i.unshift(`${p}>`),i.push(a),i.push(`${o}</${r}>`),i.join(`
|
|
41
41
|
`)}_nodePropertyArray(e,t={}){let i=e.range,r=[],s;i.xmlSerialization&&i.xmlSerialization.name?s=Ze(i.xmlSerialization.name):s=Ze(String(e.name));let{indent:o=0}=t,a=!!i.items&&i.items.types.includes(u.aml.vocabularies.shapes.ScalarShape),n=this._createTabs(o);a||r.push(`${n}<${s}>`);let l=this._arrayShapeObject(i,{...t,indent:o});return r.push(l),a||r.push(`${n}</${s}>`),r.join(`
|
|
42
42
|
`)}_arrayShapeObject(e,t={},i=!1){let{items:r}=e,s=!!r&&r.types.includes(u.aml.vocabularies.shapes.ScalarShape),o;i&&e.xmlSerialization&&e.xmlSerialization.name?o=Ze(e.xmlSerialization.name):i&&e.name?o=Ze(e.name):!s&&r?.name?o=Ze(r.name):e.name&&(o=Ze(e.name));let a=!1;e.xmlSerialization&&typeof e.xmlSerialization.wrapped=="boolean"&&(a=!0);let n=!!e.xmlSerialization&&!!e.xmlSerialization.wrapped,l=t.indent||0,d=new Array(l*2+0).fill(" ").join(""),p=new Array(l*2+(n?2:0)).fill(" ").join("");if(this.opts.renderExamples){let{examples:m=[]}=e,h=m.filter(f=>!!f.structuredValue);if(h.length){let f=[],k=new Ge;if(s&&!n){let[w]=h;!o&&r?.name&&(o=Ze(r.name));let S=k.generate(w.structuredValue,o,{indent:l});S!==void 0&&f.push(S)}else if(s&&n){let[w]=h,S=k.generate(w.structuredValue,o,{indent:l});f.push(`${d}<${o}>`),S!==void 0&&f.push(S),f.push(`${d}</${o}>`)}else n?h.forEach(w=>{f.push(`${d}<${o}>`);let S=k.generate(w.structuredValue,void 0,{indent:l+2});S!==void 0&&f.push(S),f.push(`${d}</${o}>`)}):h.forEach(w=>{let S=k.generate(w.structuredValue,void 0,{indent:l});S!==void 0&&f.push(S)});return f.join(`
|
|
@@ -48,9 +48,9 @@ Creating organization "${i}" with slug "${r}"...`);try{let a=(await c.organizati
|
|
|
48
48
|
`);return m.push(`${h}`),m.push(`${d}</${n}>`),m.join(`
|
|
49
49
|
`)}if(e.defaultValue)return this._unionDefaultValue(e,e.defaultValue);let a=this._readCurrentUnion(i);if(a)return this.processNode(a,{...t,forceName:e.name})}}_unionDefaultValue(e,t,i={}){let s=new Ge().generate(t),a=Mt(e),n=i.indent||0,l=new Array(n*2).fill(" ").join(""),d=[`${l}<${a}>`],p=new Array(n*2+2).fill(" ").join("");return d.push(`${p}${String(s).trim()}`),d.push(`${l}</${a}>`),d.join(`
|
|
50
50
|
`)}_fileShapeObject(){}_schemaShapeObject(){}_tupleShapeObject(){}_anyShapeObject(e){let{and:t=[],xone:i=[],or:r=[]}=e;if(t.length){let a=structuredClone(e);return a.and=[],a.properties=[],t.forEach(n=>{let{types:l}=n;if(l.includes(u.aml.vocabularies.shapes.ScalarShape)){let d=n;a.properties.push(d)}else if(l.includes(u.w3.shacl.NodeShape))n.properties.forEach(p=>a.properties.push(p));else if(l.includes(u.aml.vocabularies.shapes.ArrayShape)||l.includes(u.aml.vocabularies.shapes.MatrixShape)){let d=n;d.items&&a.properties.push(d.items)}}),this._nodeShapeObject(a)}if(i.length){let{selectedUnions:a=[]}=this.opts,n=i.find(l=>a.includes(l.id));return n||(n=i[0]),this.processNode(n)}if(r.length){let{selectedUnions:a=[]}=this.opts,n=r.find(l=>a.includes(l.id));return n||(n=r[0]),this.processNode(n)}let{examples:s=[]}=e,o=Mt(e);if(this.opts.renderExamples&&s&&s.length){let a=s.find(d=>!!d.structuredValue),n=this._exampleToObject(a),l=[];if(typeof n<"u"){let d=" ";l.push(`<${o}>`),l.push(`${d}${n}`),l.push(`</${o}>`)}return l.join(`
|
|
51
|
-
`)}return this._scalarShapeObject(e)}};var xd=wp(Ad(),1);var Fo=Symbol("findAmfType"),Ed=Symbol("findReferenceObject"),Ie=Symbol("getArrayItems"),_d=Symbol("computeReferenceSecurity"),Lc=c=>{class e extends c{_amf;__cachedKeys;__lastSetValue;get amf(){return this._amf}set amf(i){if(this._amf===i||this.__lastSetValue===i)return;this.__lastSetValue=i;let r=i?this._expand(i):void 0;this.__cachedKeys={},this._amf=r,this._amfChanged(r)}_amfChanged(i){}_expand(i){return xd.AmfModelExpander.expand(i)}_getAmfKey(i,r){if(!i)return"";let{amf:s}=this;if(!s&&!r)return i;Array.isArray(s)&&([s]=s),this.__cachedKeys||(this.__cachedKeys={});let o=r||s&&s["@context"];if(!o||!i)return i;let a=this.__cachedKeys;if(i in a)return a[i];i=String(i);let n=i.indexOf("#"),l=i.substring(0,n+1),d=Object.keys(o);for(let p=0,m=d.length;p<m;p++){let h=d[p];if(o[h]===i)return a[i]=h,h;if(n===-1&&i.indexOf(o[h])===0){let f=i.replace(o[h],`${h}:`);return a[i]=f,f}if(o[h]===l){let f=`${h}:${i.substring(n+1)}`;return a[i]=f,f}}return i}_ensureAmfModel(i){if(i&&(Array.isArray(i)&&([i]=i),this._hasType(i,u.aml.vocabularies.document.Document)))return i}_ensureArray(i){if(i)return i instanceof Array?i:[i]}_getValue(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&i[o];if(!a)return a;if(Array.isArray(a)&&([a]=a),!a)return;let n=typeof a;return["string","number","boolean","undefined"].includes(n)?a:a["@value"]}_getValueArray(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&this._ensureArray(i[o]);if(Array.isArray(a))return a.map(n=>n["@value"]||n)}[Ie](i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&this._ensureArray(i[o]);if(Array.isArray(a))return a}_getLinkValue(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&i[o];if(a&&(Array.isArray(a)&&([a]=a),!!a))return a["@id"]}_getLinkValues(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&i[o];if(a)return Array.isArray(a)||(a=[a]),a.map(n=>n["@id"])}_hasType(i,r,s){let o=this._ensureArray(i&&i["@type"]);if(!o||!o.length)return!1;let a=this._getAmfKey(r,s);for(let n of o)if(n===a)return!0;return!1}_hasProperty(i,r,s){let o=this._getAmfKey(r,s);return!!(i&&o&&o in i)}_computePropertyArray(i,r,s){if(!i)return;let o=this._getAmfKey(r,s);if(!o)return;let a=this._ensureArray(i&&i[o]);if(!(!a||!Array.isArray(a)))return a}_computeApiVersion(i,r){let s=this._computeApi(i);if(s)return this._getValue(s,u.aml.vocabularies.core.version,r)}_computeEncodes(i,r){if(!i)return;Array.isArray(i)&&([i]=i);let s=this._getAmfKey(u.aml.vocabularies.document.encodes,r);if(!s)return;let o=i[s];if(o)return Array.isArray(o)?o[0]:o}_computeDeclares(i,r){if(!i||(Array.isArray(i)&&([i]=i),!i))return;let s=this._getAmfKey(u.aml.vocabularies.document.declares,r);if(!s)return;let o=this._ensureArray(i[s]);return Array.isArray(o)?o:void 0}_computeReferences(i,r){if(!i||(Array.isArray(i)&&([i]=i),!i))return;let s=this._getAmfKey(u.aml.vocabularies.document.references,r);if(!s)return;let o=this._ensureArray(i[s]);return o instanceof Array?o:void 0}_computeWebApi(i,r){let s=this._computeEncodes(i,r);if(s&&this._hasType(s,u.aml.vocabularies.apiContract.WebAPI,r))return s}_computeApi(i,r){let s=this._computeEncodes(i,r);if(s&&(this._isAPI(i,r)||this._isWebAPI(i,r)||this._isAsyncAPI(i,r)))return s}_isWebAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,u.aml.vocabularies.apiContract.WebAPI,r):!1}_isAsyncAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,u.aml.vocabularies.apiContract.AsyncAPI,r):!1}_isAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,u.aml.vocabularies.apiContract.API,r):!1}_isValidServerPartial(i,r){if(Array.isArray(i)&&([i]=i),!i)return!1;let s=u.aml.vocabularies.apiContract.Operation,o=u.aml.vocabularies.apiContract.EndPoint,a=[this._getAmfKey(s,r),this._getAmfKey(o,r)],n=i["@type"];for(let l of n)if(a.indexOf(l)!==-1)return!0;return!1}_getServers(i={},r){let{endpointId:s,methodId:o}=i,{amf:a}=this;if(!a)return;let n=this._computeApi(a,r);if(Array.isArray(n)&&([n]=n),!n)if(this._isValidServerPartial(a,r))n=a;else return;let l=this._getAmfKey(u.aml.vocabularies.apiContract.server,r),d=()=>this[Ie](n,l,r),p=()=>{let h=this._computeEndpointModel(n,s,r),f=this[Ie](h,l,r);return f||d()},m=()=>{let h=this._computeMethodModel(n,o,r),f=this[Ie](h,l,r);return f||p()};return o?m():s?p():d()}_computeExpects(i,r){let s=u.aml.vocabularies.apiContract.Operation,o=u.aml.vocabularies.apiContract.expects;if(this._hasType(i,s,r)){let a=this._getAmfKey(o,r),n=this._ensureArray(i[a]);if(n)return Array.isArray(n)?n[0]:n}}_computeEndpoints(i,r){if(!i)return[];let s=u.aml.vocabularies.apiContract.endpoint,o=this._getAmfKey(s,r);return this._ensureArray(i[o])}_computeEndpointModel(i,r,s){if(this._hasType(i,u.aml.vocabularies.apiContract.EndPoint,s))return i;let o=this._computeEndpoints(i,s);if(o)return o.find(a=>a["@id"]===r)}_computeMethodModel(i,r,s){let o=this.__computeMethodsListForMethod(i,r,s);if(o)return o.find(a=>a["@id"]===r)}_computeMethodEndpoint(i,r,s){if(!i||!r)return;if(this._hasType(i,u.aml.vocabularies.apiContract.EndPoint,s))return i;let o=this._computeEndpoints(i,s);if(!o)return;let a=this._getAmfKey(u.aml.vocabularies.apiContract.supportedOperation,s);for(let n=0,l=o.length;n<l;n++){let d=o[n],p=d[a];if(p){Array.isArray(p)||(p=[p]);for(let m=0,h=p.length;m<h;m++)if(p[m]["@id"]===r)return d}}}__computeMethodsListForMethod(i,r,s){let o=this._computeMethodEndpoint(i,r,s);if(!o)return;let a=this._getAmfKey(u.aml.vocabularies.apiContract.supportedOperation,s);return this._ensureArray(o[a])}_computeType(i,r,s,o){if(!i&&!r||!s)return;let a=s.replace("amf://id",""),n=i&&i.find(l=>l["@id"]===s||l["@id"]===a);if(!n&&r&&r.length)for(let l=0,d=r.length;l<d&&!(this._hasType(r[l],u.aml.vocabularies.document.Module)&&(n=this._computeReferenceType(r[l],s,o),n));l++);return n}[Fo](i,r){let{amf:s}=this;if(!s||!i)return;Array.isArray(s)&&([s]=s);let o=this._computeDeclares(s,r),a=i.replace("amf://id","");if(Array.isArray(o)){let n=o.find(l=>l["@id"]===i||l["@id"]===a);if(n)return n}return this[Ed](i)}[Ed](i,r){let{amf:s}=this;if(Array.isArray(s)&&([s]=s),!s)return;let o=this._computeReferences(s,r);if(!Array.isArray(o)||!o.length)return;let a=i.replace("amf://id","");for(let n=0,l=o.length;n<l;n++){let d=o[n],p=this._computeDeclares(d,r);if(Array.isArray(p))for(let m=0,h=p.length;m<h;m++){let f=p[m];if(Array.isArray(f)&&([f]=f),f["@id"]===i||f["@id"]===a)return f}}}_computeReferenceType(i,r,s){let o=this._computeDeclares(i,s);if(!o||!r)return;let a=r.replace("amf://id",""),n=o.find(l=>(Array.isArray(l)&&([l]=l),l["@id"]===r||l["@id"]===a));return Array.isArray(n)&&([n]=n),this._resolve(n)}_computeDocument(i,r,s){if(!i||!r)return;let o=this._getAmfKey(u.aml.vocabularies.core.documentation,s),a=this._ensureArray(i[o]);return a&&a.find(n=>n["@id"]===r)}_resolve(i,r){let{amf:s}=this;if(typeof i!="object"||Array.isArray(i)||!s||i.__apicResolved)return i;let o=this._getAmfKey(u.aml.vocabularies.document.linkTarget,r),a=this._ensureArray(i[o]),n;if(a){let p=a[0]["@id"];if(p===i["@id"])return i.__apicResolved=!0,i;n=this._getLinkTarget(s,p,r)}else if(o=this._getAmfKey(u.aml.vocabularies.document.referenceId,r),a=this._ensureArray(i[o]),a){let p=a[0]["@id"];if(p===i["@id"])return i.__apicResolved=!0,i;n=this._getReferenceId(s,p,r)}if(!n)return this._resolveRecursive(i),i.__apicResolved=!0,i;let l={...n};delete l["@id"];let d=l["@type"];return d&&(i["@type"]?i["@type"]=i["@type"].concat(d):i["@type"]=d,delete l["@type"]),this._mergeShapes(i,l,r),i.__apicResolved=!0,this._resolveRecursive(i),i}_getLinkTarget(i,r,s){if(!i||!r)return;let o,a=this._computeDeclares(i,s);if(a&&(o=this._findById(a,r)),!o){let n=this._computeReferences(i,s);o=this._obtainShapeFromReferences(n,r,s)}if(o)return o=this._resolve(o),o}_obtainShapeFromReferences(i,r,s){if(!Array.isArray(i)||!i.length)return;let o;for(let a of i){let n=this._computeEncodes(a,s);if(n&&n["@id"]===r){o=n;break}if(!n&&(o=this._findById(this._computeDeclares(a,s),r),o))break}return o}_findById(i,r){if(!i)return;let s;for(let o of i)if(o&&o["@id"]===r){s=o;break}return s}_getReferenceId(i,r,s){if(!i||!r)return;let o=this._computeReferences(i,s);if(o)for(let a of o){let n=this._computeEncodes(a,s);if(n&&n["@id"]===r)return n}}_resolveRecursive(i,r){Object.keys(i).forEach(s=>{let o=i[s];if(Array.isArray(o))for(let a=0,n=o.length;a<n;a++)o[a]=this._resolve(o[a]);else typeof o=="object"&&(i[s]=this._resolve(o,r))})}_mergeShapes(i,r,s){let o={...i,...r};return[{key:this._getAmfKey(u.aml.vocabularies.docSourceMaps.sources,s),merger:this._mergeSourceMapsSources.bind(this)}].forEach(({key:n,merger:l})=>{this._hasProperty(o,n,s)&&(o[n]=l(i,r,s))}),Object.assign(i,o)}_mergeSourceMapsSources(i,r,s){let o=this._getAmfKey(u.aml.vocabularies.docSourceMaps.sources,s),a=i[o]||{};Array.isArray(a)&&(a=a[0]);let n=r[o]||{};return Array.isArray(n)&&(n=n[0]),[Object.assign(a,n)]}_expandKey(i,r){let{amf:s}=this;if(!i||typeof i!="string"||!s&&!r)return i;Array.isArray(s)&&([s]=s);let o=r||s&&s["@context"];if(!o)return i;let[a,n]=i.split(":");if(!a||!n)return i;let l=o[a];return l?`${l}${n}`:i}findSecurityScheme(i,r){let{amf:s}=this,o=this._computeDeclares(s,r),a;if(o&&(a=o.find(l=>l["@id"]===i)),a)return a=this._resolve(a),a;let n=this._computeReferences(s,r);if(Array.isArray(n)&&n.length){for(let l of n)if(this._hasType(l,u.aml.vocabularies.document.Module,r)&&(a=this[_d](l,i,r),a))return a=this._resolve(a),a}}[_d](i,r,s){let o=this._computeDeclares(i,s);if(!o)return;let a=o.find(n=>{let l=n;return Array.isArray(l)&&([l]=l),l["@id"]===r});return Array.isArray(a)&&([a]=a),this._resolve(a)}getByType(i,r,s){if(!i)return[];let o=[],a=this._computeDeclares(i),n=this._getAmfKey(r,s);a&&a.length&&a.forEach(d=>{this._hasType(d,n)&&o.push(d)});let l=this._computeReferences(i);if(Array.isArray(l)&&l.length){for(let d of l)if(this._hasType(d,u.aml.vocabularies.document.Module)){let p=this.getByType(d,r,s);p.length&&(o=o.concat(p))}}return o}}return e};var Mc=class extends Lc(Object){constructor(e){super(),e&&(this.amf=e)}readTypes(e,t){let i=e;return typeof i=="string"&&(i=[i]),Array.isArray(i)?i.map(r=>this._expandKey(r,t)):[]}apiSummary(e){let t=e["@context"],i={id:e["@id"],types:this.readTypes(e["@type"],t),customDomainProperties:this.customDomainProperties(e,t),sourceMaps:this.sourceMap(e),schemes:[],accepts:[],contentType:[],documentations:[],tags:[]},r=this._getValue(e,u.aml.vocabularies.core.name,t);r&&typeof r=="string"&&(i.name=r);let s=this._getValue(e,u.aml.vocabularies.core.description,t);s&&typeof s=="string"&&(i.description=s);let o=this._getValue(e,u.aml.vocabularies.core.version,t);o&&typeof o=="string"&&(i.version=o);let a=this._getValue(e,u.aml.vocabularies.core.termsOfService,t);a&&typeof a=="string"&&(i.termsOfService=a);let n=e[this._getAmfKey(u.aml.vocabularies.apiContract.accepts,t)];Array.isArray(n)&&n.length&&(i.accepts=this._getValueArray(e,u.aml.vocabularies.apiContract.accepts,t));let l=e[this._getAmfKey(u.aml.vocabularies.apiContract.contentType,t)];Array.isArray(l)&&l.length&&(i.contentType=this._getValueArray(e,u.aml.vocabularies.apiContract.contentType,t));let d=e[this._getAmfKey(u.aml.vocabularies.apiContract.scheme,t)];Array.isArray(d)&&d.length&&(i.schemes=this._getValueArray(e,u.aml.vocabularies.apiContract.scheme,t));let p=e[this._getAmfKey(u.aml.vocabularies.core.provider,t)];Array.isArray(p)&&([p]=p),p&&(i.provider=this.provider(p));let m=e[this._getAmfKey(u.aml.vocabularies.core.license,t)];Array.isArray(m)&&([m]=m),m&&(i.license=this.license(m));let h=e[this._getAmfKey(u.aml.vocabularies.apiContract.tag,t)];Array.isArray(h)&&h.length&&(i.tags=h.map(k=>this.tag(k)));let f=e[this._getAmfKey(u.aml.vocabularies.core.documentation,t)];return Array.isArray(f)&&f.length&&(i.documentations=f.map(k=>this.documentation(k))),i}api(e,t){let i=t||e["@context"],r=this.apiSummary(e);r.endPoints=[],r.servers=[],r.security=[];let s=e[this._getAmfKey(u.aml.vocabularies.apiContract.endpoint,i)];Array.isArray(s)&&s.length&&(r.endPoints=s.map(n=>this.endPoint(n,i)));let o=e[this._getAmfKey(u.aml.vocabularies.apiContract.server,i)];Array.isArray(o)&&o.length&&(r.servers=o.map(n=>this.server(n,i)));let a=e[this._getAmfKey(u.aml.vocabularies.security.security,i)];return Array.isArray(a)&&a.length&&(r.security=a.map(n=>this.securityRequirement(n,i))),r}webApi(e,t){return this.api(e,t)}asyncApi(e,t){return this.api(e,t)}provider(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getLinkValue(e,u.aml.vocabularies.core.url,i);o&&typeof o=="string"&&(r.url=o);let a=this._getValue(e,u.aml.vocabularies.core.email,i);return a&&typeof a=="string"&&(r.email=a),r}license(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getLinkValue(e,u.aml.vocabularies.core.url,i);return o&&typeof o=="string"&&(r.url=o),r}server(e,t){let i=t||e["@context"],r=this._getValue(e,u.aml.vocabularies.core.urlTemplate,i)||"",s={id:e["@id"],types:this.readTypes(e["@type"],i),url:r,variables:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(s.description=o);let a=e[this._getAmfKey(u.aml.vocabularies.apiContract.variable,i)];Array.isArray(a)&&a.length&&(s.variables=a.map(p=>this.parameter(p,i)));let n=this._getValue(e,u.aml.vocabularies.apiContract.protocol,i),l=this._getValue(e,u.aml.vocabularies.apiContract.protocolVersion,i);n&&(s.protocol=n),l&&(s.protocolVersion=l);let d=e[this._getAmfKey(u.aml.vocabularies.security.security,i)];return Array.isArray(d)&&d.length&&(s.security=d.map(p=>this.securityRequirement(p,i))),s}parameter(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),payloads:[],examples:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.paramName,i);o&&typeof o=="string"&&(r.paramName=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.apiContract.required,i);typeof n=="boolean"&&(r.required=n);let l=this._getValue(e,u.aml.vocabularies.apiContract.allowEmptyValue,i);typeof l=="boolean"&&(r.allowEmptyValue=l);let d=this._getValue(e,u.aml.vocabularies.document.deprecated,i);typeof d=="boolean"&&(r.deprecated=d);let p=this._getValue(e,u.aml.vocabularies.apiContract.explode,i);typeof p=="boolean"&&(r.explode=p);let m=this._getValue(e,u.aml.vocabularies.apiContract.allowReserved,i);typeof m=="boolean"&&(r.allowReserved=m);let h=this._getValue(e,u.aml.vocabularies.apiContract.style,i);h&&typeof h=="string"&&(r.style=h);let f=this._getValue(e,u.aml.vocabularies.apiContract.binding,i);f&&typeof f=="string"&&(r.binding=f);let k=e[this._getAmfKey(u.aml.vocabularies.shapes.schema,i)];if(Array.isArray(k)&&k.length){let[E]=k;r.schema=this.unknownShape(E,{trackedId:e["@id"]},i)}let w=e[this._getAmfKey(u.aml.vocabularies.apiContract.payload,i)];Array.isArray(w)&&w.length&&(r.payloads=w.map(E=>this.payload(E,i)));let S=e[this._getAmfKey(u.aml.vocabularies.apiContract.examples,i)];return Array.isArray(S)&&S.length&&(r.examples=S.map(E=>this.example(E,i))),r}unknownShape(e,t,i){let r=i||e["@context"],s=this.readTypes(e["@type"],r);return s.includes(u.aml.vocabularies.shapes.ScalarShape)?this.scalarShape(e,t,r):s.includes(u.w3.shacl.NodeShape)?this.nodeShape(e,t,r):s.includes(u.aml.vocabularies.shapes.UnionShape)?this.unionShape(e,t,r):s.includes(u.aml.vocabularies.shapes.FileShape)?this.fileShape(e,t,r):s.includes(u.aml.vocabularies.shapes.SchemaShape)?this.schemaShape(e,t,r):s.includes(u.aml.vocabularies.shapes.TupleShape)?this.tupleShape(e,t,r):s.includes(u.aml.vocabularies.shapes.ArrayShape)||s.includes(u.aml.vocabularies.shapes.MatrixShape)?this.arrayShape(e,t,r):s.includes(u.aml.vocabularies.shapes.RecursiveShape)?this.recursiveShape(e,r):this.anyShape(e,t,r)}isLink(e,t){let i=t||e["@context"];return!!this._getLinkValue(e,u.aml.vocabularies.document.linkTarget,i)}getLinkTarget(e,t){let i=t||e["@context"],r=this._getLinkValue(e,u.aml.vocabularies.document.linkTarget,i);if(r)return this[Fo](r,i)}shape(e,t){let i=t||e["@context"];this._resolve(e);let r,s=e;if(this.isLink(s)){r=this._getValue(s,u.aml.vocabularies.document.linkLabel,i);let L=this._getLinkValue(s,u.aml.vocabularies.document.linkTarget,i),P=this[Fo](L,i);P&&(s=P)}let o={id:s["@id"],types:this.readTypes(e["@type"],i),values:[],inherits:[],or:[],and:[],xone:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)};r&&(o.linkLabel=r);let a=this._getValue(s,u.w3.shacl.name,i);a&&typeof a=="string"&&(o.name=a);let n=this._getValue(s,u.aml.vocabularies.core.displayName,i);if(n&&typeof n=="string")o.displayName=n;else{let L=this._getValue(s,u.aml.vocabularies.core.name,i);L&&typeof L=="string"&&(o.displayName=L)}let l=this._getValue(s,u.aml.vocabularies.core.description,i);l&&typeof l=="string"&&(o.description=l);let d=this._getValue(s,u.w3.shacl.defaultValueStr,i);d&&typeof d=="string"&&(o.defaultValueStr=d);let p=this._getValue(s,u.aml.vocabularies.shapes.deprecated,i);typeof p=="boolean"&&(o.deprecated=p);let m=this._getValue(s,u.aml.vocabularies.shapes.readOnly,i);typeof m=="boolean"&&(o.readOnly=m);let h=this._getValue(s,u.aml.vocabularies.shapes.writeOnly,i);typeof h=="boolean"&&(o.writeOnly=h);let f=s[this._getAmfKey(u.w3.shacl.defaultValue,i)];Array.isArray(f)&&f.length&&(o.defaultValue=this.unknownDataNode(f[0],i));let k=this._getAmfKey(u.w3.shacl.or,i),w=s[k];Array.isArray(w)&&w.length&&(o.or=w.map(L=>this.unknownShape(L,void 0,i)));let S=this._getAmfKey(u.w3.shacl.and,i),E=s[S];Array.isArray(E)&&E.length&&(o.and=E.map(L=>this.unknownShape(L,void 0,i)));let A=this._getAmfKey(u.w3.shacl.xone,i),_=s[A];Array.isArray(_)&&_.length&&(o.xone=_.map(L=>this.unknownShape(L,void 0,i)));let O=s[this._getAmfKey(u.w3.shacl.in,i)];if(Array.isArray(O)&&O.length){let[L]=O,P=u.w3.rdfSchema.key,R=this._getAmfKey(P,i);Object.keys(L).forEach(x=>{if(x.startsWith(P)||x.startsWith(R)){let D=L[x];Array.isArray(D)&&([D]=D);let M=this.unknownDataNode(D,i);M&&o.values.push(M)}})}let I=this._getAmfKey(u.w3.shacl.not,i),j=s[I];return j&&(Array.isArray(j)&&([j]=j),o.not=this.unknownShape(j,void 0,i)),o}anyShape(e,t={},i){let r=i||e["@context"],s=e,o=this.shape(s,r);if(this.isLink(s)){let d=this.getLinkTarget(s,r);d&&(s=d)}o.examples=[];let a=s[this._getAmfKey(u.aml.vocabularies.apiContract.examples,r)];if(Array.isArray(a)&&a.length)if(t.trackedId){let d=this.filterTrackedExamples(a,t.trackedId,r);o.examples=d.map(p=>this.example(p,r))}else{let d=this.filterNonTrackedExamples(a,r);o.examples=d.map(p=>this.example(p,r))}let n=s[this._getAmfKey(u.aml.vocabularies.core.documentation,r)];if(Array.isArray(n)&&n.length){let[d]=n;o.documentation=this.documentation(d,r)}let l=s[this._getAmfKey(u.aml.vocabularies.shapes.xmlSerialization,r)];return Array.isArray(l)&&l.length&&(o.xmlSerialization=this.xmlSerializer(l[0],r)),o}filterTrackedExamples(e,t,i){let{docSourceMaps:r}=u.aml.vocabularies,s=this._getAmfKey(r.sources,i),o=this._getAmfKey(r.trackedElement,i),a=t.indexOf("amf")===-1?`amf://id${t}`:t;return e.filter(n=>{let l=n;Array.isArray(l)&&([l]=l);let d=l[s];if(!d)return!0;Array.isArray(d)&&([d]=d);let p=d[o];if(!p)return!0;Array.isArray(p)&&([p]=p);let{value:m}=this.synthesizedField(p,i);if(!m)return!0;let h=m.split(",");return h.indexOf(a)!==-1||h.indexOf(t)!==-1})}filterNonTrackedExamples(e,t){let{docSourceMaps:i}=u.aml.vocabularies,r=this._getAmfKey(i.sources,t),s=this._getAmfKey(i.trackedElement,t);return e.filter(o=>{let a=o;Array.isArray(a)&&([a]=a);let n=a[r];if(!n)return!0;Array.isArray(n)&&([n]=n);let l=n[s];if(!l)return!0;Array.isArray(l)&&([l]=l);let{value:d}=this.synthesizedField(l,t);return!d})}scalarShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let k=this.getLinkTarget(s,r);k&&(s=k)}let a=this._getValue(s,u.w3.shacl.pattern,r);a&&typeof a=="string"&&(o.pattern=a);let n=this._getLinkValue(s,u.w3.shacl.datatype,r);n&&typeof n=="string"&&(o.dataType=n);let l=this._getValue(s,u.aml.vocabularies.shapes.format,r);l&&typeof l=="string"&&(o.format=l);let d=this._getValue(s,u.aml.vocabularies.shapes.multipleOf,r);typeof d=="number"&&(o.multipleOf=d);let p=this._getValue(s,u.w3.shacl.minInclusive,r);typeof p=="number"&&(o.minimum=p,o.exclusiveMinimum=!1);let m=this._getValue(s,u.w3.shacl.maxInclusive,r);typeof m=="number"&&(o.maximum=m,o.exclusiveMaximum=!1);let h=this._getValue(s,u.w3.shacl.minLength,r);typeof h=="number"&&(o.minLength=h);let f=this._getValue(s,u.w3.shacl.maxLength,r);return typeof f=="number"&&(o.maxLength=f),o}nodeShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let m=this.getLinkTarget(s,r);m&&(s=m)}let a=this._getValue(s,u.aml.vocabularies.shapes.discriminator,r);a&&typeof a=="string"&&(o.discriminator=a);let n=this._getValue(s,u.aml.vocabularies.shapes.discriminatorValue,r);n&&typeof n=="string"&&(o.discriminatorValue=n);let l=this._getValue(s,u.w3.shacl.closed,r);typeof l=="boolean"&&(o.closed=l),o.customShapeProperties=[],o.customShapePropertyDefinitions=[],o.dependencies=[];let d=s[this._getAmfKey(u.w3.shacl.property,r)];Array.isArray(d)&&d.length?o.properties=d.map(m=>this.propertyShape(m,r)):o.properties=[];let p=s[this._getAmfKey(u.w3.shacl.additionalPropertiesSchema,r)];if(Array.isArray(p)&&p.length===1){let[m]=p;o.additionalPropertiesSchema=this.unknownShape(m,void 0,r)}return o}propertyShape(e,t){let i=t||e["@context"],r=e,s=this.shape(r,i);if(this.isLink(r)){let d=this.getLinkTarget(r,i);d&&(r=d)}let o=this._getLinkValue(r,u.w3.shacl.path,i);o&&typeof o=="string"&&(s.path=o);let a=this._getValue(r,u.w3.shacl.minCount,i);typeof a=="number"&&(s.minCount=a);let n=this._getValue(r,u.w3.shacl.maxCount,i);typeof n=="number"&&(s.maxCount=n);let l=r[this._getAmfKey(u.aml.vocabularies.shapes.range,i)];if(Array.isArray(l)&&l.length){let[d]=l;s.range=this.unknownShape(d,void 0,i)}return s}unionShape(e,t={},i){let r=i||e["@context"],s=e[this._getAmfKey(u.aml.vocabularies.shapes.anyOf,r)],o=this.anyShape(e,t,r);if(Array.isArray(s)&&s.length){let a={...t,trackedId:void 0};o.anyOf=s.map(n=>this.unknownShape(n,a,r))}else o.anyOf=[];return o}fileShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let k=this.getLinkTarget(s,r);k&&(s=k)}let a=this._getValue(s,u.w3.shacl.pattern,r);a&&typeof a=="string"&&(o.pattern=a);let n=this._getValueArray(s,u.aml.vocabularies.shapes.fileType,r);Array.isArray(n)&&n.length&&(o.fileTypes=n);let l=this._getValue(s,u.w3.shacl.minLength,r);typeof l=="number"&&(o.minLength=l);let d=this._getValue(s,u.w3.shacl.maxLength,r);typeof d=="number"&&(o.maxLength=d);let p=this._getValue(s,u.w3.shacl.minInclusive,r);typeof p=="number"&&(o.minimum=p,o.exclusiveMinimum=!1);let m=this._getValue(s,u.w3.shacl.maxInclusive,r);typeof m=="number"&&(o.maximum=m,o.exclusiveMaximum=!1);let h=this._getValue(s,u.aml.vocabularies.shapes.format,r);h&&typeof h=="string"&&(o.format=h);let f=this._getValue(s,u.aml.vocabularies.shapes.multipleOf,r);return typeof f=="number"&&(o.multipleOf=f),o}schemaShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let l=this.getLinkTarget(s,r);l&&(s=l)}let a=this._getValue(s,u.aml.vocabularies.core.mediaType,r);a&&typeof a=="string"&&(o.mediaType=a);let n=this._getValue(s,u.aml.vocabularies.document.raw,r);return n&&typeof n=="string"&&(o.raw=n),o}recursiveShape(e,t){let i=t||e["@context"],r=e,s=this.shape(r,i);if(this.isLink(r)){let a=this.getLinkTarget(r,i);a&&(r=a)}let o=this._getLinkValue(r,u.aml.vocabularies.shapes.fixPoint,i);return o&&typeof o=="string"&&(s.fixPoint=o),s}dataArrangeShape(e,t={},i){let r=i||e["@context"];return this.anyShape(e,t,r)}arrayShape(e,t={},i){let r=i||e["@context"],s=e,o=this.dataArrangeShape(s,t,r);if(this.isLink(s)){let n=this.getLinkTarget(s,r);n&&(s=n)}let a=s[this._getAmfKey(u.aml.vocabularies.shapes.items,r)];if(Array.isArray(a)&&a.length){let[n]=a;o.items=this.unknownShape(n,void 0,r)}return o}tupleShape(e,t,i){let r=i||e["@context"],s=e,o=this.dataArrangeShape(s,t,r);if(this.isLink(s)){let l=this.getLinkTarget(s,r);l&&(s=l)}let a=s[this._getAmfKey(u.aml.vocabularies.shapes.items,r)],n=this._getAmfKey(u.w3.rdfSchema.key,r);return Array.isArray(a)&&a.length?(o.items=[],a.forEach(l=>{Array.isArray(l)&&([l]=l),Object.keys(l).filter(d=>d.startsWith(n)).forEach(d=>{let p=l[d];Array.isArray(p)&&([p]=p);let m=this.unknownShape(p,void 0,r);o.items.push(m)})})):o.items=[],o}documentation(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getLinkValue(e,u.aml.vocabularies.core.url,i);s&&typeof s=="string"&&(r.url=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,u.aml.vocabularies.core.title,i);return a&&typeof a=="string"&&(r.title=a),r}example(e,t){let i=t||e["@context"];this._resolve(e);let r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),strict:!1},s=this._getValue(e,u.aml.vocabularies.document.strict,i);typeof s=="boolean"&&(r.strict=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.displayName,i);a&&typeof a=="string"&&(r.displayName=a);let n=this._getValue(e,u.aml.vocabularies.core.description,i);n&&typeof n=="string"&&(r.description=n);let l=this._getValue(e,u.aml.vocabularies.document.raw,i);l&&typeof l=="string"&&(r.value=l);let d=this._getValue(e,u.aml.vocabularies.document.location,i);d&&typeof d=="string"&&(r.location=d);let p=e[this._getAmfKey(u.aml.vocabularies.document.structuredValue,i)];if(Array.isArray(p)&&p.length){let[m]=p;r.structuredValue=this.unknownDataNode(m,i)}return r}xmlSerializer(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.shapes.xmlAttribute,i);typeof s=="boolean"&&(r.attribute=s);let o=this._getValue(e,u.aml.vocabularies.shapes.xmlWrapped,i);typeof o=="boolean"&&(r.wrapped=o);let a=this._getValue(e,u.aml.vocabularies.shapes.xmlName,i);a&&typeof a=="string"&&(r.name=a);let n=this._getValue(e,u.aml.vocabularies.shapes.xmlNamespace,i);n&&typeof n=="string"&&(r.namespace=n);let l=this._getValue(e,u.aml.vocabularies.shapes.xmlPrefix,i);return l&&typeof l=="string"&&(r.prefix=l),r}unknownDataNode(e,t){let i=this.readTypes(e["@type"],t);if(i.includes(u.aml.vocabularies.data.Scalar))return this.scalarNode(e,t);if(i.includes(u.aml.vocabularies.data.Object))return this.objectNode(e,t);if(i.includes(u.aml.vocabularies.data.Array))return this.arrayNode(e,t)}dataNode(e,t){let i={id:e["@id"],types:this.readTypes(e["@type"],t),customDomainProperties:this.customDomainProperties(e,t)},r=this._getValue(e,u.aml.vocabularies.core.name,t);return r&&typeof r=="string"&&(i.name=r),i}scalarNode(e,t){let i=t||e["@context"],r=this.dataNode(e,t),s=this._getValue(e,u.aml.vocabularies.data.value,i);s&&typeof s=="string"&&(r.value=s);let o=this._getLinkValue(e,u.w3.shacl.datatype,i);return o&&typeof o=="string"&&(r.dataType=o),r}objectNode(e,t){let i=t||e["@context"],r=this.dataNode(e,t);r.properties={};let s=u.aml.vocabularies.data.key,o=`${this._getAmfKey(s,i)}:`;return Object.keys(e).forEach(a=>{if(a.startsWith(s)||a.startsWith(o)){let n=e[a];Array.isArray(n)&&([n]=n);let l=a.replace(s,"").replace(o,""),d=this.unknownDataNode(n,t);d&&(r.properties[l]=d)}}),r}arrayNode(e,t){let i=t||e["@context"],r=this.dataNode(e,i);r.members=[];let s=this._computePropertyArray(e,u.w3.rdfSchema.member);return Array.isArray(s)&&s.length&&s.forEach(o=>{let a=this.unknownDataNode(o);a&&r.members.push(a)}),r}customDomainProperties(e,t){let i=[],r=t||e["@context"],s=this._getLinkValues(e,u.aml.vocabularies.document.customDomainProperties,r);return Array.isArray(s)&&s.length&&s.forEach(o=>{let a=`@base:${o}`,n=e[o]||e[a];if(!n)return;Array.isArray(n)&&([n]=n);let l=this.unknownDataNode(n,r),d=this._getValue(n,u.aml.vocabularies.core.extensionName,r);if(!d||!l)return;let p={id:o,name:d,extension:l};i.push(p)}),i}endPoint(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),path:"",operations:[],parameters:[],payloads:[],servers:[],security:[],extends:[]},s=this._getValue(e,u.aml.vocabularies.apiContract.path,i);s&&typeof s=="string"&&(r.path=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.core.summary,i);n&&typeof n=="string"&&(r.summary=n);let l=this[Ie](e,u.aml.vocabularies.apiContract.supportedOperation,i);Array.isArray(l)&&l.length&&(r.operations=l.map(k=>this.operation(k,i)));let d=this[Ie](e,u.aml.vocabularies.apiContract.parameter,i);Array.isArray(d)&&d.length&&(r.parameters=d.map(k=>this.parameter(k,i)));let p=this[Ie](e,u.aml.vocabularies.apiContract.payload,i);Array.isArray(p)&&p.length&&(r.payloads=p.map(k=>this.payload(k,i)));let m=this[Ie](e,u.aml.vocabularies.apiContract.server,i);Array.isArray(m)&&m.length&&(r.servers=m.map(k=>this.server(k,i)));let h=this[Ie](e,u.aml.vocabularies.security.security,i);Array.isArray(h)&&h.length&&(r.security=h.map(k=>this.securityRequirement(k,i)));let f=this[Ie](e,u.aml.vocabularies.document.extends,i);return Array.isArray(f)&&f.length&&(r.extends=[],f.forEach(k=>{let w=k;Array.isArray(w)&&([w]=w),this._hasType(w,u.aml.vocabularies.apiContract.ParametrizedResourceType,i)?r.extends.push(this.parametrizedResourceType(w,i)):this._hasType(w,u.aml.vocabularies.apiContract.ParametrizedTrait,i)&&r.extends.push(this.parametrizedTrait(w,i))})),r}operation(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),method:"",deprecated:!1,callbacks:[],responses:[],servers:[],security:[],accepts:[],schemes:[],contentType:[],tags:[],extends:[]},s=this._getValue(e,u.aml.vocabularies.apiContract.method,i);s&&typeof s=="string"&&(r.method=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.apiContract.guiSummary,i);n&&typeof n=="string"&&(r.summary=n);let l=this._getValue(e,u.aml.vocabularies.core.deprecated,i);typeof l=="boolean"&&(r.deprecated=l);let d=this._getValue(e,u.aml.vocabularies.apiContract.operationId,i);d&&typeof d=="string"&&(r.operationId=d);let p=this._getValueArray(e,u.aml.vocabularies.apiContract.accepts,i);Array.isArray(p)&&(r.accepts=p);let m=this._getValueArray(e,u.aml.vocabularies.apiContract.scheme,i);Array.isArray(m)&&(r.schemes=m);let h=this._getValueArray(e,u.aml.vocabularies.apiContract.contentType,i);Array.isArray(h)&&(r.contentType=h);let f=e[this._getAmfKey(u.aml.vocabularies.apiContract.expects,i)];f&&(Array.isArray(f)&&([f]=f),r.request=this.request(f,i));let k=e[this._getAmfKey(u.aml.vocabularies.core.documentation,i)];k&&(Array.isArray(k)&&([k]=k),r.documentation=this.documentation(k,i));let w=e[this._getAmfKey(u.aml.vocabularies.apiContract.returns,i)];Array.isArray(w)&&(r.responses=w.map(I=>this.response(I,i)));let S=e[this._getAmfKey(u.aml.vocabularies.apiContract.callback,i)];Array.isArray(S)&&(r.callbacks=S.map(I=>this.callback(I,i)));let E=e[this._getAmfKey(u.aml.vocabularies.apiContract.server,i)];Array.isArray(E)&&(r.servers=E.map(I=>this.server(I)));let A=e[this._getAmfKey(u.aml.vocabularies.security.security,i)];Array.isArray(A)&&(r.security=A.map(I=>this.securityRequirement(I,i)));let _=e[this._getAmfKey(u.aml.vocabularies.apiContract.tag,i)];Array.isArray(_)&&_.length&&(r.tags=_.map(I=>this.tag(I,i)));let O=e[this._getAmfKey(u.aml.vocabularies.document.extends,i)];return Array.isArray(O)&&O.length&&(r.extends=O.map(I=>this.parametrizedTrait(I,i))),r}tag(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),name:""},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=e[this._getAmfKey(u.aml.vocabularies.core.documentation,i)];return a&&(Array.isArray(a)&&([a]=a),r.documentation=this.documentation(a,i)),r}tagListItem(e,t){let i=t||e["@context"],r={id:e["@id"],name:""},s=this._getValue(e,u.aml.vocabularies.core.name,i);return s&&typeof s=="string"&&(r.name=s),r}callback(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.expression,i);o&&typeof o=="string"&&(r.expression=o);let a=e[this._getAmfKey(u.aml.vocabularies.apiContract.endpoint,i)];return a&&(Array.isArray(a)&&([a]=a),r.endpoint=this.endPoint(a,i)),r}request(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),required:!1,headers:[],queryParameters:[],payloads:[],uriParameters:[],cookieParameters:[]},s=this._getValue(e,u.aml.vocabularies.core.description,i);s&&typeof s=="string"&&(r.description=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.required,i);o&&typeof o=="boolean"&&(r.required=o);let a=e[this._getAmfKey(u.aml.vocabularies.apiContract.queryString,i)];a&&(Array.isArray(a)&&([a]=a),r.queryString=this.unknownShape(a,void 0,i));let n=this[Ie](e,u.aml.vocabularies.apiContract.header,i);Array.isArray(n)&&n.length&&(r.headers=n.map(h=>this.parameter(h,i)));let l=this[Ie](e,u.aml.vocabularies.apiContract.parameter,i);Array.isArray(l)&&l.length&&(r.queryParameters=l.map(h=>this.parameter(h,i)));let d=this[Ie](e,u.aml.vocabularies.apiContract.uriParameter,i);Array.isArray(d)&&d.length&&(r.uriParameters=d.map(h=>this.parameter(h,i)));let p=this[Ie](e,u.aml.vocabularies.apiContract.cookieParameter,i);Array.isArray(p)&&p.length&&(r.cookieParameters=p.map(h=>this.parameter(h,i)));let m=this[Ie](e,u.aml.vocabularies.apiContract.payload,i);return Array.isArray(m)&&m.length&&(r.payloads=m.map(h=>this.payload(h,i))),r}response(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),headers:[],payloads:[],examples:[],links:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,u.aml.vocabularies.apiContract.statusCode,i);a&&typeof a=="string"&&(r.statusCode=a);let n=this[Ie](e,u.aml.vocabularies.apiContract.header,i);Array.isArray(n)&&n.length&&(r.headers=n.map(m=>this.parameter(m,i)));let l=this[Ie](e,u.aml.vocabularies.apiContract.payload,i);Array.isArray(l)&&l.length&&(r.payloads=l.map(m=>this.payload(m,i)));let d=e[this._getAmfKey(u.aml.vocabularies.apiContract.examples,i)];Array.isArray(d)&&d.length&&(r.examples=d.map(m=>this.example(m,i)));let p=e[this._getAmfKey(u.aml.vocabularies.apiContract.link,i)];return Array.isArray(p)&&p.length&&(r.links=p.map(m=>this.templatedLink(m,i))),r}payload(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),examples:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.mediaType,i);o&&typeof o=="string"&&(r.mediaType=o);let a=e[this._getAmfKey(u.aml.vocabularies.shapes.schema,i)];a&&(Array.isArray(a)&&([a]=a),r.schema=this.unknownShape(a,{trackedId:r.id},i));let n=e[this._getAmfKey(u.aml.vocabularies.apiContract.examples,i)];return Array.isArray(n)&&n.length&&(r.examples=n.map(l=>this.example(l,i))),r}templatedLink(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),mapping:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,u.aml.vocabularies.apiContract.operationId,i);a&&typeof a=="string"&&(r.operationId=a);let n=e[this._getAmfKey(u.aml.vocabularies.apiContract.server,i)];n&&(Array.isArray(n)&&([n]=n),r.server=this.server(n,i));let l=e[this._getAmfKey(u.aml.vocabularies.apiContract.mapping,i)];return l&&(l&&!Array.isArray(l)&&(l=[l]),l&&(r.mapping=l.map(d=>this.iriTemplateMapping(d,i)))),r}iriTemplateMapping(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.apiContract.templateVariable,i);s&&typeof s=="string"&&(r.templateVariable=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.linkExpression,i);return o&&typeof o=="string"&&(r.linkExpression=o),r}parametrizedSecurityScheme(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(u.aml.vocabularies.security.scheme,i)];o&&(Array.isArray(o)&&([o]=o),r.scheme=this.securityScheme(o,i));let a=e[this._getAmfKey(u.aml.vocabularies.security.settings,i)];return a&&(Array.isArray(a)&&([a]=a),r.settings=this.securitySettings(a,i)),r}securitySchemeListItem(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),type:""},s=this._getValue(e,u.aml.vocabularies.security.type,i);s&&typeof s=="string"&&(r.type=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.displayName,i);return a&&typeof a=="string"&&(r.displayName=a),r}securityScheme(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),headers:[],queryParameters:[],responses:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.displayName,i);o&&typeof o=="string"&&(r.displayName=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.security.type,i);n&&typeof n=="string"&&(r.type=n);let l=e[this._getAmfKey(u.aml.vocabularies.security.settings,i)];l&&(Array.isArray(l)&&([l]=l),r.settings=this.securitySettings(l,i));let d=e[this._getAmfKey(u.aml.vocabularies.apiContract.queryString,i)];d&&(Array.isArray(d)&&([d]=d),r.queryString=this.unknownShape(d,void 0,i));let p=this[Ie](e,u.aml.vocabularies.apiContract.header,i);Array.isArray(p)&&p.length&&(r.headers=p.map(f=>this.parameter(f,i)));let m=this[Ie](e,u.aml.vocabularies.apiContract.parameter,i);Array.isArray(m)&&m.length&&(r.queryParameters=m.map(f=>this.parameter(f,i)));let h=this[Ie](e,u.aml.vocabularies.apiContract.response,i);return Array.isArray(h)&&h.length&&(r.responses=h.map(f=>this.response(f,i))),r}securityRequirement(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),schemes:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(u.aml.vocabularies.security.schemes,i)];return Array.isArray(o)&&o.length&&(r.schemes=o.map(a=>this.parametrizedSecurityScheme(a,i))),r}securitySettings(e,t){let i=t||e["@context"],r=this.readTypes(e["@type"],i);return r.includes(u.aml.vocabularies.security.OAuth1Settings)?this.oAuth1Settings(e,i):r.includes(u.aml.vocabularies.security.OAuth2Settings)?this.oAuth2Settings(e,i):r.includes(u.aml.vocabularies.security.ApiKeySettings)?this.apiKeySettings(e,i):r.includes(u.aml.vocabularies.security.HttpSettings)?this.httpSettings(e,i):r.includes(u.aml.vocabularies.security.OpenIdConnectSettings)?this.openIdConnectSettings(e,i):this.settings(e,i)}settings(e,t){let i=t||e["@context"];return{id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)}}oAuth1Settings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let o=this._getValue(e,u.aml.vocabularies.security.requestTokenUri,i);o&&typeof o=="string"&&(r.requestTokenUri=o);let a=this._getValue(e,u.aml.vocabularies.security.tokenCredentialsUri,i);a&&typeof a=="string"&&(r.tokenCredentialsUri=a);let n=this._getValueArray(e,u.aml.vocabularies.security.signature,i);return Array.isArray(n)&&n.length?r.signatures=n:r.signatures=[],r}oAuth2Settings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValueArray(e,u.aml.vocabularies.security.authorizationGrant,i);Array.isArray(s)&&s.length?r.authorizationGrants=s:r.authorizationGrants=[];let o=e[this._getAmfKey(u.aml.vocabularies.security.flows,i)];return Array.isArray(o)&&o.length?r.flows=o.map(a=>this.oAuth2Flow(a,i)):r.flows=[],r}oAuth2Flow(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),scopes:[],sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let o=this._getValue(e,u.aml.vocabularies.security.accessTokenUri,i);o&&typeof o=="string"&&(r.accessTokenUri=o);let a=this._getValue(e,u.aml.vocabularies.security.flow,i);a&&typeof a=="string"&&(r.flow=a);let n=this._getValue(e,u.aml.vocabularies.security.refreshUri,i);n&&typeof n=="string"&&(r.refreshUri=n);let l=e[this._getAmfKey(u.aml.vocabularies.security.scope,i)];return Array.isArray(l)&&l.length&&(r.scopes=l.map(d=>this.scope(d,i))),r}scope(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);return o&&typeof o=="string"&&(r.description=o),r}apiKeySettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.security.in,i);return o&&typeof o=="string"&&(r.in=o),r}httpSettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.security.scheme,i);s&&typeof s=="string"&&(r.scheme=s);let o=this._getValue(e,u.aml.vocabularies.security.bearerFormat,i);return o&&typeof o=="string"&&(r.bearerFormat=o),r}openIdConnectSettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.security.openIdConnectUrl,i);return s&&typeof s=="string"&&(r.url=s),r}sourceMap(e,t){let i=t||e["@context"],r=e[this._getAmfKey(u.aml.vocabularies.docSourceMaps.sources,i)];if(!r)return;Array.isArray(r)&&([r]=r);let s={id:r["@id"],types:this.readTypes(r["@type"])},o=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.synthesizedField,i)];Array.isArray(o)&&o.length&&(s.synthesizedField=o.map(m=>this.synthesizedField(m,i)));let a=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.lexical,i)];Array.isArray(a)&&a.length&&(s.lexical=a.map(m=>this.synthesizedField(m,i)));let n=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.trackedElement,i)];Array.isArray(n)&&n.length&&(s.trackedElement=this.synthesizedField(n[0],i));let l=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.autoGeneratedName,i)];Array.isArray(l)&&l.length&&(s.autoGeneratedName=l.map(m=>this.synthesizedField(m,i)));let d=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.parsedJsonSchema,i)];Array.isArray(d)&&d.length&&(s.parsedJsonSchema=this.synthesizedField(d[0],i));let p=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.declaredElement,i)];return Array.isArray(p)&&p.length&&(s.declaredElement=this.synthesizedField(p[0],i)),s}synthesizedField(e,t){if(typeof e=="string")return{id:"synthesizedField/generated",value:e};let i={id:e["@id"],value:""},r=this._getValue(e,u.aml.vocabularies.docSourceMaps.element,t);typeof r=="string"&&(i.element=r);let s=this._getValue(e,u.aml.vocabularies.docSourceMaps.value,t);return typeof s=="string"&&(i.value=s),i}parametrizedDeclaration(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),variables:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(u.aml.vocabularies.document.variable,i)];Array.isArray(o)&&o.forEach(n=>{r.variables.push(this.variableValue(n,i))});let a=e[this._getAmfKey(u.aml.vocabularies.document.target,i)];if(Array.isArray(a)&&a.length){let[n]=a;r.target=this.abstractDeclaration(n,i)}return r}parametrizedTrait(e,t){let i=t||e["@context"];return this.parametrizedDeclaration(e,i)}parametrizedResourceType(e,t){let i=t||e["@context"];return this.parametrizedDeclaration(e,i)}variableValue(e,t){let i=t||e["@context"],r=this._getValue(e,u.aml.vocabularies.core.name,i),s={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),name:r},o=e[this._getAmfKey(u.aml.vocabularies.document.value,i)];if(Array.isArray(o)){let[a]=o;s.value=this.unknownDataNode(a,i)}return s}abstractDeclaration(e,t){let i=t||e["@context"],r=this._getValue(e,u.aml.vocabularies.core.name,i),s={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),name:r,variables:[]},o=this._getValueArray(e,u.aml.vocabularies.document.variable,i);Array.isArray(o)&&(s.variables=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(s.description=a);let n=e[this._getAmfKey(u.aml.vocabularies.document.dataNode,i)];if(Array.isArray(n)){let[l]=n;s.dataNode=this.unknownDataNode(l,i)}return s}endPointWithOperationsListItem(e,t){let i=this._getValue(e,u.aml.vocabularies.apiContract.path,t),r={id:e["@id"],path:i,operations:[]},s=this[Ie](e,u.aml.vocabularies.apiContract.supportedOperation,t);Array.isArray(s)&&s.length&&(r.operations=s.map(a=>this.operationListItem(a,t)));let o=this._getValue(e,u.aml.vocabularies.core.name,t);return o&&typeof o=="string"&&(r.name=o),r}operationListItem(e,t){let i={id:e["@id"],method:""},r=this._getValue(e,u.aml.vocabularies.apiContract.method,t);r&&typeof r=="string"&&(i.method=r);let s=this._getValue(e,u.aml.vocabularies.core.name,t);return s&&typeof s=="string"&&(i.name=s),i}};var Ni=class c{mime;opts;generator;constructor(e,t={}){this.mime=e,this.opts=Object.freeze({...t}),e.includes("json")?this.generator=new ns(t):e.includes("xml")&&(this.generator=new cs(t))}static asExample(e,t,i){return new c(t,i).toExample(e)}static asSchema(e,t,i){return new c(t,i).toValue(e)}generate(e){let{generator:t}=this;if(t)return t.generate(e)}toValue(e){return this.generate(e)}toExample(e){let t=this.generate(e);if(t==null)return;let i={id:`${e.id}/generated`,strict:!0,types:[u.aml.vocabularies.apiContract.Example],mediaType:this.mime,renderValue:t,customDomainProperties:[]},r=e;if(Array.isArray(r.examples)&&r.examples.length){let[s]=r.examples;s.value&&(i.value=s.value)}return i}};var tr=Object.freeze({processApiLink:"amfprocessapilink",processBuffer:"amfprocessbuffer",processApiFile:"amfprocessapifile",selectApiMainFile:"amfselectapimainfile"});var Nm=Object.freeze({processApiLink:async(c,e,t,i,r=globalThis)=>{let s=new CustomEvent(tr.processApiLink,{bubbles:!0,composed:!0,cancelable:!0,detail:{url:c,mainFile:e,md5:t,packaging:i}});return r.dispatchEvent(s),s.detail.result},processBuffer:async(c,e,t=globalThis)=>{let i=new CustomEvent(tr.processBuffer,{bubbles:!0,composed:!0,cancelable:!0,detail:{buffer:c,opts:e}});return t.dispatchEvent(i),i.detail.result},processApiFile:async(c,e=globalThis)=>{let t=new CustomEvent(tr.processApiFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{file:c}});return e.dispatchEvent(t),t.detail.result},selectApiMainFile:async(c,e=globalThis)=>{let t=new CustomEvent(tr.selectApiMainFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{candidates:c}});return e.dispatchEvent(t),t.detail.result}});var Uc=["string","number","boolean","date","datetime","time","binary","json"],ls;(function(c){c.string="string",c.number="number",c.boolean="boolean",c.date="date",c.datetime="datetime",c.time="time",c.file="binary",c.json="json"})(ls||(ls={}));var Id=["required","multiple","primary","index","unique","search","readOnly","writeOnly","deprecated","immutable"],Pd=["required","multiple"],Rd=["float","double","int32","int64"];function qo(c,e){return c==="number"?e?.format==="int32"||e?.format==="int64"?u.w3.xmlSchema.integer:u.w3.xmlSchema.number:c==="boolean"?u.aml.vocabularies.shapes.boolean:c==="date"?u.w3.xmlSchema.date:c==="datetime"?u.w3.xmlSchema.dateTime:c==="time"?u.aml.vocabularies.shapes.dateTimeOnly:u.w3.xmlSchema.string}var Ti=Symbol("noValue"),ds=class{increment=0;static noValue=Ti;generate(e,t){return t==="string"?this.generateString(e):t==="number"?this.generateNumber(e):t==="date"?this.generateDate(e):t==="time"?this.generateTime(e):t==="datetime"?this.generateDateTime(e):Ti}generateString(e){switch(e){case"random":return W(8);case"uuid-v4":return crypto.randomUUID();default:return Ti}}generateNumber(e){return e==="incremental"?`${this.increment++}`:Ti}generateDate(e){if(e==="now"){let t=new Date,i=t.getFullYear(),r=`${t.getMonth()+1}`.padStart(2,"0"),s=`${t.getDate()}`.padStart(2,"0");return`${i}-${r}-${s}`}return Ti}generateTime(e){if(e==="now"){let t=new Date,i=`${t.getHours()}`.padStart(2,"0"),r=`${t.getMinutes()}`.padStart(2,"0"),s=`${t.getSeconds()}`.padStart(2,"0");return`${i}:${r}:${s}`}return Ti}generateDateTime(e){if(e==="now"){let t=new Date,i=t.getFullYear(),r=`${t.getMonth()+1}`.padStart(2,"0"),s=`${t.getDate()}`.padStart(2,"0"),o=`${t.getHours()}`.padStart(2,"0"),a=`${t.getMinutes()}`.padStart(2,"0"),n=`${t.getSeconds()}`.padStart(2,"0");return`${i}-${r}-${s}T${o}:${a}:${n}`}return Ti}};var zc="anyOf",Tm="allOf",jm="oneOf",Cm="not",Vc="string",$d="binary",bi=class{#e;get valueGenerator(){return this.#e||(this.#e=new ds),this.#e}entity(e,t=new Set){if(t.has(e.key))return this.createRecursiveShape(e);t.add(e.key);let i=Xe.nodeShape(e.key);i.id=e.key,this.updateBaseProperties(e,i),i.properties=[];for(let r of e.listProperties()){let s=r.readBinding("web");if(s&&s.hidden)continue;let o=this.property(r);i.properties.push(o)}for(let r of e.listAssociations()){let s=r.readBinding("web");if(s&&s.hidden)continue;let o=this.associationProperty(r,t);i.properties.push(o)}for(let r of e.listParents()){let s=this.entity(r,t);i.inherits.push(s)}return i}property(e){let{required:t,key:i}=e,r=Xe.propertyShape(i);return r.path=`${u.aml.vocabularies.data.key}${e.info.name}`,t&&(r.minCount=1),r.range=this.getRange(e),this.updateBaseProperties(e,r),r.range.name&&(r.name=r.range.name),r}associationProperty(e,t=new Set){let{required:i,key:r}=e,s=Xe.propertyShape(r);return s.path=`${u.aml.vocabularies.data.key}${e.info.name}`,i&&(s.minCount=1),s.range=this.associationShape(e,t),this.updateBaseProperties(e,s),s}associationShape(e,t=new Set){let i=e.schema;if(!i?.embedded)return this.createLinkedShape(e);let r=this.associationUnion(e,t);if(!r)return;if(Array.isArray(r))return this.createUnionShape(e,r);if((i&&i.unionType||zc)===Cm){let o=Xe.anyShape(e.key);return o.id=`not-shape-${e.key}`,o.not=r,o}return e.multiple?this.refactorShapeToArray(e.key,r):r}createLinkedShape(e){let t=Xe.scalarShape(e.key);return t.id=`link-${e.key}`,t.dataType=qo(Vc),t}createUnionShape(e,t){let i=Xe.unionShape(e.key);this.updateBaseProperties(e,i),i.anyOf=[];let r=e.schema&&e.schema.unionType||zc;return r===zc?i.anyOf=t:r===Tm?i.and=t:r===jm?i.xone=t:i.not=t[0],e.multiple?this.refactorShapeToArray(e.key,i):i}associationUnion(e,t=new Set){let i=[];for(let r of e.listTargets())i.push(this.entity(r,t));if(i.length)return i.length>1?i:i[0]}getRange(e){let t=e.readBinding("web"),i;e.schema&&(i=e.schema);let{multiple:r,type:s}=e;return r?this.createArrayShape(e,i,t):s===$d?this.createFileShape(e,t):this.createScalarShape(e,i,t)}setShapeSchema(e,t,i,r,s){if(i.defaultValue){let{type:o}=i.defaultValue,{value:a}=i.defaultValue;if(o==="function"){let n=this.valueGenerator.generate(a,e.type);if(n!==ds.noValue){let l=jt.scalar(n,o);t.defaultValue=l.toJSON()}}else{let n=jt.scalar(a,r);t.defaultValue=n.toJSON()}}Array.isArray(i.enum)&&(t.values=i.enum.map(o=>jt.scalar(o,r).toJSON())),Array.isArray(i.examples)&&(s?t.examples=this.createArrayExamples(i.examples,r):t.examples=this.createExamples(i.examples,r))}createArrayShape(e,t,i){let r=Xe.arrayShape(e.key),{type:s}=e;if(s===$d?r.items=this.createFileShape(e,i):r.items=this.createScalarShape(e,void 0,i),t){let o=r.items.dataType;this.setShapeSchema(e,r,t,o,e.multiple)}return r}createScalarShape(e,t,i){let r=Xe.scalarShape(e.key);return this.updateBaseProperties(e,r),this.setScalarCommonProperties(r,e,i),r.dataType||(r.dataType=qo(e.type,i)),t&&this.setShapeSchema(e,r,t,r.dataType,e.multiple),r}createExamples(e,t){let i=[];for(let r of e){let s={id:W(),customDomainProperties:[],strict:!0,types:[...es.IAmfExampleTypes],structuredValue:jt.scalar(r,t).toJSON()};i.push(s)}return i}createArrayExamples(e,t){let i={id:W(),customDomainProperties:[],strict:!0,types:[...es.IAmfExampleTypes]},r=new jt("array");for(let s of e){let o=jt.scalar(s,t);r.addMember(o)}return i.structuredValue=r.toJSON(),[i]}createFileShape(e,t){let i=Xe.fileShape(e.key);return this.updateBaseProperties(e,i),t&&(Array.isArray(t.fileTypes)&&(i.fileTypes=t.fileTypes),this.setScalarCommonProperties(i,e,t)),i}setScalarCommonProperties(e,t,i){i?.name&&(e.name=i.name),i?.xml&&(e.xmlSerialization=i.xml);let{schema:r,type:s}=t;if(r&&(r.pattern&&(e.pattern=r.pattern),typeof r.multipleOf=="number"&&(e.multipleOf=r.multipleOf),typeof r.minimum=="number"&&(s===Vc?e.minLength=r.minimum:e.minimum=r.minimum),typeof r.maximum=="number"&&(s===Vc?e.maxLength=r.maximum:e.maximum=r.maximum),typeof r.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum=r.exclusiveMinimum),typeof r.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum=r.exclusiveMaximum)),i?.format)switch(i.format){case"double":e.format=u.w3.xmlSchema.double;break;case"float":e.format=u.w3.xmlSchema.float;break;case"int32":e.format=u.w3.xmlSchema.integer;break;case"int64":e.format=u.w3.xmlSchema.integer;break}typeof t.readOnly=="boolean"&&(e.readOnly=t.readOnly),typeof t.writeOnly=="boolean"&&(e.writeOnly=t.writeOnly);let o=r?.examples&&r.examples.length>0,a=r?.defaultValue?.value!==void 0;if(t.required&&!t.readOnly&&!o&&!a){let n="";t.type==="number"?n=0:t.type==="boolean"&&(n=!1);let l=("dataType"in e?e.dataType:void 0)||qo(t.type,i);e.examples=this.createExamples([String(n)],l)}}updateBaseProperties(e,t){t.name=e.info.name,t.displayName=e.info.displayName,t.description=e.info.description,(e.kind===be||e.kind===$)&&(t.deprecated=e.deprecated)}createRecursiveShape(e){return Xe.recursiveShape(e.key,e.key)}refactorShapeToArray(e,t){let i=Xe.arrayShape(e);return i.items=t,i}};var ir=class extends b{static code="E_DOMAIN_SCHEMA";static status=400;static message="Invalid domain schema configuration.";static help="Ensure that the property and entity configurations do not violate schema constraints."};var ps=class extends b{static code="E_INVALID_TYPE";static status=422;static message="Invalid type.";static help="Make sure you are initializing the object with the correct data."};var ki=class c extends lt{kind;info;required;multiple;primary;unique;index;search;readOnly;immutable;writeOnly;deprecated;tags=[];semantics=[];type="string";jsonSchema;jsonIndex;schema;bindings=[];lineage;static createSchema(e={}){let{key:t=W(),multiple:i,required:r,type:s=ls.string,index:o,search:a,primary:n,unique:l,readOnly:d,writeOnly:p,immutable:m,tags:h,semantics:f,deprecated:k,schema:w,bindings:S,jsonSchema:E,jsonIndex:A,lineage:_}=e;if(d===!0&&m===!0){let L=e.info?.name||e.key||"property";throw new ir(`Property '${L}' cannot be both readOnly and immutable.`)}if(typeof s=="string"&&!Uc.includes(s))throw new ps(`Invalid data property type ${s}`);let O=he.fromJSON(e.info,{name:"new_property"}).toJSON(),I={kind:be,key:t,info:O,type:s};E&&(I.jsonSchema=structuredClone(E)),A&&(I.jsonIndex=structuredClone(A)),typeof i=="boolean"&&(I.multiple=i),typeof r=="boolean"&&(I.required=r),typeof o=="boolean"&&(I.index=o),typeof a=="boolean"&&(I.search=a),typeof n=="boolean"&&(I.primary=n),typeof l=="boolean"&&(I.unique=l);let j=d;return n===!0&&d===void 0&&m===void 0&&(j=!0),typeof j=="boolean"&&(I.readOnly=j),typeof m=="boolean"&&(I.immutable=m),typeof p=="boolean"&&(I.writeOnly=p),typeof k=="boolean"&&(I.deprecated=k),Array.isArray(h)&&(I.tags=[...h]),Array.isArray(f)&&(I.semantics=[...f]),w&&(I.schema=structuredClone(w)),Array.isArray(S)?I.bindings=S.map(L=>structuredClone(L)):I.bindings=[],_&&(I.lineage=structuredClone(_)),I}parent;constructor(e,t,i={}){let r=c.createSchema(i);super(e,r.key),this.parent=t,this.kind=be,this.info=new he(r.info),this.type=r.type,typeof r.multiple=="boolean"&&(this.multiple=r.multiple),typeof r.required=="boolean"&&(this.required=r.required),typeof r.index=="boolean"&&(this.index=r.index),typeof r.search=="boolean"&&(this.search=r.search),typeof r.deprecated=="boolean"&&(this.deprecated=r.deprecated),typeof r.primary=="boolean"&&(this.primary=r.primary),typeof r.unique=="boolean"&&(this.unique=r.unique),typeof r.readOnly=="boolean"&&(this.readOnly=r.readOnly),typeof r.immutable=="boolean"&&(this.immutable=r.immutable),typeof r.writeOnly=="boolean"&&(this.writeOnly=r.writeOnly),Array.isArray(r.tags)?this.tags=[...r.tags]:this.tags=[],Array.isArray(r.semantics)?this.semantics=[...r.semantics]:this.semantics=[],r.schema&&(this.schema=structuredClone(r.schema)),r.jsonSchema&&(this.jsonSchema=structuredClone(r.jsonSchema)),r.jsonIndex&&(this.jsonIndex=structuredClone(r.jsonIndex)),Array.isArray(r.bindings)?this.bindings=r.bindings.map(s=>structuredClone(s)):this.bindings=[],r.lineage&&(this.lineage=structuredClone(r.lineage))}static validate(e,t={}){if(!e||typeof e!="object"&&e!==null)return!1;let i=e;return!(t.strict&&i.kind!==be)}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON(),type:this.type||ls.string};return typeof this.index=="boolean"&&(e.index=this.index),typeof this.search=="boolean"&&(e.search=this.search),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),typeof this.primary=="boolean"&&(e.primary=this.primary),typeof this.unique=="boolean"&&(e.unique=this.unique),typeof this.multiple=="boolean"&&(e.multiple=this.multiple),typeof this.required=="boolean"&&(e.required=this.required),typeof this.readOnly=="boolean"&&(e.readOnly=this.readOnly),typeof this.immutable=="boolean"&&(e.immutable=this.immutable),typeof this.writeOnly=="boolean"&&(e.writeOnly=this.writeOnly),Array.isArray(this.tags)&&this.tags.length&&(e.tags=[...this.tags]),Array.isArray(this.semantics)&&this.semantics.length&&(e.semantics=this.semantics.map(t=>structuredClone(t))),this.schema&&(e.schema=structuredClone(this.schema)),this.jsonSchema&&(e.jsonSchema=structuredClone(this.jsonSchema)),this.jsonIndex&&(e.jsonIndex=structuredClone(this.jsonIndex)),Array.isArray(this.bindings)&&this.bindings.length&&(e.bindings=this.bindings.map(t=>structuredClone(t))),this.lineage&&(e.lineage=structuredClone(this.lineage)),e}remove(){this.getParentInstance()?.removeProperty(this.key)}getParentInstance(){return this.root.graph.node(this.parent)}static isValidType(e){return typeof e!="string"?!1:Uc.includes(e)}static isValidAttribute(e){return typeof e!="string"?!1:Id.includes(e)}static isValidFormat(e){return e===void 0?!0:typeof e!="string"?!1:!!Rd.includes(e)}ensureSchema(){return this.schema||(this.schema={}),this.schema}getWebBinding(){let e=this.bindings.find(t=>t.type==="web");return e||(e={type:"web",schema:{}},this.bindings.push(e)),e.schema}readWebBinding(){return this.bindings.find(t=>t.type==="web")?.schema}getExposedName(){let e=this.readWebBinding()?.name||this.info.name;if(!e)throw new b(`Property ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}readBinding(e){return this.bindings.find(i=>i.type===e)?.schema||void 0}toApiShape(){return new bi().property(this)}toExample(e,t={}){let i=this.toApiShape();return i.range?new Ni(e,{renderExamples:t.renderExamples??!0,renderMocked:t.renderMocked??!0,renderOptional:t.renderOptional??!0,selectedUnions:t.selectedUnions}).generate(i):void 0}getDefaultValue(){return Fc(this)}addSemantic(e){this.root.ensureWritable();let t=at[e.id];if(!Ao(t))throw new ps(`Invalid semantic type: ${e.id}. Expected a property semantic.`);let i=this.semantics.findIndex(r=>r.id===e.id);i>=0?this.semantics[i]=e:this.semantics.push(e)}removeSemantic(e){this.root.ensureWritable();let t=this.semantics.findIndex(i=>i.id===e);t>=0&&this.semantics.splice(t,1)}hasSemantic(e){return this.semantics.some(t=>t.id===e)}getSemantic(e){return this.semantics.find(t=>t.id===e)}duplicate(){let e=this.getParentInstance();if(!e)throw new ir(`Cannot duplicate property ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(l=>l.key===this.key);if(t===-1)throw new ir(`Cannot duplicate property ${this.key} as it does not exist on the parent entity fields list.`);let i=this.info.name||"field",r=e.generateUniqueName(i),s=this.toJSON();delete s.key,delete s.primary,delete s.lineage,s.info?s.info.name=r:s.info={name:r};let o=e.addProperty(s),a=e.fields.length-1,n=e.fields[a];return e.fields.splice(a,1),e.fields.splice(t+1,0,n),o}setLineage(e,t){this.lineage={id:t,key:e.key,kind:e.kind},e.namespace!==this.root.key&&(this.lineage.domain=e.namespace)}};function Fc(c,e){let t,i;if(typeof c=="string"?(t=c,i=e):(t=c.type,i=c.schema?.defaultValue),!i||i.value===void 0||i.type==="function")return;let r=i.value;if(r===null)return null;switch(t){case"number":{if(typeof r=="number")return r;if(typeof r=="string"){let s=r.trim();if(s!==""){let o=Number(s);if(!Number.isNaN(o))return o}}return r}case"boolean":{if(typeof r=="boolean")return r;if(typeof r=="string"){let s=r.trim().toLowerCase();if(s==="true")return!0;if(s==="false")return!1}return r}case"json":{if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r}default:return typeof r=="string"?r:String(r)}}var vi=class extends b{static code="E_REMOVE_PROPERTY";static status=500;static message="Error removing a data property.";static help="Make sure the property exists and can be removed."};function Ve(c,e){if(!c.hasNode(e))return;let t=c.node(e);if(t){if(t.kind===se){c.removeNode(e);return}for(let i of c.children(e))Ve(c,i);for(let i of c.outEdges(e)){let r=c.edge(i);r&&(r.type==="association"||r.type==="property")&&Ve(c,i.w)}c.removeNode(e)}}var qc=[],Kc=[],Od={},us={},ms={};function Nd(c){return typeof c=="string"?new RegExp("^"+c+"$","i"):c}function Ko(c,e){return c===e?e:c===c.toLowerCase()?e.toLowerCase():c===c.toUpperCase()?e.toUpperCase():c[0]===c[0].toUpperCase()?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():e.toLowerCase()}function Dm(c,e){return c.replace(/\$(\d{1,2})/g,function(t,i){return e[i]||""})}function Lm(c,e){return c.replace(e[0],function(t,i){let r=Dm(e[1],arguments);return Ko(t===""?c[i-1]:t,r)})}function Td(c,e,t){if(!c.length||Object.hasOwn(Od,c))return e;let i=t.length;for(;i--;){let r=t[i];if(r[0].test(e))return Lm(e,r)}return e}function jd(c,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?Ko(i,r):Object.prototype.hasOwnProperty.call(c,r)?Ko(i,c[r]):Td(r,i,t)}}function Cd(c,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?!0:Object.prototype.hasOwnProperty.call(c,r)?!1:Td(r,r,t)===r}}var ze=function(c,e,t){let i=e===1?ze.singular(c):ze.plural(c);return(t?e+" ":"")+i};ze.plural=jd(ms,us,qc);ze.isPlural=Cd(ms,us,qc);ze.singular=jd(us,ms,Kc);ze.isSingular=Cd(us,ms,Kc);ze.addPluralRule=function(c,e){qc.push([Nd(c),e])};ze.addSingularRule=function(c,e){Kc.push([Nd(c),e])};ze.addUncountableRule=function(c){if(typeof c=="string"){Od[c.toLowerCase()]=!0;return}ze.addPluralRule(c,"$0"),ze.addSingularRule(c,"$0")};ze.addIrregularRule=function(c,e){e=e.toLowerCase(),c=c.toLowerCase(),ms[c]=e,us[e]=c};[["I","we"],["me","us"],["he","they"],["she","they"],["them","them"],["myself","ourselves"],["yourself","yourselves"],["itself","themselves"],["herself","themselves"],["himself","themselves"],["themself","themselves"],["is","are"],["was","were"],["has","have"],["this","these"],["that","those"],["my","our"],["its","their"],["his","their"],["her","their"],["echo","echoes"],["dingo","dingoes"],["volcano","volcanoes"],["tornado","tornadoes"],["torpedo","torpedoes"],["genus","genera"],["viscus","viscera"],["stigma","stigmata"],["stoma","stomata"],["dogma","dogmata"],["lemma","lemmata"],["schema","schemata"],["anathema","anathemata"],["ox","oxen"],["axe","axes"],["die","dice"],["yes","yeses"],["foot","feet"],["eave","eaves"],["goose","geese"],["tooth","teeth"],["quiz","quizzes"],["human","humans"],["proof","proofs"],["carve","carves"],["valve","valves"],["looey","looies"],["thief","thieves"],["groove","grooves"],["pickaxe","pickaxes"],["passerby","passersby"],["canvas","canvases"]].forEach(function(c){ze.addIrregularRule(c[0],c[1])});[[/s?$/i,"s"],[/[^\u0000-\u007F]$/i,"$0"],[/([^aeiou]ese)$/i,"$1"],[/(ax|test)is$/i,"$1es"],[/(alias|[^aou]us|t[lm]as|gas|ris)$/i,"$1es"],[/(e[mn]u)s?$/i,"$1s"],[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i,"$1"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1i"],[/(alumn|alg|vertebr)(?:a|ae)$/i,"$1ae"],[/(seraph|cherub)(?:im)?$/i,"$1im"],[/(her|at|gr)o$/i,"$1oes"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,"$1a"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i,"$1a"],[/sis$/i,"ses"],[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i,"$1$2ves"],[/([^aeiouy]|qu)y$/i,"$1ies"],[/([^ch][ieo][ln])ey$/i,"$1ies"],[/(x|ch|ss|sh|zz)$/i,"$1es"],[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i,"$1ices"],[/\b((?:tit)?m|l)(?:ice|ouse)$/i,"$1ice"],[/(pe)(?:rson|ople)$/i,"$1ople"],[/(child)(?:ren)?$/i,"$1ren"],[/eaux$/i,"$0"],[/m[ae]n$/i,"men"],["thou","you"]].forEach(function(c){ze.addPluralRule(c[0],c[1])});[[/s$/i,""],[/(ss)$/i,"$1"],[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i,"$1fe"],[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i,"$1f"],[/ies$/i,"y"],[/(dg|ss|ois|lk|ok|wn|mb|th|ch|ec|oal|is|ck|ix|sser|ts|wb)ies$/i,"$1ie"],[/\b(l|(?:neck|cross|hog|aun)?t|coll|faer|food|gen|goon|group|hipp|junk|vegg|(?:pork)?p|charl|calor|cut)ies$/i,"$1ie"],[/\b(mon|smil)ies$/i,"$1ey"],[/\b((?:tit)?m|l)ice$/i,"$1ouse"],[/(seraph|cherub)im$/i,"$1"],[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i,"$1"],[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i,"$1sis"],[/(movie|twelve|abuse|e[mn]u)s$/i,"$1"],[/(test)(?:is|es)$/i,"$1is"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1us"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i,"$1um"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i,"$1on"],[/(alumn|alg|vertebr)ae$/i,"$1a"],[/(cod|mur|sil|vert|ind)ices$/i,"$1ex"],[/(matr|append)ices$/i,"$1ix"],[/(pe)(rson|ople)$/i,"$1rson"],[/(child)ren$/i,"$1"],[/(eau)x?$/i,"$1"],[/men$/i,"man"]].forEach(function(c){ze.addSingularRule(c[0],c[1])});["adulthood","advice","agenda","aid","aircraft","alcohol","ammo","analytics","anime","athletics","audio","bison","blood","bream","buffalo","butter","carp","cash","chassis","chess","clothing","cod","commerce","cooperation","corps","debris","diabetes","digestion","elk","energy","equipment","excretion","expertise","firmware","flounder","fun","gallows","garbage","graffiti","hardware","headquarters","health","herpes","highjinks","homework","housework","information","jeans","justice","kudos","labour","literature","machinery","mackerel","mail","media","mews","moose","music","mud","manga","news","only","personnel","pike","plankton","pliers","police","pollution","premises","rain","research","rice","salmon","scissors","series","sewage","shambles","shrimp","software","staff","swine","tennis","traffic","transportation","trout","tuna","wealth","welfare","whiting","wildebeest","wildlife","you",/pok[eé]mon$/i,/[^aeiou]ese$/i,/deer$/i,/fish$/i,/measles$/i,/o[iu]s$/i,/pox$/i,/sheep$/i].forEach(ze.addUncountableRule);var Et=ze;function Mm(c,e,t){let i=c.getExposedName(),r=i.charAt(0).toLowerCase()+i.slice(1),s=Et(r),o=new Set(Array.from(e.listFields()).map(n=>n.info.name).filter(Boolean)),a=o.has(s)?t.getExposedName():s;return o.has(a)&&(a=e.generateUniqueName(a)),a}var rr=class c extends lt{kind;info;link;bindings=[];_required;_multiple;_semantics=[];_schema;_onDelete;_readOnly;get required(){return this.link?this.getLinkedAssociation()?.required:this._required}set required(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set required on linked association "${this.key}". Required status is owned by the link target "${this.link?.key}".`);this._required=e}get multiple(){return this.link?this.getLinkedAssociation()?.multiple:this._multiple}set multiple(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set multiple on linked association "${this.key}". Multiplicity is owned by the link target "${this.link?.key}".`);this._multiple=e}get schema(){return this.link?this.getLinkedAssociation()?.schema:this._schema}set schema(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set schema on linked association "${this.key}". Schema is owned by the link target "${this.link?.key}".`);this._schema=e}parent;targets;get semantics(){if(this.link){let e=this.getLinkedAssociation();return Object.freeze(e?[...e.semantics]:[])}return this._semantics}set semantics(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set semantics on linked association "${this.key}". Semantics are owned by the link target "${this.link?.key}".`);this._semantics=e}get onDelete(){return this.link?this.getLinkedAssociation()?.onDelete:this._onDelete}set onDelete(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set onDelete on linked association "${this.key}". onDelete rule is owned by the link target "${this.link?.key}".`);this._onDelete=e}get readOnly(){return this.link?this.getLinkedAssociation()?.readOnly:this._readOnly}set readOnly(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set readOnly on linked association "${this.key}". readOnly flag is owned by the link target "${this.link?.key}".`);this._readOnly=e}fields;static createSchema(e={}){let{key:t=W(),semantics:i=[]}=e,r=he.fromJSON(e.info,{name:"new_association"}).toJSON(),s={kind:se,key:t,info:r};return e.link&&(s.link=structuredClone(e.link)),Array.isArray(i)&&(s.semantics=[...i]),e.onDelete&&(s.onDelete=e.onDelete),typeof e.readOnly=="boolean"&&(s.readOnly=e.readOnly),e.schema&&(s.schema=structuredClone(e.schema)),typeof e.multiple=="boolean"&&(s.multiple=e.multiple),typeof e.required=="boolean"&&(s.required=e.required),Array.isArray(e.bindings)&&(s.bindings=e.bindings.map(o=>structuredClone(o))),Array.isArray(e.targets)&&(s.targets=e.targets.map(o=>({...o}))),Array.isArray(e.fields)&&(s.fields=[...e.fields]),s}constructor(e,t,i){let r=c.createSchema(i);super(e,r.key),this.parent=t,this.kind=se,this.info=new he(r.info),r.link&&(this.link=structuredClone(r.link)),r.schema&&(this._schema=structuredClone(r.schema)),typeof r.multiple=="boolean"&&(this._multiple=r.multiple),typeof r.required=="boolean"&&(this._required=r.required),Array.isArray(r.bindings)?this.bindings=r.bindings.map(s=>structuredClone(s)):this.bindings=[],Array.isArray(r.targets)?this.targets=r.targets.map(s=>({...s})):this.targets=[],Array.isArray(r.semantics)?this._semantics=r.semantics.map(s=>structuredClone(s)):this._semantics=[],r.onDelete&&(this._onDelete=r.onDelete),Array.isArray(r.fields)?this.fields=[...r.fields]:this.fields=[],typeof r.readOnly=="boolean"&&(this._readOnly=r.readOnly)}isLinked(){return!!this.link}getLinkedAssociation(e=new Set){if(!this.link)return;if(e.has(this.key))throw new Error(`Circular association link detected involving association key "${this.key}".`);e.add(this.key);let t=!this.link.domain||this.link.domain===this.root.key?this.root:this.root.dependencies.get(this.link.domain);if(!t)return;let i=t.graph.node(this.link.key);if(!i||i.kind!==se)return;let r=i;return r.isLinked()?r.getLinkedAssociation(e):r}addProperty(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot add property to linked association "${this.key}". Properties are owned by the link target "${this.link?.key}".`);if(e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a property ${e.key}, but it already exists`);let t=new ki(this.root,this.key,e);return this.root.graph.setNode(t.key,t),this.root.graph.setEdge(this.key,t.key,{type:"property"}),this.fields.push({type:"property",key:t.key}),t}get properties(){return this.listProperties()}*listProperties(){if(this.link){let e=this.getLinkedAssociation();e&&(yield*e.listProperties());return}for(let{key:e}of this.fields){let t=this.root.graph.node(e);!t||t.kind!==be||(yield t)}}removeProperty(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot remove property from linked association "${this.key}". Properties are owned by the link target "${this.link?.key}".`);let t=this.fields.findIndex(r=>r.key===e&&r.type==="property");if(!this.root.graph.hasNode(e))throw new vi(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new vi(`Trying to remove the ${e} property, but it doesn't belong to this association`);Ve(this.root.graph,e),t!==-1&&this.fields.splice(t,1)}generateUniqueName(e){let t=new Set;for(let s of this.listProperties())s.info.name&&t.add(s.info.name);let i=2,r=`${e}_copy`;for(;t.has(r);)r=`${e}_copy_${i}`,i++;return r}toJSON(){if(this.link){let t={kind:this.kind,key:this.key,info:this.info.toJSON(),link:structuredClone(this.link)};return Array.isArray(this.targets)&&this.targets.length&&(t.targets=this.targets.map(i=>({...i}))),Array.isArray(this.bindings)&&this.bindings.length&&(t.bindings=this.bindings.map(i=>structuredClone(i))),t}let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return this.schema&&(e.schema=structuredClone(this.schema)),typeof this.multiple=="boolean"&&(e.multiple=this.multiple),typeof this.required=="boolean"&&(e.required=this.required),Array.isArray(this.bindings)&&this.bindings.length&&(e.bindings=this.bindings.map(t=>structuredClone(t))),Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),Array.isArray(this.targets)&&this.targets.length&&(e.targets=this.targets.map(t=>({...t}))),Array.isArray(this.semantics)&&this.semantics.length&&(e.semantics=this.semantics.map(t=>structuredClone(t))),this.onDelete&&(e.onDelete=this.onDelete),typeof this.readOnly=="boolean"&&this.readOnly&&(e.readOnly=this.readOnly),e}getParentInstance(){return this.root.graph.node(this.parent)}remove(){this.getParentInstance()?.removeAssociation(this.key)}ensureSchema(){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot ensure schema on linked association "${this.key}". Schema is owned by the link target "${this.link?.key}".`);return this.schema||(this.schema={}),this.schema}static isValidAttribute(e){return typeof e!="string"?!1:Pd.includes(e)}getWebBinding(){this.root.ensureWritable();let e=this.bindings.find(t=>t.type==="web");return e||(e={type:"web",schema:{}},this.bindings.push(e)),e.schema}readWebBinding(){return this.bindings?.find(t=>t.type==="web")?.schema}getExposedName(){let e=this.readWebBinding()?.name||this.info.name;if(!e)throw new b(`Association ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}readBinding(e){return this.bindings.find(i=>i.type===e)?.schema||void 0}addTarget(e,t){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot add targets to linked association "${this.key}". Targets are determined by the reciprocal relationship with "${this.link?.key}".`);let i;if(typeof e=="string"?i=e:(i=e.key,e.domain.key!==this.root.key&&(t=e.domain.key)),t&&t===this.root.key&&(t=void 0),this.targets.some(a=>a.key===i&&a.domain===t)){let a=`Target ${i} already exists.`;throw new Error(a)}if(t&&!this.root.dependencies.has(t))throw new Error(`Foreign namespace "${t}" does not exist.`);let r={key:i};t&&(r.domain=t),this.targets.push(r);let s=t?`${t}:${i}`:i,o={type:"association"};t&&(o.domain=t,o.foreign=!0),this.root.graph.setEdge(this.key,s,o),this.synchronizePeerReciprocalAssociations()}removeTarget(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot remove targets from linked association "${this.key}". Targets are determined by the reciprocal relationship with "${this.link?.key}".`);let t;typeof e=="string"?t=e:t=e.key;let i=this.targets.findIndex(r=>r.key===t);i>=0&&this.targets.splice(i,1),this.root.graph.removeEdge(this.key,t),this.synchronizePeerReciprocalAssociations()}*listTargets(){for(let e of this.targets){let{key:t,domain:i}=e,r=i?`${i}:${t}`:t,s=this.root.graph.node(r);s&&(yield s)}}toApiShape(){return new bi().associationProperty(this)}checkPreconditions(e){let t=at[e];if(!(!t||!Xi(t)||!t.preconditions||t.preconditions.length===0)){for(let i of t.preconditions)if(i.kind==="associationMultiple"){if(this.multiple!==i.multiple)throw new b(i.unmetMessage||`Semantic ${e} requires association multiple to be ${i.multiple}.`,{status:400})}else if(i.kind==="entityPairs"){let r=this.getParentInstance(),s=Array.from(this.listTargets());if(!r)throw new b(i.unmetMessage||`Parent entity is required to evaluate entity pairing preconditions for semantic ${e}.`,{status:400});if(!i.entityPairs.some(a=>(Array.isArray(a.parent)?a.parent.some(d=>r.hasSemantic(d)):r.hasSemantic(a.parent))?s.some(d=>Array.isArray(a.target)?a.target.some(p=>d.hasSemantic(p)):d.hasSemantic(a.target)):!1))throw new b(i.unmetMessage||`Association entity pairing precondition check failed for semantic ${e}.`,{status:400})}}}getReciprocalAssociations(e){let t=[],i=this.getParentInstance()?.key;if(!i)return t;let r=this.root.getIncomingAssociations(i);for(let s of r)if(s.key!==this.key){if(s.link&&s.link.key===this.key&&(!e||s.hasSemantic(e))){t.push(s);continue}for(let o of s.semantics)if(o.link&&o.link.key===this.key&&(!e||o.id===e)){t.push(s);break}}return t}toggleOptionalSemanticProperty(e,t,i){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot toggle edge properties on linked reciprocal association "${this.key}". Edge properties belong to the source of truth association.`);let r=at[e];if(!r||!Xi(r))throw new Error(`Invalid semantic type: ${e}. Expected an association semantic.`);if(this.getSemantic(e)?.link)throw new Error(`Cannot toggle edge properties on linked reciprocal semantic ${e}. Edge properties belong to the source of truth association.`);let o=r.properties?.find(l=>l.value.info?.name===t);if(!o)throw new Error(`Property "${t}" is not defined in semantic blueprint ${e}.`);let n=Array.from(this.listProperties()).find(l=>l.info.name===t||l.lineage?.id===e&&l.info.name===t);if(i){if(n)return n;let l={...o.value,lineage:{key:this.key,kind:se,domain:this.root.key,id:e}};return this.addProperty(l)}else{n&&n.remove();return}}addSemantic(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot add semantics to linked association "${this.key}". Semantics are owned by the link target "${this.link?.key}".`);let t=at[e.id];if(!Xi(t))throw new Error(`Invalid semantic type: ${e.id}. Expected an association semantic.`);this.checkPreconditions(e.id);let i=this.semantics.findIndex(r=>r.id===e.id);i>=0?this.semantics[i]=e:this.semantics.push(e),e.link||t.properties?.forEach(r=>{if(!r.meta.required)return;let s=r.value.info?.name;if(!Array.from(this.listProperties()).find(a=>a.info.name===s||a.lineage?.id===e.id&&a.info.name===s)){let a={...r.value,lineage:{key:this.key,kind:se,domain:this.root.key,id:e.id}};this.addProperty(a)}}),this.synchronizePeerReciprocalAssociations()}removeSemantic(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot remove semantics from linked association "${this.key}". Semantics are owned by the link target "${this.link?.key}".`);let t=this.getReciprocalAssociations(e),i=this.semantics.findIndex(s=>s.id===e);i>=0&&this.semantics.splice(i,1);let r=Array.from(this.listProperties()).filter(s=>s.lineage?.id===e);for(let s of r)s.remove();for(let s of t)s.isLinked()?s.remove():(s.removeSemantic(e),s.semantics.length===0&&s.remove());e===g.PeerRelation&&this.synchronizePeerReciprocalAssociations()}hasSemantic(e){return this.link?this.getLinkedAssociation()?.hasSemantic(e)??!1:this._semantics.some(t=>t.id===e)}getSemantic(e){return this.link?this.getLinkedAssociation()?.getSemantic(e):this._semantics.find(t=>t.id===e)}isManyToMany(){return this.link?this.getLinkedAssociation()?.isManyToMany()??!1:this.multiple?this.semantics.some(e=>{let t=at[e.id];return!!t&&Xi(t)&&t.isManyToMany===!0}):!1}isManyToManyLinkReciprocal(){return this.multiple?this.link?this.isManyToMany():this.semantics.some(e=>{if(!e.link)return!1;let t=at[e.id];return!!t&&Xi(t)&&t.isManyToMany===!0}):!1}isLinkedReciprocal(e){return this.link?!e||this.hasSemantic(e):this.semantics.some(t=>t.link?!e||t.id===e:!1)}synchronizePeerReciprocalAssociations(){if(this.root.readOnly||this.isLinked())return;let e=this.getSemantic(g.PeerRelation);if(!e)return;if(!(e.config?.symmetry==="mutual")){let a=this.getReciprocalAssociations(g.PeerRelation);for(let n of a)n.remove();return}let i=this.getParentInstance();if(!i)return;let r=Array.from(this.listTargets()),s=new Set(r.map(a=>a.key)),o=this.getReciprocalAssociations(g.PeerRelation);for(let a of o){let n=a.getParentInstance();(!n||!s.has(n.key))&&a.remove()}for(let a of r){if(a.domain.key!==this.root.key)throw new b(`Cannot apply symmetry "mutual" on association "${this.getExposedName()}": target entity "${a.info.getLabel()}" belongs to foreign domain "${a.domain.key}". Reciprocal associations cannot be synthesized on read-only foreign domains. Use symmetry "directed" or target only local entities.`,{status:400});if(Array.from(a.listAssociations()).some(p=>p.link&&p.link.key===this.key||p.semantics.some(m=>m.id===g.PeerRelation&&m.link?.key===this.key)))continue;let l=Mm(i,a,this),d=i.info.displayName?Et(i.info.displayName):l;a.addAssociation({info:{name:l,displayName:d},targets:[{key:i.key}],link:{kind:se,key:this.key}})}}duplicate(){if(this.isLinked())throw new Error(`Cannot duplicate linked association "${this.key}". Duplicate the primary association instead.`);let e=this.getParentInstance();if(!e)throw new Error(`Cannot duplicate association ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(l=>l.key===this.key);if(t===-1)throw new Error(`Cannot duplicate association ${this.key} as it does not exist on the parent entity fields list.`);let i=this.info.name||"field",r=e.generateUniqueName(i),s=this.toJSON();delete s.key,delete s.targets,delete s.fields,s.info?s.info.name=r:s.info={name:r};let o=e.addAssociation(s);for(let l of this.listProperties()){let d=l.toJSON();delete d.key,o.addProperty(d)}for(let l of this.targets)o.addTarget(l.key,l.domain);let a=e.fields.length-1,n=e.fields[a];return e.fields.splice(a,1),e.fields.splice(t+1,0,n),o}};var ji=class extends Error{messages;status=422;code="E_VALIDATION_ERROR";constructor(e,t){let i=t?.message||"Validation failure";super(i,t),this.messages=e;let r=this.constructor;"captureStackTrace"in Error&&Error.captureStackTrace(this,r)}get[Symbol.toStringTag](){return this.constructor.name}toString(){return`${this.name} [${this.code}]: ${this.message}`}};var sr=class c extends lt{kind;#e;#t;#i;#r;info;tags;semantics=[];fields;deprecated;static createSchema(e={}){let{key:t=W(),tags:i,semantics:r,fields:s,deprecated:o}=e,a=he.fromJSON(e.info,{name:"new_entity"}).toJSON(),n={kind:$,key:t,info:a};return Array.isArray(i)&&(n.tags=[...i]),Array.isArray(r)&&(n.semantics=[...r]),Array.isArray(s)&&(n.fields=[...s]),typeof o=="boolean"&&(n.deprecated=o),n}constructor(e,t){let i=c.createSchema(t);super(e,i.key),this.kind=$,this.info=new he(i.info),Array.isArray(i.tags)?this.tags=[...i.tags]:this.tags=[],Array.isArray(i.semantics)?this.semantics=i.semantics.map(r=>structuredClone(r)):this.semantics=[],Array.isArray(i.fields)?this.fields=[...i.fields]:this.fields=[],typeof i.deprecated=="boolean"&&(this.deprecated=i.deprecated)}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),Array.isArray(this.semantics)&&this.semantics.length&&(e.semantics=this.semantics.map(t=>structuredClone(t))),Array.isArray(this.tags)&&this.tags.length&&(e.tags=[...this.tags]),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),e}getParentInstance(){let e=this.root.graph.parent(this.key);if(e)return this.root.graph.node(e)}getExposedName(){let e=this.info.name;if(!e)throw new b(`Entity ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}getDatabaseTableName(){return Il(this.getExposedName(),this.namespace)}addProperty(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a property ${e.key}, but it already exists`);let t=new ki(this.root,this.key,e);return this.root.graph.setNode(t.key,t),this.root.graph.setEdge(this.key,t.key,{type:"property"}),this.fields.push({type:"property",key:t.key}),t}removeProperty(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new vi(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new vi(`Trying to remove the ${e} property, but it doesn't belong to this entity`);Ve(this.root.graph,e),this.removeField(e)}get properties(){return this.listProperties()}*listProperties(){for(let{key:e,type:t}of this.fields){if(t!=="property")continue;let i=this.root.graph.node(e);!i||i.kind!==be||(yield i)}}withInheritedProperties(){if(this.root.readOnly&&this.#e)return this.#e.values();let e=new Map,t=this.listAllParents("up");for(let i of t)for(let r of i.properties)r.info.name&&e.set(r.info.name,r);for(let i of this.properties)i.info.name&&e.set(i.info.name,i);return this.root.readOnly&&(this.#e=Array.from(e.values())),e.values()}hasProperties(){return this.fields.some(e=>e.type==="property")}get parents(){return this.listParents()}*listParents(){for(let e of this.root.graph.outEdges(this.key)){let t=this.root.graph.edge(e);if(!t||t.type!=="parent")continue;let i=this.root.graph.node(e.w);i&&(yield i)}}listAllParents(e="up"){if(this.root.readOnly&&this.#t?.[e])return this.#t[e];let t=new Set,i=[],r=[...this.listParents()],s=0;for(;s<r.length;){let o=r[s++];t.has(o.key)||(t.add(o.key),i.push(o),r.push(...o.listParents()))}return e==="down"&&i.reverse(),this.root.readOnly&&(this.#t||(this.#t={}),this.#t[e]=i),i}addParent(e,t){this.root.ensureWritable();let i=this.domain.buildReferenceKey(e,t);if(i===this.key){let s="Entity cannot be a parent of itself";throw new ji([{field:"parents",message:s,rule:"circular"}],{message:s})}let{graph:r}=this.root;if(!r.hasNode(i)){let s=`Entity with key "${e}" not found`;throw t&&(s+=` in domain "${t}"`),new ji([{field:"parents",message:s,rule:"required"}],{message:s})}if(this.hasCircularParent(i)){let s=`Circular inheritance detected. Cannot add ${e} as a parent`;throw new ji([{field:"parents",message:s,rule:"circular"}],{message:s})}if(r.outEdges(this.key,i).next().value){let s=`Parent ${e} already exists`;throw new ji([{field:"parents",message:s,rule:"unique"}],{message:s})}return t?r.setEdge(this.key,i,{type:"parent",domain:t,foreign:!0}):r.setEdge(this.key,i,{type:"parent"}),this}removeParent(e,t){this.root.ensureWritable();let{graph:i}=this.root,r=this.domain.buildReferenceKey(e,t);if(!i.hasEdge(this.key,r)){let o=`Trying to remove a parent ${e} from ${this.key}, but it doesn't exist`;throw t&&(o=`Trying to remove a foreign parent ${e} from domain "${t}" from ${this.key}, but it doesn't exist`),new Error(o)}let s=i.edge(this.key,r);if(!s||s.type!=="parent"){let o=`Edge between ${this.key} and ${e} exists but is not a parent relationship`;throw t&&(o=`Edge between ${this.key} and ${e} in domain "${t}" exists but is not a parent relationship`),new Error(o)}return i.removeEdge(this.key,r),this}hasParents(){for(let e of this.root.graph.outEdges(this.key))if(this.root.graph.edge(e)?.type==="parent")return!0;return!1}hasCircularParent(e){let{graph:t}=this.root;for(let r of t.outEdges(e,this.key))if(t.edge(r)?.type==="parent")return!0;let i=t.node(e);for(;i;){if(i.key===this.key)return!0;let r=[...i.listParents()];if(r.length===0)break;i=r[0]}return!1}breadcrumbs(){let e=[];e.push({key:this.key,name:this.info.getLabel("Unnamed entity"),kind:$});let t=this.getParentInstance();if(t){e.push({key:t.key,kind:t.kind,name:t.info.getLabel("Unnamed model")});let i=t.getParentInstance();for(;i&&i!==this.root;)e.push({key:i.key,kind:i.kind,name:i.info.getLabel("Unnamed namespace")}),i=i.getParentInstance()}return e.push({key:this.root.key,name:this.root.info.getLabel("Unnamed data domain"),kind:this.root.kind}),e.reverse()}addAssociation(e={}){this.root.ensureWritable();let{graph:t}=this.root,i={...e},r=i.targets;delete i.targets;let s=Array.isArray(r)&&r.length;if(s)for(let a of r){if(!a.key)throw new Error("Missing key for target");if(a.domain&&a.domain!==this.root.key){let n=`${a.domain}:${a.key}`;if(!t.hasNode(n))throw new Error(`Foreign entity ${n} not found`)}else if(!t.hasNode(a.key))throw new Error(`Target entity ${a.key} not found`)}let o=new rr(this.root,this.key,i);if(t.setNode(o.key,o),t.setEdge(this.key,o.key,{type:"association"}),s)if(o.isLinked())for(let a of r){let n=a.domain?`${a.domain}:${a.key}`:a.key,l={key:a.key};a.domain&&(l.domain=a.domain),o.targets.push(l);let d={type:"association"};a.domain&&(d.domain=a.domain,d.foreign=!0),t.setEdge(o.key,n,d)}else for(let a of r)o.addTarget(a.key,a.domain);return this.fields.push({type:"association",key:o.key}),o.synchronizePeerReciprocalAssociations(),o}addLinkedAssociation(e,t){let i=e.getParentInstance();if(!i)throw new Error(`Cannot link to association "${e.key}" because it has no parent entity.`);let r=i.domain.key!==this.root.key?i.domain.key:void 0,s={key:i.key};r&&(s.domain=r);let o={kind:se,key:e.key};return r&&(o.domain=r),this.addAssociation({info:t,targets:[s],link:o})}removeAssociation(e){if(this.root.ensureWritable(),!this.root.graph.hasEdge(this.key,e))throw new Error(`Unable to find a connection between this entity and the ${e} association`);let t=this.root.graph.edge(this.key,e);if(!t||t.type!=="association")throw new Error(`Association ${e} does not exist`);let i=this.root.graph.node(e);if(i){let r=i.getReciprocalAssociations();for(let s of r)s.remove()}Ve(this.root.graph,e),this.removeField(e)}get associations(){return this.listAssociations()}*listAssociations(){for(let{key:e,type:t}of this.fields){if(t!=="association")continue;let i=this.root.graph.node(e);!i||i.kind!==se||(yield i)}}hasAssociations(){return this.fields.some(e=>e.type==="association")}*listFields(){for(let{key:e}of this.fields){let t=this.root.graph.node(e);t&&(t.kind===se||t.kind===be)&&(yield t)}}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}toApiShape(){return new bi().entity(this)}toExample(e,t={}){let i=this.toApiShape();return new Ni(e,{renderExamples:t.renderExamples??!0,renderMocked:t.renderMocked??!0,renderOptional:t.renderOptional??!0,selectedUnions:t.selectedUnions}).generate(i)}isChildOf(e){if(this.key===e)return!1;let t=this.getParentInstance();return t?t.key===e?!0:t.isChildOf(e):!1}primaryKey(){for(let t of this.properties)if(t.primary)return t;let e;for(let t of this.listParents()){let i=t.primaryKey();i&&(e=i)}return e}addSemantic(e){this.root.ensureWritable();let t=at[e.id];if(!Sl(t))throw new Error(`Invalid semantic type: ${e.id}. Expected an entity semantic.`);let i=this.semantics.findIndex(r=>r.id===e.id);i>=0?this.semantics[i]=e:this.semantics.push(e),t.properties?.forEach(r=>{r.meta.required&&this.addProperty(r.value)})}removeSemantic(e){this.root.ensureWritable();let t=this.semantics.findIndex(i=>i.id===e);t>=0&&this.semantics.splice(t,1)}hasSemantic(e){return this.semantics.some(t=>t.id===e)}getSemantic(e){return this.semantics.find(t=>t.id===e)}withInheritedAssociations(){if(this.root.readOnly&&this.#i)return this.#i.values();let e=new Map,t=this.listAllParents("up");for(let i of t)for(let r of i.associations)r.info.name&&e.set(r.info.name,r);for(let i of this.associations)i.info.name&&e.set(i.info.name,i);return this.root.readOnly&&(this.#i=Array.from(e.values())),e.values()}listAllSemantics(){if(this.root.readOnly&&this.#r)return this.#r;let e=new Map,t=this.listAllParents("up");for(let r of t)for(let s of r.semantics)e.set(s.id,s);for(let r of this.semantics)e.set(r.id,r);let i=Array.from(e.values());return this.root.readOnly&&(this.#r=i),i}generateUniqueName(e){let t=new Set;for(let s of this.listFields())s.info.name&&t.add(s.info.name);let i=2,r=`${e}_copy`;for(;t.has(r);)r=`${e}_copy_${i}`,i++;return r}*getSystemFields(){let e=this.root.getIncomingAssociations(this.key);for(let t of e){if(!t.multiple||t.isManyToMany())continue;let i=t.getParentInstance();if(!i)continue;let r=i.primaryKey();if(!r)continue;yield{name:Pl({entityName:i.getExposedName(),assocName:t.getExposedName(),pkName:r.getExposedName()}),primaryKey:r,sourceEntity:i,association:t}}}};var or=class extends b{static code="E_REMOVE_ENTITY";static status=500;static message="Error removing a data entity.";static help="Make sure the entity exists and can be removed."};var Qe=class extends b{static code="E_ATTACH";static status=500;static message="Error attaching the object.";static help="Make sure you are attaching the right object."};var Ut=class extends b{static code="E_DETACH";static status=500;static message="Error detaching the object.";static help="Make sure you are detaching the right object."};var wi=class c extends lt{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=W(),fields:i,deprecated:r}=e,s=he.fromJSON(e.info,{name:"New model"}).toJSON(),o={kind:Oe,key:t,info:s};return Array.isArray(i)&&(o.fields=[...i]),typeof r=="boolean"&&(o.deprecated=r),o}constructor(e,t){let i=c.createSchema(t);super(e,i.key),this.kind=Oe,this.info=new he(i.info),Array.isArray(i.fields)?this.fields=[...i.fields]:this.fields=[],typeof i.deprecated=="boolean"?this.deprecated=i.deprecated:this.deprecated=void 0}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),e}getParentInstance(){let e=this.root.graph.parent(this.key);return e?this.root.graph.node(e):this.root}addEntity(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Entity with key ${e?.key} already exists`);let t=new sr(this.root,e);return this.root.graph.setNode(t.key,t),this.root.graph.setParent(t.key,this.key),this.fields.push({key:t.key,type:"entity"}),t}removeEntity(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new or(`Trying to remove the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==$)throw new or(`Trying to remove the ${e} entity, but it is not an entity`);if(t.getParentInstance()!==this)throw new or(`Trying to remove the ${e} entity, but it is not a child of this model`);Ve(this.root.graph,e),this.removeField(e)}attachEntity(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Qe(`Trying to attach the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==$)throw new Qe(`Trying to attach the ${e} entity, but it is not a entity`);if(t.domain.key!==this.root.key)throw new Qe(`Trying to attach the ${e} entity, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Qe(`Trying to attach the ${e} entity, but it is already a child of this model`);if(i.detachEntity(e),this.fields.some(s=>s.key===e)||this.fields.push({type:"entity",key:e}),this.root.graph.setParent(e,this.key),this.root.graph.parent(e)!==this.key)throw new Qe(`Trying to attach the ${e} entity, but it is not a child of this model`);return this}detachEntity(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e);if(t===-1)throw new Ut(`Trying to detach the ${e} entity, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==$)throw new Ut(`Trying to detach the ${e} entity, but it is not an entity`);if(i.getParentInstance()!==this)throw new Ut(`Trying to detach the ${e} entity, but it is not a child of this model`);return this.fields.splice(t,1),this.root.graph.setParent(e),this}*listEntities(){for(let{key:e,type:t}of this.fields){if(t!=="entity")continue;let i=this.root.graph.node(e);!i||i.kind!==$||(yield i)}}hasEntities(){return this.fields.some(e=>e.type==="entity")}breadcrumbs(){let e=[];e.push({key:this.key,name:this.info.getLabel("Unnamed model"),kind:Oe});let t=this.getParentInstance();for(;t&&t!==this.root;)e.push({key:t.key,kind:t.kind,name:t.info.getLabel("Unnamed namespace")}),t=t.getParentInstance();return e.push({key:this.root.key,name:this.root.info.getLabel("Unnamed data domain"),kind:this.root.kind}),e.reverse()}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}isChildOf(e){if(this.key===e)return!1;let t=this.getParentInstance();return t?t.key===e?!0:t===this.root?!1:t.isChildOf(e):!1}};var Ci=class extends b{static code="E_REMOVE_NAMESPACE";static status=500;static message="Error removing a domain namespace.";static help="Make sure the namespace exists and can be removed."};var hs=class extends b{static code="E_REMOVE_MODEL";static status=500;static message="Error removing a domain model.";static help="Make sure the model exists and can be removed."};var ar=class c extends lt{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=W(),fields:i,deprecated:r}=e,s=he.fromJSON(e.info,{name:"New namespace"}).toJSON(),o={kind:Le,key:t,info:s};return Array.isArray(i)&&(o.fields=[...i]),typeof r=="boolean"&&(o.deprecated=r),o}constructor(e,t){let i=c.createSchema(t);super(e,i.key),this.kind=Le,this.info=new he(i.info),Array.isArray(i.fields)?this.fields=[...i.fields]:this.fields=[],typeof i.deprecated=="boolean"?this.deprecated=i.deprecated:this.deprecated=void 0}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),e}addNamespace(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a namespace to ${this.key}, but it already exists`);let t=new c(this.root,e);return this.root.graph.setNode(t.key,t),this.root.graph.setParent(t.key,this.key),this.fields.push({type:"namespace",key:t.key}),t}removeNamespace(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Ci(`Trying to remove the ${e} namespace, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Le)throw new Ci(`Trying to remove the ${e} namespace, but it is not a namespace`);return Ve(this.root.graph,e),this.removeField(e),this}attachNamespace(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Error(`Trying to attach the ${e} namespace, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Le)throw new Error(`Trying to attach the ${e} namespace, but it is not a namespace`);if(t.domain.key!==this.root.key)throw new Error(`Trying to attach the ${e} namespace, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Qe(`Trying to attach the ${e} entity, but it is already a child of this model`);return this.root!==i&&i.detachNamespace(e),this.fields.push({type:"namespace",key:e}),this.root.graph.setParent(e,this.key),this}detachNamespace(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e);if(t===-1)throw new Ci(`Trying to detach the ${e} namespace, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Le)throw new Ci(`Trying to detach the ${e} namespace, but it is not a namespace`);return this.fields.splice(t,1),this.root.graph.setParent(e),this}*listNamespaces(){for(let{key:e,type:t}of this.fields){if(t!=="namespace")continue;let i=this.root.graph.node(e);!i||i.kind!==Le||(yield i)}}hasNamespaces(){return this.fields.some(e=>e.type==="namespace")}addModel(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a model to ${this.key}, but it already exists`);let t=new wi(this.root,e);return this.root.graph.setNode(t.key,t),this.root.graph.setParent(t.key,this.key),this.fields.push({type:"model",key:t.key}),t}removeModel(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new hs(`Trying to remove the ${e} model, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Oe)throw new hs(`Trying to remove the ${e} model, but it is not a model`);return Ve(this.root.graph,e),this.removeField(e),this}attachModel(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Qe(`Trying to attach the ${e} model, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Oe)throw new Qe(`Trying to attach the ${e} model, but it is not a model`);if(t.domain.key!==this.root.key)throw new Qe(`Trying to attach the ${e} model, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Qe(`Trying to attach the ${e} model, but it is already a child of this namespace`);return this.root!==i&&i.detachModel(e),this.fields.push({type:"model",key:e}),this.root.graph.setParent(e,this.key),this}detachModel(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e);if(t===-1)throw new Ut(`Trying to detach the ${e} model, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Oe)throw new Ut(`Trying to detach the ${e} model, but it is not a model`);if(i.getParentInstance()!==this)throw new Ut(`Trying to detach the ${e} model, but it is not a child of this namespace`);return this.fields.splice(t,1),this.root.graph.setParent(e),this}*listModels(){for(let{key:e,type:t}of this.fields){if(t!=="model")continue;let i=this.root.graph.node(e);!i||i.kind!==Oe||(yield i)}}hasModels(){return this.fields.some(e=>e.type==="model")}getParentInstance(){let e;for(let t of this.root.graph.parents(this.key)){e=t;break}return e?this.root.graph.node(e):this.root}*listFields(){for(let{key:e}of this.fields){let t=this.root.graph.node(e);t&&(t.kind===Le||t.kind===Oe)&&(yield t)}}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}isChildOf(e){if(this.key===e)return!1;let t=this.getParentInstance();return t?t.key===e?!0:t===this.root?!1:t.isChildOf(e):!1}};function nr(c,e,t){return c+""+e+""+(t||"\0")}function Bc(c,e,t){let i={v:c,w:e};return t&&(i.name=t),i}var Bo=class c{isDirectedValue;isMultigraphValue;isCompoundValue;graphLabelValue;nodesValue;#e;get parentValue(){if(!this.isCompoundValue)throw new Error("Cannot access parentValue in a non-compound graph");return this.#e||(this.#e=new Map),this.#e}#t;get childrenValue(){if(!this.isCompoundValue)throw new Error("Cannot access childrenValue in a non-compound graph");return this.#t||(this.#t=new Map),this.#t}inValue;predecessorsValue;outValue;successorsValue;edgeObjectsValue;edgeLabelsValue;nodeCountValue;edgeCountValue;constructor(e={}){this.isDirectedValue=typeof e.directed=="boolean"?e.directed:!0,this.isMultigraphValue=typeof e.multigraph=="boolean"?e.multigraph:!1,this.isCompoundValue=typeof e.compound=="boolean"?e.compound:!1,this.graphLabelValue=void 0,this.nodesValue=new Map,this.isCompoundValue&&this.childrenValue.set("\0",new Set),this.inValue=new Map,this.outValue=new Map,this.predecessorsValue=new Map,this.successorsValue=new Map,this.edgeObjectsValue=new Map,this.edgeLabelsValue=new Map,this.nodeCountValue=0,this.edgeCountValue=0,this.defaultNodeLabelFn=()=>{},this.defaultEdgeLabelFn=()=>{}}isDirected(){return this.isDirectedValue}isMultigraph(){return this.isMultigraphValue}isCompound(){return this.isCompoundValue}setGraph(e){return this.graphLabelValue=e,this}graph(){return this.graphLabelValue}defaultNodeLabelFn(e){}defaultEdgeLabelFn(e,t,i){}setDefaultNodeLabel(e){return typeof e=="function"?this.defaultNodeLabelFn=e:this.defaultNodeLabelFn=()=>e,this}nodeCount(){return this.nodeCountValue}nodes(){return this.nodesValue.keys()}*sources(){for(let e of this.nodes()){let t=this.inValue.get(e);(!t||t.size===0)&&(yield e)}}*sinks(){for(let e of this.nodes()){let t=this.outValue.get(e);(!t||t.size===0)&&(yield e)}}setNodes(e,t){if(typeof t>"u")for(let i of e)this.setNode(i);else for(let i of e)this.setNode(i,t);return this}setNode(e,t){return this.nodesValue.has(e)?(t&&this.nodesValue.set(e,t),this):(this.nodesValue.set(e,t||this.defaultNodeLabelFn(e)),this.isCompoundValue&&(this.parentValue.set(e,new Set(["\0"])),this.childrenValue.set(e,new Set),this.childrenValue.get("\0").add(e)),this.inValue.set(e,new Map),this.predecessorsValue.set(e,new Map),this.outValue.set(e,new Map),this.successorsValue.set(e,new Map),++this.nodeCountValue,this)}node(e){return this.nodesValue.get(e)}hasNode(e){return this.nodesValue.has(e)}removeNode(e){if(!this.hasNode(e))return this;if(this.nodesValue.delete(e),this.isCompoundValue){this.removeFromParentsChildList(e),this.parentValue.delete(e);for(let r of this.children(e))this.removeParent(r,e);this.childrenValue.delete(e)}let t=this.inValue.get(e);if(t){for(let r of t.keys()){let s=this.edgeObjectsValue.get(r);s&&this.removeEdge(s)}this.inValue.delete(e)}this.predecessorsValue.delete(e);let i=this.outValue.get(e);if(i){for(let r of i.keys()){let s=this.edgeObjectsValue.get(r);s&&this.removeEdge(s)}this.outValue.delete(e)}return this.successorsValue.delete(e),this.nodeCountValue-=1,this}setParent(e,t="\0"){if(!this.isCompoundValue)throw new Error("Cannot set parent in a non-compound graph");return t!=="\0"&&(this.checkParentCycle(e,t),this.nodesValue.has(t)||this.setNode(t)),this.nodesValue.has(e)||this.setNode(e),this.removeFromParentsChildList(e),this.parentValue.set(e,new Set),this.parentValue.get(e).add(t),this.childrenValue.has(t)||this.childrenValue.set(t,new Set),this.childrenValue.get(t).add(e),this}checkParentCycle(e,t){for(let i of this.parents(t)){if(i===e)throw new Error(`Setting ${t} as parent of ${e} would create a cycle`);this.checkParentCycle(e,i)}}addParent(e,t){if(!this.isCompoundValue)throw new Error("Cannot set parent in a non-compound graph");return this.checkParentCycle(e,t),this.nodesValue.has(t)||this.setNode(t),this.nodesValue.has(e)||this.setNode(e),this.parentValue.has(e)||this.parentValue.set(e,new Set),this.parentValue.get(e).add(t),this.childrenValue.has(t)||this.childrenValue.set(t,new Set),this.childrenValue.get(t).add(e),this}removeParent(e,t){if(!this.isCompoundValue)throw new Error("Cannot remove parent in a non-compound graph");return this.nodesValue.has(e)?(t?(this.childrenValue.get(t)?.delete(e),this.parentValue.get(e)?.delete(t)):(this.removeFromParentsChildList(e),this.parentValue.set(e,new Set),this.parentValue.get(e).add("\0"),this.childrenValue.get("\0").add(e)),this):this}removeFromParentsChildList(e){let t=this.parentValue.get(e);if(t)for(let i of t)this.childrenValue.get(i)?.delete(e)}*parents(e){if(this.isCompoundValue){let t=this.parentValue.get(e);if(t)for(let i of t)i!=="\0"&&(yield i)}}hasParents(e){for(let t of this.parents(e))return!0;return!1}hasParent(e,t){if(this.isCompoundValue){let i=this.parentValue.get(e);if(i)return i.has(t)}return!1}parent(e){for(let t of this.parents(e))return t}*children(e="\0"){if(this.isCompoundValue){let t=this.childrenValue.get(e);if(t)for(let i of t.keys())yield i}else if(e==="\0")for(let t of this.nodes())yield t}hasChildren(e="\0"){if(this.isCompoundValue){let t=this.childrenValue.get(e);if(!t)return!1;for(let i of t.keys())return!0;return!1}else if(e==="\0"){for(let t of this.nodes())return!0;return!1}return!1}*predecessors(e){let t=this.predecessorsValue.get(e);if(t)for(let i of t.keys())yield i}*successors(e){let t=this.successorsValue.get(e);if(t)for(let i of t.keys())yield i}*neighbors(e){if(!this.hasNode(e))return;let t=new Set;for(let i of this.predecessors(e))t.has(i)||(t.add(i),yield i);for(let i of this.successors(e))t.has(i)||(t.add(i),yield i)}isLeaf(e){if(this.isDirected()){for(let t of this.successors(e))return!1;return!0}for(let t of this.neighbors(e))return!1;return!0}filterNodes(e){let t=new c({directed:this.isDirectedValue,multigraph:this.isMultigraphValue,compound:this.isCompoundValue}),i=this.graph();t.setGraph(i);let r=new Set;if(this.nodesValue.forEach((s,o)=>{e(o)&&(t.setNode(o,s),r.add(o))}),this.edgeObjectsValue.forEach(s=>{r.has(s.v)&&r.has(s.w)&&t.setEdge(s,this.edge(s))}),this.isCompoundValue){let s=new Map;for(let o of t.nodes()){let a=[...this.parents(o)],n=[];for(;a.length>0;){let l=!1;for(let p of a)t.hasNode(p)&&(n.push(p),l=!0);if(l)break;let d=[];for(let p of a)for(let m of this.parents(p))d.push(m);a=d}n.length===0&&n.push("\0"),s.set(o,n)}for(let[o,a]of s){this.removeParent(o);for(let n of a)t.addParent(o,n)}}return t}setDefaultEdgeLabel(e){return typeof e=="function"?this.defaultEdgeLabelFn=e:this.defaultEdgeLabelFn=()=>e,this}edgeCount(){return this.edgeCountValue}edges(){return this.edgeObjectsValue.values()}setPath(e,t){if(!Array.isArray(e)||!e.length)return this;let i=arguments.length>1;return e.reduce((r,s)=>(i?this.setEdge(r,s,t):this.setEdge(r,s),s)),this}setEdge(e,t,i,r){if(typeof e=="object"&&e!==null&&"v"in e){let s=e;arguments.length>1?this._setEdge({loop:0},s,t):this._setEdge({loop:0},s)}else if(typeof t=="string"){let s=Bc(e,t,r);arguments.length>2?this._setEdge({loop:0},s,i):this._setEdge({loop:0},s)}else throw new Error("Invalid arguments for setEdge");return this}_setEdge(e,t,i){let r=!1,s;arguments.length>2&&(s=i,r=!0);let o=nr(t.v,t.w,t.name);if(this.edgeLabelsValue.has(o)){if(r&&this.edgeLabelsValue.set(o,s),e.loop===0&&!this.isDirectedValue&&t.w!==t.v){let p=Bc(t.w,t.v,t.name);r?this._setEdge({loop:1},p,i):this._setEdge({loop:1},p)}return}if(t.name&&!this.isMultigraphValue)throw new Error("Cannot set a named edge when isMultigraph = false");this.hasNode(t.v)||this.setNode(t.v),this.hasNode(t.w)||this.setNode(t.w);let n=r?s:this.defaultEdgeLabelFn(t.v,t.w,t.name);this.edgeLabelsValue.set(o,n),this.edgeObjectsValue.set(o,t);let l=this.predecessorsValue.get(t.w);if(l){let p=(l.get(t.v)||0)+1;l.set(t.v,p)}let d=this.successorsValue.get(t.v);if(d){let p=(d.get(t.w)||0)+1;d.set(t.w,p)}if(this.inValue.get(t.w).set(o,t),this.outValue.get(t.v).set(o,t),this.edgeCountValue++,e.loop===0&&!this.isDirectedValue&&t.w!==t.v){let p=Bc(t.w,t.v,t.name);r?this._setEdge({loop:1},p,i):typeof n=="object"&&n!==null?this._setEdge({loop:1},p,n):this._setEdge({loop:1},p)}}edge(e,t,i){let r;return typeof e=="object"?r=nr(e.v,e.w,e.name):r=nr(e,t,i),this.edgeLabelsValue.get(r)}hasEdge(e,t,i){let r;return typeof e=="object"?r=nr(e.v,e.w,e.name):r=nr(e,t,i),this.edgeLabelsValue.has(r)}removeEdge(e,t,i){return typeof e=="object"?this._removeEdge({loop:0},e.v,e.w,e.name):this._removeEdge({loop:0},e,t,i),this}_removeEdge(e,t,i,r){let s=nr(t,i,r),o=this.edgeObjectsValue.get(s);if(o){this.edgeLabelsValue.delete(s),this.edgeObjectsValue.delete(s);let a=this.predecessorsValue.get(o.w);if(a){let l=(a.get(o.v)||0)-1;l<=0?a.delete(o.v):a.set(o.v,l)}let n=this.successorsValue.get(o.v);if(n){let l=(n.get(o.w)||0)-1;l<=0?n.delete(o.w):n.set(o.w,l)}this.inValue.get(o.w)?.delete(s),this.outValue.get(o.v)?.delete(s),this.edgeCountValue--}!this.isDirectedValue&&e.loop===0&&this._removeEdge({loop:1},i,t,r)}*inEdges(e,t){let i=this.inValue.get(e);if(i){let r=i.values();if(!t){for(let s of r)yield s;return}for(let s of r)s.v===t&&(yield s)}}*outEdges(e,t){let i=this.outValue.get(e);if(!i)return;let r=i.values();if(!t){for(let s of r)yield s;return}for(let s of r)s.w===t&&(yield s)}*nodeEdges(e,t){for(let i of this.inEdges(e,t))yield i;for(let i of this.outEdges(e,t))i.v!==i.w&&(yield i)}};function Um(c,e){let t=[];for(let i of c.nodes()){let r=c.node(i);if(!r||r.domain.key!==e)continue;let s=[...c.parents(i)],o={v:i};o.value=r.toJSON(),s.length&&(o.parents=s),t.push(o)}return t}function zm(c,e){let t=[];for(let i of c.edges()){let r=c.edge(i);if(!r)continue;let s=c.node(i.v),o=c.node(i.w);if(!s||!o||s.domain.key!==e||o.domain.key!==e&&r.type!=="association"&&r.type!=="parent")continue;let a={v:i.v,w:i.w};i.name&&(a.name=i.name),a.value=structuredClone(r),t.push(a)}return t}function Vm(c,e){let t=[],i=new Set;for(let r of c.nodes()){let s=c.node(r);s&&s.domain.key===e&&i.add(r)}for(let r of i){let s=c.node(r);if(s){if(s.kind===be||s.kind===se){let a=[...c.inEdges(r)].filter(n=>{let l=c.node(n.v);return l&&l.domain.key===e});if(a.length===0){let n=s.kind===be?"Property":"Association";t.push(`${n} "${s.info.name}" (${r}) has no parent entity edge. This will cause deserialization to fail.`)}else if(a.length>1){let n=s.kind===be?"Property":"Association",l=a.map(d=>d.v).join(", ");t.push(`${n} "${s.info.name}" (${r}) has multiple parent edges: ${l}. This may cause deserialization issues.`)}else{let n=a[0],l=c.node(n.v);if(!l||l.kind!==$&&l.kind!==se){let d=s.kind===be?"Property":"Association";t.push(`${d} "${s.info.name}" (${r}) has a parent that is not an entity or association. Parent: ${l?.kind||"unknown"} (${n.v})`)}}}if(s.kind===$&&([...c.parents(r)].some(n=>{let l=c.node(n);return l&&l.kind===Oe})||t.push(`Entity "${s.info.name}" (${r}) has no model parent. Entities must belong to a model.`)),s.kind===Oe){let o=[...c.parents(r)],a=o.some(n=>{let l=c.node(n);return l&&l.kind===Le});if(o.length>0&&!a){let n=o.map(l=>`${c.node(l)?.kind||"unknown"} (${l})`).join(", ");t.push(`Model "${s.info.name}" (${r}) has invalid parent types: ${n}. Models can only belong to namespaces or be at root level.`)}}}}for(let r of i){let s=c.node(r);if(s&&s.kind===se){let o=s,n=[...c.outEdges(r)].filter(l=>{let d=c.edge(l);return d&&d.type==="association"});n.length;for(let l of n){let d=c.node(l.w);d?d.kind!==$&&t.push(`Association "${o.info.name}" (${r}) references non-entity target: ${d.kind} (${l.w})`):t.push(`Association "${o.info.name}" (${r}) references non-existent target: ${l.w}`)}}}if(t.length>0)throw new Error(`Graph consistency validation failed for domain "${e}":
|
|
51
|
+
`)}return this._scalarShapeObject(e)}};var xd=wp(Ad(),1);var Fo=Symbol("findAmfType"),Ed=Symbol("findReferenceObject"),Ie=Symbol("getArrayItems"),_d=Symbol("computeReferenceSecurity"),Lc=c=>{class e extends c{_amf;__cachedKeys;__lastSetValue;get amf(){return this._amf}set amf(i){if(this._amf===i||this.__lastSetValue===i)return;this.__lastSetValue=i;let r=i?this._expand(i):void 0;this.__cachedKeys={},this._amf=r,this._amfChanged(r)}_amfChanged(i){}_expand(i){return xd.AmfModelExpander.expand(i)}_getAmfKey(i,r){if(!i)return"";let{amf:s}=this;if(!s&&!r)return i;Array.isArray(s)&&([s]=s),this.__cachedKeys||(this.__cachedKeys={});let o=r||s&&s["@context"];if(!o||!i)return i;let a=this.__cachedKeys;if(i in a)return a[i];i=String(i);let n=i.indexOf("#"),l=i.substring(0,n+1),d=Object.keys(o);for(let p=0,m=d.length;p<m;p++){let h=d[p];if(o[h]===i)return a[i]=h,h;if(n===-1&&i.indexOf(o[h])===0){let f=i.replace(o[h],`${h}:`);return a[i]=f,f}if(o[h]===l){let f=`${h}:${i.substring(n+1)}`;return a[i]=f,f}}return i}_ensureAmfModel(i){if(i&&(Array.isArray(i)&&([i]=i),this._hasType(i,u.aml.vocabularies.document.Document)))return i}_ensureArray(i){if(i)return i instanceof Array?i:[i]}_getValue(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&i[o];if(!a)return a;if(Array.isArray(a)&&([a]=a),!a)return;let n=typeof a;return["string","number","boolean","undefined"].includes(n)?a:a["@value"]}_getValueArray(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&this._ensureArray(i[o]);if(Array.isArray(a))return a.map(n=>n["@value"]||n)}[Ie](i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&this._ensureArray(i[o]);if(Array.isArray(a))return a}_getLinkValue(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&i[o];if(a&&(Array.isArray(a)&&([a]=a),!!a))return a["@id"]}_getLinkValues(i,r,s){let o=this._getAmfKey(r,s);if(!o)return;let a=i&&i[o];if(a)return Array.isArray(a)||(a=[a]),a.map(n=>n["@id"])}_hasType(i,r,s){let o=this._ensureArray(i&&i["@type"]);if(!o||!o.length)return!1;let a=this._getAmfKey(r,s);for(let n of o)if(n===a)return!0;return!1}_hasProperty(i,r,s){let o=this._getAmfKey(r,s);return!!(i&&o&&o in i)}_computePropertyArray(i,r,s){if(!i)return;let o=this._getAmfKey(r,s);if(!o)return;let a=this._ensureArray(i&&i[o]);if(!(!a||!Array.isArray(a)))return a}_computeApiVersion(i,r){let s=this._computeApi(i);if(s)return this._getValue(s,u.aml.vocabularies.core.version,r)}_computeEncodes(i,r){if(!i)return;Array.isArray(i)&&([i]=i);let s=this._getAmfKey(u.aml.vocabularies.document.encodes,r);if(!s)return;let o=i[s];if(o)return Array.isArray(o)?o[0]:o}_computeDeclares(i,r){if(!i||(Array.isArray(i)&&([i]=i),!i))return;let s=this._getAmfKey(u.aml.vocabularies.document.declares,r);if(!s)return;let o=this._ensureArray(i[s]);return Array.isArray(o)?o:void 0}_computeReferences(i,r){if(!i||(Array.isArray(i)&&([i]=i),!i))return;let s=this._getAmfKey(u.aml.vocabularies.document.references,r);if(!s)return;let o=this._ensureArray(i[s]);return o instanceof Array?o:void 0}_computeWebApi(i,r){let s=this._computeEncodes(i,r);if(s&&this._hasType(s,u.aml.vocabularies.apiContract.WebAPI,r))return s}_computeApi(i,r){let s=this._computeEncodes(i,r);if(s&&(this._isAPI(i,r)||this._isWebAPI(i,r)||this._isAsyncAPI(i,r)))return s}_isWebAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,u.aml.vocabularies.apiContract.WebAPI,r):!1}_isAsyncAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,u.aml.vocabularies.apiContract.AsyncAPI,r):!1}_isAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,u.aml.vocabularies.apiContract.API,r):!1}_isValidServerPartial(i,r){if(Array.isArray(i)&&([i]=i),!i)return!1;let s=u.aml.vocabularies.apiContract.Operation,o=u.aml.vocabularies.apiContract.EndPoint,a=[this._getAmfKey(s,r),this._getAmfKey(o,r)],n=i["@type"];for(let l of n)if(a.indexOf(l)!==-1)return!0;return!1}_getServers(i={},r){let{endpointId:s,methodId:o}=i,{amf:a}=this;if(!a)return;let n=this._computeApi(a,r);if(Array.isArray(n)&&([n]=n),!n)if(this._isValidServerPartial(a,r))n=a;else return;let l=this._getAmfKey(u.aml.vocabularies.apiContract.server,r),d=()=>this[Ie](n,l,r),p=()=>{let h=this._computeEndpointModel(n,s,r),f=this[Ie](h,l,r);return f||d()},m=()=>{let h=this._computeMethodModel(n,o,r),f=this[Ie](h,l,r);return f||p()};return o?m():s?p():d()}_computeExpects(i,r){let s=u.aml.vocabularies.apiContract.Operation,o=u.aml.vocabularies.apiContract.expects;if(this._hasType(i,s,r)){let a=this._getAmfKey(o,r),n=this._ensureArray(i[a]);if(n)return Array.isArray(n)?n[0]:n}}_computeEndpoints(i,r){if(!i)return[];let s=u.aml.vocabularies.apiContract.endpoint,o=this._getAmfKey(s,r);return this._ensureArray(i[o])}_computeEndpointModel(i,r,s){if(this._hasType(i,u.aml.vocabularies.apiContract.EndPoint,s))return i;let o=this._computeEndpoints(i,s);if(o)return o.find(a=>a["@id"]===r)}_computeMethodModel(i,r,s){let o=this.__computeMethodsListForMethod(i,r,s);if(o)return o.find(a=>a["@id"]===r)}_computeMethodEndpoint(i,r,s){if(!i||!r)return;if(this._hasType(i,u.aml.vocabularies.apiContract.EndPoint,s))return i;let o=this._computeEndpoints(i,s);if(!o)return;let a=this._getAmfKey(u.aml.vocabularies.apiContract.supportedOperation,s);for(let n=0,l=o.length;n<l;n++){let d=o[n],p=d[a];if(p){Array.isArray(p)||(p=[p]);for(let m=0,h=p.length;m<h;m++)if(p[m]["@id"]===r)return d}}}__computeMethodsListForMethod(i,r,s){let o=this._computeMethodEndpoint(i,r,s);if(!o)return;let a=this._getAmfKey(u.aml.vocabularies.apiContract.supportedOperation,s);return this._ensureArray(o[a])}_computeType(i,r,s,o){if(!i&&!r||!s)return;let a=s.replace("amf://id",""),n=i&&i.find(l=>l["@id"]===s||l["@id"]===a);if(!n&&r&&r.length)for(let l=0,d=r.length;l<d&&!(this._hasType(r[l],u.aml.vocabularies.document.Module)&&(n=this._computeReferenceType(r[l],s,o),n));l++);return n}[Fo](i,r){let{amf:s}=this;if(!s||!i)return;Array.isArray(s)&&([s]=s);let o=this._computeDeclares(s,r),a=i.replace("amf://id","");if(Array.isArray(o)){let n=o.find(l=>l["@id"]===i||l["@id"]===a);if(n)return n}return this[Ed](i)}[Ed](i,r){let{amf:s}=this;if(Array.isArray(s)&&([s]=s),!s)return;let o=this._computeReferences(s,r);if(!Array.isArray(o)||!o.length)return;let a=i.replace("amf://id","");for(let n=0,l=o.length;n<l;n++){let d=o[n],p=this._computeDeclares(d,r);if(Array.isArray(p))for(let m=0,h=p.length;m<h;m++){let f=p[m];if(Array.isArray(f)&&([f]=f),f["@id"]===i||f["@id"]===a)return f}}}_computeReferenceType(i,r,s){let o=this._computeDeclares(i,s);if(!o||!r)return;let a=r.replace("amf://id",""),n=o.find(l=>(Array.isArray(l)&&([l]=l),l["@id"]===r||l["@id"]===a));return Array.isArray(n)&&([n]=n),this._resolve(n)}_computeDocument(i,r,s){if(!i||!r)return;let o=this._getAmfKey(u.aml.vocabularies.core.documentation,s),a=this._ensureArray(i[o]);return a&&a.find(n=>n["@id"]===r)}_resolve(i,r){let{amf:s}=this;if(typeof i!="object"||Array.isArray(i)||!s||i.__apicResolved)return i;let o=this._getAmfKey(u.aml.vocabularies.document.linkTarget,r),a=this._ensureArray(i[o]),n;if(a){let p=a[0]["@id"];if(p===i["@id"])return i.__apicResolved=!0,i;n=this._getLinkTarget(s,p,r)}else if(o=this._getAmfKey(u.aml.vocabularies.document.referenceId,r),a=this._ensureArray(i[o]),a){let p=a[0]["@id"];if(p===i["@id"])return i.__apicResolved=!0,i;n=this._getReferenceId(s,p,r)}if(!n)return this._resolveRecursive(i),i.__apicResolved=!0,i;let l={...n};delete l["@id"];let d=l["@type"];return d&&(i["@type"]?i["@type"]=i["@type"].concat(d):i["@type"]=d,delete l["@type"]),this._mergeShapes(i,l,r),i.__apicResolved=!0,this._resolveRecursive(i),i}_getLinkTarget(i,r,s){if(!i||!r)return;let o,a=this._computeDeclares(i,s);if(a&&(o=this._findById(a,r)),!o){let n=this._computeReferences(i,s);o=this._obtainShapeFromReferences(n,r,s)}if(o)return o=this._resolve(o),o}_obtainShapeFromReferences(i,r,s){if(!Array.isArray(i)||!i.length)return;let o;for(let a of i){let n=this._computeEncodes(a,s);if(n&&n["@id"]===r){o=n;break}if(!n&&(o=this._findById(this._computeDeclares(a,s),r),o))break}return o}_findById(i,r){if(!i)return;let s;for(let o of i)if(o&&o["@id"]===r){s=o;break}return s}_getReferenceId(i,r,s){if(!i||!r)return;let o=this._computeReferences(i,s);if(o)for(let a of o){let n=this._computeEncodes(a,s);if(n&&n["@id"]===r)return n}}_resolveRecursive(i,r){Object.keys(i).forEach(s=>{let o=i[s];if(Array.isArray(o))for(let a=0,n=o.length;a<n;a++)o[a]=this._resolve(o[a]);else typeof o=="object"&&(i[s]=this._resolve(o,r))})}_mergeShapes(i,r,s){let o={...i,...r};return[{key:this._getAmfKey(u.aml.vocabularies.docSourceMaps.sources,s),merger:this._mergeSourceMapsSources.bind(this)}].forEach(({key:n,merger:l})=>{this._hasProperty(o,n,s)&&(o[n]=l(i,r,s))}),Object.assign(i,o)}_mergeSourceMapsSources(i,r,s){let o=this._getAmfKey(u.aml.vocabularies.docSourceMaps.sources,s),a=i[o]||{};Array.isArray(a)&&(a=a[0]);let n=r[o]||{};return Array.isArray(n)&&(n=n[0]),[Object.assign(a,n)]}_expandKey(i,r){let{amf:s}=this;if(!i||typeof i!="string"||!s&&!r)return i;Array.isArray(s)&&([s]=s);let o=r||s&&s["@context"];if(!o)return i;let[a,n]=i.split(":");if(!a||!n)return i;let l=o[a];return l?`${l}${n}`:i}findSecurityScheme(i,r){let{amf:s}=this,o=this._computeDeclares(s,r),a;if(o&&(a=o.find(l=>l["@id"]===i)),a)return a=this._resolve(a),a;let n=this._computeReferences(s,r);if(Array.isArray(n)&&n.length){for(let l of n)if(this._hasType(l,u.aml.vocabularies.document.Module,r)&&(a=this[_d](l,i,r),a))return a=this._resolve(a),a}}[_d](i,r,s){let o=this._computeDeclares(i,s);if(!o)return;let a=o.find(n=>{let l=n;return Array.isArray(l)&&([l]=l),l["@id"]===r});return Array.isArray(a)&&([a]=a),this._resolve(a)}getByType(i,r,s){if(!i)return[];let o=[],a=this._computeDeclares(i),n=this._getAmfKey(r,s);a&&a.length&&a.forEach(d=>{this._hasType(d,n)&&o.push(d)});let l=this._computeReferences(i);if(Array.isArray(l)&&l.length){for(let d of l)if(this._hasType(d,u.aml.vocabularies.document.Module)){let p=this.getByType(d,r,s);p.length&&(o=o.concat(p))}}return o}}return e};var Mc=class extends Lc(Object){constructor(e){super(),e&&(this.amf=e)}readTypes(e,t){let i=e;return typeof i=="string"&&(i=[i]),Array.isArray(i)?i.map(r=>this._expandKey(r,t)):[]}apiSummary(e){let t=e["@context"],i={id:e["@id"],types:this.readTypes(e["@type"],t),customDomainProperties:this.customDomainProperties(e,t),sourceMaps:this.sourceMap(e),schemes:[],accepts:[],contentType:[],documentations:[],tags:[]},r=this._getValue(e,u.aml.vocabularies.core.name,t);r&&typeof r=="string"&&(i.name=r);let s=this._getValue(e,u.aml.vocabularies.core.description,t);s&&typeof s=="string"&&(i.description=s);let o=this._getValue(e,u.aml.vocabularies.core.version,t);o&&typeof o=="string"&&(i.version=o);let a=this._getValue(e,u.aml.vocabularies.core.termsOfService,t);a&&typeof a=="string"&&(i.termsOfService=a);let n=e[this._getAmfKey(u.aml.vocabularies.apiContract.accepts,t)];Array.isArray(n)&&n.length&&(i.accepts=this._getValueArray(e,u.aml.vocabularies.apiContract.accepts,t));let l=e[this._getAmfKey(u.aml.vocabularies.apiContract.contentType,t)];Array.isArray(l)&&l.length&&(i.contentType=this._getValueArray(e,u.aml.vocabularies.apiContract.contentType,t));let d=e[this._getAmfKey(u.aml.vocabularies.apiContract.scheme,t)];Array.isArray(d)&&d.length&&(i.schemes=this._getValueArray(e,u.aml.vocabularies.apiContract.scheme,t));let p=e[this._getAmfKey(u.aml.vocabularies.core.provider,t)];Array.isArray(p)&&([p]=p),p&&(i.provider=this.provider(p));let m=e[this._getAmfKey(u.aml.vocabularies.core.license,t)];Array.isArray(m)&&([m]=m),m&&(i.license=this.license(m));let h=e[this._getAmfKey(u.aml.vocabularies.apiContract.tag,t)];Array.isArray(h)&&h.length&&(i.tags=h.map(k=>this.tag(k)));let f=e[this._getAmfKey(u.aml.vocabularies.core.documentation,t)];return Array.isArray(f)&&f.length&&(i.documentations=f.map(k=>this.documentation(k))),i}api(e,t){let i=t||e["@context"],r=this.apiSummary(e);r.endPoints=[],r.servers=[],r.security=[];let s=e[this._getAmfKey(u.aml.vocabularies.apiContract.endpoint,i)];Array.isArray(s)&&s.length&&(r.endPoints=s.map(n=>this.endPoint(n,i)));let o=e[this._getAmfKey(u.aml.vocabularies.apiContract.server,i)];Array.isArray(o)&&o.length&&(r.servers=o.map(n=>this.server(n,i)));let a=e[this._getAmfKey(u.aml.vocabularies.security.security,i)];return Array.isArray(a)&&a.length&&(r.security=a.map(n=>this.securityRequirement(n,i))),r}webApi(e,t){return this.api(e,t)}asyncApi(e,t){return this.api(e,t)}provider(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getLinkValue(e,u.aml.vocabularies.core.url,i);o&&typeof o=="string"&&(r.url=o);let a=this._getValue(e,u.aml.vocabularies.core.email,i);return a&&typeof a=="string"&&(r.email=a),r}license(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getLinkValue(e,u.aml.vocabularies.core.url,i);return o&&typeof o=="string"&&(r.url=o),r}server(e,t){let i=t||e["@context"],r=this._getValue(e,u.aml.vocabularies.core.urlTemplate,i)||"",s={id:e["@id"],types:this.readTypes(e["@type"],i),url:r,variables:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(s.description=o);let a=e[this._getAmfKey(u.aml.vocabularies.apiContract.variable,i)];Array.isArray(a)&&a.length&&(s.variables=a.map(p=>this.parameter(p,i)));let n=this._getValue(e,u.aml.vocabularies.apiContract.protocol,i),l=this._getValue(e,u.aml.vocabularies.apiContract.protocolVersion,i);n&&(s.protocol=n),l&&(s.protocolVersion=l);let d=e[this._getAmfKey(u.aml.vocabularies.security.security,i)];return Array.isArray(d)&&d.length&&(s.security=d.map(p=>this.securityRequirement(p,i))),s}parameter(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),payloads:[],examples:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.paramName,i);o&&typeof o=="string"&&(r.paramName=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.apiContract.required,i);typeof n=="boolean"&&(r.required=n);let l=this._getValue(e,u.aml.vocabularies.apiContract.allowEmptyValue,i);typeof l=="boolean"&&(r.allowEmptyValue=l);let d=this._getValue(e,u.aml.vocabularies.document.deprecated,i);typeof d=="boolean"&&(r.deprecated=d);let p=this._getValue(e,u.aml.vocabularies.apiContract.explode,i);typeof p=="boolean"&&(r.explode=p);let m=this._getValue(e,u.aml.vocabularies.apiContract.allowReserved,i);typeof m=="boolean"&&(r.allowReserved=m);let h=this._getValue(e,u.aml.vocabularies.apiContract.style,i);h&&typeof h=="string"&&(r.style=h);let f=this._getValue(e,u.aml.vocabularies.apiContract.binding,i);f&&typeof f=="string"&&(r.binding=f);let k=e[this._getAmfKey(u.aml.vocabularies.shapes.schema,i)];if(Array.isArray(k)&&k.length){let[E]=k;r.schema=this.unknownShape(E,{trackedId:e["@id"]},i)}let w=e[this._getAmfKey(u.aml.vocabularies.apiContract.payload,i)];Array.isArray(w)&&w.length&&(r.payloads=w.map(E=>this.payload(E,i)));let S=e[this._getAmfKey(u.aml.vocabularies.apiContract.examples,i)];return Array.isArray(S)&&S.length&&(r.examples=S.map(E=>this.example(E,i))),r}unknownShape(e,t,i){let r=i||e["@context"],s=this.readTypes(e["@type"],r);return s.includes(u.aml.vocabularies.shapes.ScalarShape)?this.scalarShape(e,t,r):s.includes(u.w3.shacl.NodeShape)?this.nodeShape(e,t,r):s.includes(u.aml.vocabularies.shapes.UnionShape)?this.unionShape(e,t,r):s.includes(u.aml.vocabularies.shapes.FileShape)?this.fileShape(e,t,r):s.includes(u.aml.vocabularies.shapes.SchemaShape)?this.schemaShape(e,t,r):s.includes(u.aml.vocabularies.shapes.TupleShape)?this.tupleShape(e,t,r):s.includes(u.aml.vocabularies.shapes.ArrayShape)||s.includes(u.aml.vocabularies.shapes.MatrixShape)?this.arrayShape(e,t,r):s.includes(u.aml.vocabularies.shapes.RecursiveShape)?this.recursiveShape(e,r):this.anyShape(e,t,r)}isLink(e,t){let i=t||e["@context"];return!!this._getLinkValue(e,u.aml.vocabularies.document.linkTarget,i)}getLinkTarget(e,t){let i=t||e["@context"],r=this._getLinkValue(e,u.aml.vocabularies.document.linkTarget,i);if(r)return this[Fo](r,i)}shape(e,t){let i=t||e["@context"];this._resolve(e);let r,s=e;if(this.isLink(s)){r=this._getValue(s,u.aml.vocabularies.document.linkLabel,i);let L=this._getLinkValue(s,u.aml.vocabularies.document.linkTarget,i),I=this[Fo](L,i);I&&(s=I)}let o={id:s["@id"],types:this.readTypes(e["@type"],i),values:[],inherits:[],or:[],and:[],xone:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)};r&&(o.linkLabel=r);let a=this._getValue(s,u.w3.shacl.name,i);a&&typeof a=="string"&&(o.name=a);let n=this._getValue(s,u.aml.vocabularies.core.displayName,i);if(n&&typeof n=="string")o.displayName=n;else{let L=this._getValue(s,u.aml.vocabularies.core.name,i);L&&typeof L=="string"&&(o.displayName=L)}let l=this._getValue(s,u.aml.vocabularies.core.description,i);l&&typeof l=="string"&&(o.description=l);let d=this._getValue(s,u.w3.shacl.defaultValueStr,i);d&&typeof d=="string"&&(o.defaultValueStr=d);let p=this._getValue(s,u.aml.vocabularies.shapes.deprecated,i);typeof p=="boolean"&&(o.deprecated=p);let m=this._getValue(s,u.aml.vocabularies.shapes.readOnly,i);typeof m=="boolean"&&(o.readOnly=m);let h=this._getValue(s,u.aml.vocabularies.shapes.writeOnly,i);typeof h=="boolean"&&(o.writeOnly=h);let f=s[this._getAmfKey(u.w3.shacl.defaultValue,i)];Array.isArray(f)&&f.length&&(o.defaultValue=this.unknownDataNode(f[0],i));let k=this._getAmfKey(u.w3.shacl.or,i),w=s[k];Array.isArray(w)&&w.length&&(o.or=w.map(L=>this.unknownShape(L,void 0,i)));let S=this._getAmfKey(u.w3.shacl.and,i),E=s[S];Array.isArray(E)&&E.length&&(o.and=E.map(L=>this.unknownShape(L,void 0,i)));let A=this._getAmfKey(u.w3.shacl.xone,i),_=s[A];Array.isArray(_)&&_.length&&(o.xone=_.map(L=>this.unknownShape(L,void 0,i)));let $=s[this._getAmfKey(u.w3.shacl.in,i)];if(Array.isArray($)&&$.length){let[L]=$,I=u.w3.rdfSchema.key,R=this._getAmfKey(I,i);Object.keys(L).forEach(x=>{if(x.startsWith(I)||x.startsWith(R)){let D=L[x];Array.isArray(D)&&([D]=D);let M=this.unknownDataNode(D,i);M&&o.values.push(M)}})}let P=this._getAmfKey(u.w3.shacl.not,i),j=s[P];return j&&(Array.isArray(j)&&([j]=j),o.not=this.unknownShape(j,void 0,i)),o}anyShape(e,t={},i){let r=i||e["@context"],s=e,o=this.shape(s,r);if(this.isLink(s)){let d=this.getLinkTarget(s,r);d&&(s=d)}o.examples=[];let a=s[this._getAmfKey(u.aml.vocabularies.apiContract.examples,r)];if(Array.isArray(a)&&a.length)if(t.trackedId){let d=this.filterTrackedExamples(a,t.trackedId,r);o.examples=d.map(p=>this.example(p,r))}else{let d=this.filterNonTrackedExamples(a,r);o.examples=d.map(p=>this.example(p,r))}let n=s[this._getAmfKey(u.aml.vocabularies.core.documentation,r)];if(Array.isArray(n)&&n.length){let[d]=n;o.documentation=this.documentation(d,r)}let l=s[this._getAmfKey(u.aml.vocabularies.shapes.xmlSerialization,r)];return Array.isArray(l)&&l.length&&(o.xmlSerialization=this.xmlSerializer(l[0],r)),o}filterTrackedExamples(e,t,i){let{docSourceMaps:r}=u.aml.vocabularies,s=this._getAmfKey(r.sources,i),o=this._getAmfKey(r.trackedElement,i),a=t.indexOf("amf")===-1?`amf://id${t}`:t;return e.filter(n=>{let l=n;Array.isArray(l)&&([l]=l);let d=l[s];if(!d)return!0;Array.isArray(d)&&([d]=d);let p=d[o];if(!p)return!0;Array.isArray(p)&&([p]=p);let{value:m}=this.synthesizedField(p,i);if(!m)return!0;let h=m.split(",");return h.indexOf(a)!==-1||h.indexOf(t)!==-1})}filterNonTrackedExamples(e,t){let{docSourceMaps:i}=u.aml.vocabularies,r=this._getAmfKey(i.sources,t),s=this._getAmfKey(i.trackedElement,t);return e.filter(o=>{let a=o;Array.isArray(a)&&([a]=a);let n=a[r];if(!n)return!0;Array.isArray(n)&&([n]=n);let l=n[s];if(!l)return!0;Array.isArray(l)&&([l]=l);let{value:d}=this.synthesizedField(l,t);return!d})}scalarShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let k=this.getLinkTarget(s,r);k&&(s=k)}let a=this._getValue(s,u.w3.shacl.pattern,r);a&&typeof a=="string"&&(o.pattern=a);let n=this._getLinkValue(s,u.w3.shacl.datatype,r);n&&typeof n=="string"&&(o.dataType=n);let l=this._getValue(s,u.aml.vocabularies.shapes.format,r);l&&typeof l=="string"&&(o.format=l);let d=this._getValue(s,u.aml.vocabularies.shapes.multipleOf,r);typeof d=="number"&&(o.multipleOf=d);let p=this._getValue(s,u.w3.shacl.minInclusive,r);typeof p=="number"&&(o.minimum=p,o.exclusiveMinimum=!1);let m=this._getValue(s,u.w3.shacl.maxInclusive,r);typeof m=="number"&&(o.maximum=m,o.exclusiveMaximum=!1);let h=this._getValue(s,u.w3.shacl.minLength,r);typeof h=="number"&&(o.minLength=h);let f=this._getValue(s,u.w3.shacl.maxLength,r);return typeof f=="number"&&(o.maxLength=f),o}nodeShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let m=this.getLinkTarget(s,r);m&&(s=m)}let a=this._getValue(s,u.aml.vocabularies.shapes.discriminator,r);a&&typeof a=="string"&&(o.discriminator=a);let n=this._getValue(s,u.aml.vocabularies.shapes.discriminatorValue,r);n&&typeof n=="string"&&(o.discriminatorValue=n);let l=this._getValue(s,u.w3.shacl.closed,r);typeof l=="boolean"&&(o.closed=l),o.customShapeProperties=[],o.customShapePropertyDefinitions=[],o.dependencies=[];let d=s[this._getAmfKey(u.w3.shacl.property,r)];Array.isArray(d)&&d.length?o.properties=d.map(m=>this.propertyShape(m,r)):o.properties=[];let p=s[this._getAmfKey(u.w3.shacl.additionalPropertiesSchema,r)];if(Array.isArray(p)&&p.length===1){let[m]=p;o.additionalPropertiesSchema=this.unknownShape(m,void 0,r)}return o}propertyShape(e,t){let i=t||e["@context"],r=e,s=this.shape(r,i);if(this.isLink(r)){let d=this.getLinkTarget(r,i);d&&(r=d)}let o=this._getLinkValue(r,u.w3.shacl.path,i);o&&typeof o=="string"&&(s.path=o);let a=this._getValue(r,u.w3.shacl.minCount,i);typeof a=="number"&&(s.minCount=a);let n=this._getValue(r,u.w3.shacl.maxCount,i);typeof n=="number"&&(s.maxCount=n);let l=r[this._getAmfKey(u.aml.vocabularies.shapes.range,i)];if(Array.isArray(l)&&l.length){let[d]=l;s.range=this.unknownShape(d,void 0,i)}return s}unionShape(e,t={},i){let r=i||e["@context"],s=e[this._getAmfKey(u.aml.vocabularies.shapes.anyOf,r)],o=this.anyShape(e,t,r);if(Array.isArray(s)&&s.length){let a={...t,trackedId:void 0};o.anyOf=s.map(n=>this.unknownShape(n,a,r))}else o.anyOf=[];return o}fileShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let k=this.getLinkTarget(s,r);k&&(s=k)}let a=this._getValue(s,u.w3.shacl.pattern,r);a&&typeof a=="string"&&(o.pattern=a);let n=this._getValueArray(s,u.aml.vocabularies.shapes.fileType,r);Array.isArray(n)&&n.length&&(o.fileTypes=n);let l=this._getValue(s,u.w3.shacl.minLength,r);typeof l=="number"&&(o.minLength=l);let d=this._getValue(s,u.w3.shacl.maxLength,r);typeof d=="number"&&(o.maxLength=d);let p=this._getValue(s,u.w3.shacl.minInclusive,r);typeof p=="number"&&(o.minimum=p,o.exclusiveMinimum=!1);let m=this._getValue(s,u.w3.shacl.maxInclusive,r);typeof m=="number"&&(o.maximum=m,o.exclusiveMaximum=!1);let h=this._getValue(s,u.aml.vocabularies.shapes.format,r);h&&typeof h=="string"&&(o.format=h);let f=this._getValue(s,u.aml.vocabularies.shapes.multipleOf,r);return typeof f=="number"&&(o.multipleOf=f),o}schemaShape(e,t={},i){let r=i||e["@context"],s=e,o=this.anyShape(s,t,r);if(this.isLink(s)){let l=this.getLinkTarget(s,r);l&&(s=l)}let a=this._getValue(s,u.aml.vocabularies.core.mediaType,r);a&&typeof a=="string"&&(o.mediaType=a);let n=this._getValue(s,u.aml.vocabularies.document.raw,r);return n&&typeof n=="string"&&(o.raw=n),o}recursiveShape(e,t){let i=t||e["@context"],r=e,s=this.shape(r,i);if(this.isLink(r)){let a=this.getLinkTarget(r,i);a&&(r=a)}let o=this._getLinkValue(r,u.aml.vocabularies.shapes.fixPoint,i);return o&&typeof o=="string"&&(s.fixPoint=o),s}dataArrangeShape(e,t={},i){let r=i||e["@context"];return this.anyShape(e,t,r)}arrayShape(e,t={},i){let r=i||e["@context"],s=e,o=this.dataArrangeShape(s,t,r);if(this.isLink(s)){let n=this.getLinkTarget(s,r);n&&(s=n)}let a=s[this._getAmfKey(u.aml.vocabularies.shapes.items,r)];if(Array.isArray(a)&&a.length){let[n]=a;o.items=this.unknownShape(n,void 0,r)}return o}tupleShape(e,t,i){let r=i||e["@context"],s=e,o=this.dataArrangeShape(s,t,r);if(this.isLink(s)){let l=this.getLinkTarget(s,r);l&&(s=l)}let a=s[this._getAmfKey(u.aml.vocabularies.shapes.items,r)],n=this._getAmfKey(u.w3.rdfSchema.key,r);return Array.isArray(a)&&a.length?(o.items=[],a.forEach(l=>{Array.isArray(l)&&([l]=l),Object.keys(l).filter(d=>d.startsWith(n)).forEach(d=>{let p=l[d];Array.isArray(p)&&([p]=p);let m=this.unknownShape(p,void 0,r);o.items.push(m)})})):o.items=[],o}documentation(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getLinkValue(e,u.aml.vocabularies.core.url,i);s&&typeof s=="string"&&(r.url=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,u.aml.vocabularies.core.title,i);return a&&typeof a=="string"&&(r.title=a),r}example(e,t){let i=t||e["@context"];this._resolve(e);let r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),strict:!1},s=this._getValue(e,u.aml.vocabularies.document.strict,i);typeof s=="boolean"&&(r.strict=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.displayName,i);a&&typeof a=="string"&&(r.displayName=a);let n=this._getValue(e,u.aml.vocabularies.core.description,i);n&&typeof n=="string"&&(r.description=n);let l=this._getValue(e,u.aml.vocabularies.document.raw,i);l&&typeof l=="string"&&(r.value=l);let d=this._getValue(e,u.aml.vocabularies.document.location,i);d&&typeof d=="string"&&(r.location=d);let p=e[this._getAmfKey(u.aml.vocabularies.document.structuredValue,i)];if(Array.isArray(p)&&p.length){let[m]=p;r.structuredValue=this.unknownDataNode(m,i)}return r}xmlSerializer(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.shapes.xmlAttribute,i);typeof s=="boolean"&&(r.attribute=s);let o=this._getValue(e,u.aml.vocabularies.shapes.xmlWrapped,i);typeof o=="boolean"&&(r.wrapped=o);let a=this._getValue(e,u.aml.vocabularies.shapes.xmlName,i);a&&typeof a=="string"&&(r.name=a);let n=this._getValue(e,u.aml.vocabularies.shapes.xmlNamespace,i);n&&typeof n=="string"&&(r.namespace=n);let l=this._getValue(e,u.aml.vocabularies.shapes.xmlPrefix,i);return l&&typeof l=="string"&&(r.prefix=l),r}unknownDataNode(e,t){let i=this.readTypes(e["@type"],t);if(i.includes(u.aml.vocabularies.data.Scalar))return this.scalarNode(e,t);if(i.includes(u.aml.vocabularies.data.Object))return this.objectNode(e,t);if(i.includes(u.aml.vocabularies.data.Array))return this.arrayNode(e,t)}dataNode(e,t){let i={id:e["@id"],types:this.readTypes(e["@type"],t),customDomainProperties:this.customDomainProperties(e,t)},r=this._getValue(e,u.aml.vocabularies.core.name,t);return r&&typeof r=="string"&&(i.name=r),i}scalarNode(e,t){let i=t||e["@context"],r=this.dataNode(e,t),s=this._getValue(e,u.aml.vocabularies.data.value,i);s&&typeof s=="string"&&(r.value=s);let o=this._getLinkValue(e,u.w3.shacl.datatype,i);return o&&typeof o=="string"&&(r.dataType=o),r}objectNode(e,t){let i=t||e["@context"],r=this.dataNode(e,t);r.properties={};let s=u.aml.vocabularies.data.key,o=`${this._getAmfKey(s,i)}:`;return Object.keys(e).forEach(a=>{if(a.startsWith(s)||a.startsWith(o)){let n=e[a];Array.isArray(n)&&([n]=n);let l=a.replace(s,"").replace(o,""),d=this.unknownDataNode(n,t);d&&(r.properties[l]=d)}}),r}arrayNode(e,t){let i=t||e["@context"],r=this.dataNode(e,i);r.members=[];let s=this._computePropertyArray(e,u.w3.rdfSchema.member);return Array.isArray(s)&&s.length&&s.forEach(o=>{let a=this.unknownDataNode(o);a&&r.members.push(a)}),r}customDomainProperties(e,t){let i=[],r=t||e["@context"],s=this._getLinkValues(e,u.aml.vocabularies.document.customDomainProperties,r);return Array.isArray(s)&&s.length&&s.forEach(o=>{let a=`@base:${o}`,n=e[o]||e[a];if(!n)return;Array.isArray(n)&&([n]=n);let l=this.unknownDataNode(n,r),d=this._getValue(n,u.aml.vocabularies.core.extensionName,r);if(!d||!l)return;let p={id:o,name:d,extension:l};i.push(p)}),i}endPoint(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),path:"",operations:[],parameters:[],payloads:[],servers:[],security:[],extends:[]},s=this._getValue(e,u.aml.vocabularies.apiContract.path,i);s&&typeof s=="string"&&(r.path=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.core.summary,i);n&&typeof n=="string"&&(r.summary=n);let l=this[Ie](e,u.aml.vocabularies.apiContract.supportedOperation,i);Array.isArray(l)&&l.length&&(r.operations=l.map(k=>this.operation(k,i)));let d=this[Ie](e,u.aml.vocabularies.apiContract.parameter,i);Array.isArray(d)&&d.length&&(r.parameters=d.map(k=>this.parameter(k,i)));let p=this[Ie](e,u.aml.vocabularies.apiContract.payload,i);Array.isArray(p)&&p.length&&(r.payloads=p.map(k=>this.payload(k,i)));let m=this[Ie](e,u.aml.vocabularies.apiContract.server,i);Array.isArray(m)&&m.length&&(r.servers=m.map(k=>this.server(k,i)));let h=this[Ie](e,u.aml.vocabularies.security.security,i);Array.isArray(h)&&h.length&&(r.security=h.map(k=>this.securityRequirement(k,i)));let f=this[Ie](e,u.aml.vocabularies.document.extends,i);return Array.isArray(f)&&f.length&&(r.extends=[],f.forEach(k=>{let w=k;Array.isArray(w)&&([w]=w),this._hasType(w,u.aml.vocabularies.apiContract.ParametrizedResourceType,i)?r.extends.push(this.parametrizedResourceType(w,i)):this._hasType(w,u.aml.vocabularies.apiContract.ParametrizedTrait,i)&&r.extends.push(this.parametrizedTrait(w,i))})),r}operation(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),method:"",deprecated:!1,callbacks:[],responses:[],servers:[],security:[],accepts:[],schemes:[],contentType:[],tags:[],extends:[]},s=this._getValue(e,u.aml.vocabularies.apiContract.method,i);s&&typeof s=="string"&&(r.method=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.apiContract.guiSummary,i);n&&typeof n=="string"&&(r.summary=n);let l=this._getValue(e,u.aml.vocabularies.core.deprecated,i);typeof l=="boolean"&&(r.deprecated=l);let d=this._getValue(e,u.aml.vocabularies.apiContract.operationId,i);d&&typeof d=="string"&&(r.operationId=d);let p=this._getValueArray(e,u.aml.vocabularies.apiContract.accepts,i);Array.isArray(p)&&(r.accepts=p);let m=this._getValueArray(e,u.aml.vocabularies.apiContract.scheme,i);Array.isArray(m)&&(r.schemes=m);let h=this._getValueArray(e,u.aml.vocabularies.apiContract.contentType,i);Array.isArray(h)&&(r.contentType=h);let f=e[this._getAmfKey(u.aml.vocabularies.apiContract.expects,i)];f&&(Array.isArray(f)&&([f]=f),r.request=this.request(f,i));let k=e[this._getAmfKey(u.aml.vocabularies.core.documentation,i)];k&&(Array.isArray(k)&&([k]=k),r.documentation=this.documentation(k,i));let w=e[this._getAmfKey(u.aml.vocabularies.apiContract.returns,i)];Array.isArray(w)&&(r.responses=w.map(P=>this.response(P,i)));let S=e[this._getAmfKey(u.aml.vocabularies.apiContract.callback,i)];Array.isArray(S)&&(r.callbacks=S.map(P=>this.callback(P,i)));let E=e[this._getAmfKey(u.aml.vocabularies.apiContract.server,i)];Array.isArray(E)&&(r.servers=E.map(P=>this.server(P)));let A=e[this._getAmfKey(u.aml.vocabularies.security.security,i)];Array.isArray(A)&&(r.security=A.map(P=>this.securityRequirement(P,i)));let _=e[this._getAmfKey(u.aml.vocabularies.apiContract.tag,i)];Array.isArray(_)&&_.length&&(r.tags=_.map(P=>this.tag(P,i)));let $=e[this._getAmfKey(u.aml.vocabularies.document.extends,i)];return Array.isArray($)&&$.length&&(r.extends=$.map(P=>this.parametrizedTrait(P,i))),r}tag(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),name:""},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=e[this._getAmfKey(u.aml.vocabularies.core.documentation,i)];return a&&(Array.isArray(a)&&([a]=a),r.documentation=this.documentation(a,i)),r}tagListItem(e,t){let i=t||e["@context"],r={id:e["@id"],name:""},s=this._getValue(e,u.aml.vocabularies.core.name,i);return s&&typeof s=="string"&&(r.name=s),r}callback(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.expression,i);o&&typeof o=="string"&&(r.expression=o);let a=e[this._getAmfKey(u.aml.vocabularies.apiContract.endpoint,i)];return a&&(Array.isArray(a)&&([a]=a),r.endpoint=this.endPoint(a,i)),r}request(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e),required:!1,headers:[],queryParameters:[],payloads:[],uriParameters:[],cookieParameters:[]},s=this._getValue(e,u.aml.vocabularies.core.description,i);s&&typeof s=="string"&&(r.description=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.required,i);o&&typeof o=="boolean"&&(r.required=o);let a=e[this._getAmfKey(u.aml.vocabularies.apiContract.queryString,i)];a&&(Array.isArray(a)&&([a]=a),r.queryString=this.unknownShape(a,void 0,i));let n=this[Ie](e,u.aml.vocabularies.apiContract.header,i);Array.isArray(n)&&n.length&&(r.headers=n.map(h=>this.parameter(h,i)));let l=this[Ie](e,u.aml.vocabularies.apiContract.parameter,i);Array.isArray(l)&&l.length&&(r.queryParameters=l.map(h=>this.parameter(h,i)));let d=this[Ie](e,u.aml.vocabularies.apiContract.uriParameter,i);Array.isArray(d)&&d.length&&(r.uriParameters=d.map(h=>this.parameter(h,i)));let p=this[Ie](e,u.aml.vocabularies.apiContract.cookieParameter,i);Array.isArray(p)&&p.length&&(r.cookieParameters=p.map(h=>this.parameter(h,i)));let m=this[Ie](e,u.aml.vocabularies.apiContract.payload,i);return Array.isArray(m)&&m.length&&(r.payloads=m.map(h=>this.payload(h,i))),r}response(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),headers:[],payloads:[],examples:[],links:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,u.aml.vocabularies.apiContract.statusCode,i);a&&typeof a=="string"&&(r.statusCode=a);let n=this[Ie](e,u.aml.vocabularies.apiContract.header,i);Array.isArray(n)&&n.length&&(r.headers=n.map(m=>this.parameter(m,i)));let l=this[Ie](e,u.aml.vocabularies.apiContract.payload,i);Array.isArray(l)&&l.length&&(r.payloads=l.map(m=>this.payload(m,i)));let d=e[this._getAmfKey(u.aml.vocabularies.apiContract.examples,i)];Array.isArray(d)&&d.length&&(r.examples=d.map(m=>this.example(m,i)));let p=e[this._getAmfKey(u.aml.vocabularies.apiContract.link,i)];return Array.isArray(p)&&p.length&&(r.links=p.map(m=>this.templatedLink(m,i))),r}payload(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),examples:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.mediaType,i);o&&typeof o=="string"&&(r.mediaType=o);let a=e[this._getAmfKey(u.aml.vocabularies.shapes.schema,i)];a&&(Array.isArray(a)&&([a]=a),r.schema=this.unknownShape(a,{trackedId:r.id},i));let n=e[this._getAmfKey(u.aml.vocabularies.apiContract.examples,i)];return Array.isArray(n)&&n.length&&(r.examples=n.map(l=>this.example(l,i))),r}templatedLink(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),mapping:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,u.aml.vocabularies.apiContract.operationId,i);a&&typeof a=="string"&&(r.operationId=a);let n=e[this._getAmfKey(u.aml.vocabularies.apiContract.server,i)];n&&(Array.isArray(n)&&([n]=n),r.server=this.server(n,i));let l=e[this._getAmfKey(u.aml.vocabularies.apiContract.mapping,i)];return l&&(l&&!Array.isArray(l)&&(l=[l]),l&&(r.mapping=l.map(d=>this.iriTemplateMapping(d,i)))),r}iriTemplateMapping(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.apiContract.templateVariable,i);s&&typeof s=="string"&&(r.templateVariable=s);let o=this._getValue(e,u.aml.vocabularies.apiContract.linkExpression,i);return o&&typeof o=="string"&&(r.linkExpression=o),r}parametrizedSecurityScheme(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(u.aml.vocabularies.security.scheme,i)];o&&(Array.isArray(o)&&([o]=o),r.scheme=this.securityScheme(o,i));let a=e[this._getAmfKey(u.aml.vocabularies.security.settings,i)];return a&&(Array.isArray(a)&&([a]=a),r.settings=this.securitySettings(a,i)),r}securitySchemeListItem(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),type:""},s=this._getValue(e,u.aml.vocabularies.security.type,i);s&&typeof s=="string"&&(r.type=s);let o=this._getValue(e,u.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,u.aml.vocabularies.core.displayName,i);return a&&typeof a=="string"&&(r.displayName=a),r}securityScheme(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),headers:[],queryParameters:[],responses:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.displayName,i);o&&typeof o=="string"&&(r.displayName=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let n=this._getValue(e,u.aml.vocabularies.security.type,i);n&&typeof n=="string"&&(r.type=n);let l=e[this._getAmfKey(u.aml.vocabularies.security.settings,i)];l&&(Array.isArray(l)&&([l]=l),r.settings=this.securitySettings(l,i));let d=e[this._getAmfKey(u.aml.vocabularies.apiContract.queryString,i)];d&&(Array.isArray(d)&&([d]=d),r.queryString=this.unknownShape(d,void 0,i));let p=this[Ie](e,u.aml.vocabularies.apiContract.header,i);Array.isArray(p)&&p.length&&(r.headers=p.map(f=>this.parameter(f,i)));let m=this[Ie](e,u.aml.vocabularies.apiContract.parameter,i);Array.isArray(m)&&m.length&&(r.queryParameters=m.map(f=>this.parameter(f,i)));let h=this[Ie](e,u.aml.vocabularies.apiContract.response,i);return Array.isArray(h)&&h.length&&(r.responses=h.map(f=>this.response(f,i))),r}securityRequirement(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),schemes:[]},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(u.aml.vocabularies.security.schemes,i)];return Array.isArray(o)&&o.length&&(r.schemes=o.map(a=>this.parametrizedSecurityScheme(a,i))),r}securitySettings(e,t){let i=t||e["@context"],r=this.readTypes(e["@type"],i);return r.includes(u.aml.vocabularies.security.OAuth1Settings)?this.oAuth1Settings(e,i):r.includes(u.aml.vocabularies.security.OAuth2Settings)?this.oAuth2Settings(e,i):r.includes(u.aml.vocabularies.security.ApiKeySettings)?this.apiKeySettings(e,i):r.includes(u.aml.vocabularies.security.HttpSettings)?this.httpSettings(e,i):r.includes(u.aml.vocabularies.security.OpenIdConnectSettings)?this.openIdConnectSettings(e,i):this.settings(e,i)}settings(e,t){let i=t||e["@context"];return{id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)}}oAuth1Settings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let o=this._getValue(e,u.aml.vocabularies.security.requestTokenUri,i);o&&typeof o=="string"&&(r.requestTokenUri=o);let a=this._getValue(e,u.aml.vocabularies.security.tokenCredentialsUri,i);a&&typeof a=="string"&&(r.tokenCredentialsUri=a);let n=this._getValueArray(e,u.aml.vocabularies.security.signature,i);return Array.isArray(n)&&n.length?r.signatures=n:r.signatures=[],r}oAuth2Settings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValueArray(e,u.aml.vocabularies.security.authorizationGrant,i);Array.isArray(s)&&s.length?r.authorizationGrants=s:r.authorizationGrants=[];let o=e[this._getAmfKey(u.aml.vocabularies.security.flows,i)];return Array.isArray(o)&&o.length?r.flows=o.map(a=>this.oAuth2Flow(a,i)):r.flows=[],r}oAuth2Flow(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),scopes:[],sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let o=this._getValue(e,u.aml.vocabularies.security.accessTokenUri,i);o&&typeof o=="string"&&(r.accessTokenUri=o);let a=this._getValue(e,u.aml.vocabularies.security.flow,i);a&&typeof a=="string"&&(r.flow=a);let n=this._getValue(e,u.aml.vocabularies.security.refreshUri,i);n&&typeof n=="string"&&(r.refreshUri=n);let l=e[this._getAmfKey(u.aml.vocabularies.security.scope,i)];return Array.isArray(l)&&l.length&&(r.scopes=l.map(d=>this.scope(d,i))),r}scope(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.core.description,i);return o&&typeof o=="string"&&(r.description=o),r}apiKeySettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,u.aml.vocabularies.security.in,i);return o&&typeof o=="string"&&(r.in=o),r}httpSettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.security.scheme,i);s&&typeof s=="string"&&(r.scheme=s);let o=this._getValue(e,u.aml.vocabularies.security.bearerFormat,i);return o&&typeof o=="string"&&(r.bearerFormat=o),r}openIdConnectSettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,u.aml.vocabularies.security.openIdConnectUrl,i);return s&&typeof s=="string"&&(r.url=s),r}sourceMap(e,t){let i=t||e["@context"],r=e[this._getAmfKey(u.aml.vocabularies.docSourceMaps.sources,i)];if(!r)return;Array.isArray(r)&&([r]=r);let s={id:r["@id"],types:this.readTypes(r["@type"])},o=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.synthesizedField,i)];Array.isArray(o)&&o.length&&(s.synthesizedField=o.map(m=>this.synthesizedField(m,i)));let a=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.lexical,i)];Array.isArray(a)&&a.length&&(s.lexical=a.map(m=>this.synthesizedField(m,i)));let n=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.trackedElement,i)];Array.isArray(n)&&n.length&&(s.trackedElement=this.synthesizedField(n[0],i));let l=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.autoGeneratedName,i)];Array.isArray(l)&&l.length&&(s.autoGeneratedName=l.map(m=>this.synthesizedField(m,i)));let d=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.parsedJsonSchema,i)];Array.isArray(d)&&d.length&&(s.parsedJsonSchema=this.synthesizedField(d[0],i));let p=r[this._getAmfKey(u.aml.vocabularies.docSourceMaps.declaredElement,i)];return Array.isArray(p)&&p.length&&(s.declaredElement=this.synthesizedField(p[0],i)),s}synthesizedField(e,t){if(typeof e=="string")return{id:"synthesizedField/generated",value:e};let i={id:e["@id"],value:""},r=this._getValue(e,u.aml.vocabularies.docSourceMaps.element,t);typeof r=="string"&&(i.element=r);let s=this._getValue(e,u.aml.vocabularies.docSourceMaps.value,t);return typeof s=="string"&&(i.value=s),i}parametrizedDeclaration(e,t){let i=t||e["@context"],r={id:e["@id"],types:this.readTypes(e["@type"],i),variables:[],customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i)},s=this._getValue(e,u.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(u.aml.vocabularies.document.variable,i)];Array.isArray(o)&&o.forEach(n=>{r.variables.push(this.variableValue(n,i))});let a=e[this._getAmfKey(u.aml.vocabularies.document.target,i)];if(Array.isArray(a)&&a.length){let[n]=a;r.target=this.abstractDeclaration(n,i)}return r}parametrizedTrait(e,t){let i=t||e["@context"];return this.parametrizedDeclaration(e,i)}parametrizedResourceType(e,t){let i=t||e["@context"];return this.parametrizedDeclaration(e,i)}variableValue(e,t){let i=t||e["@context"],r=this._getValue(e,u.aml.vocabularies.core.name,i),s={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),name:r},o=e[this._getAmfKey(u.aml.vocabularies.document.value,i)];if(Array.isArray(o)){let[a]=o;s.value=this.unknownDataNode(a,i)}return s}abstractDeclaration(e,t){let i=t||e["@context"],r=this._getValue(e,u.aml.vocabularies.core.name,i),s={id:e["@id"],types:this.readTypes(e["@type"],i),customDomainProperties:this.customDomainProperties(e,i),sourceMaps:this.sourceMap(e,i),name:r,variables:[]},o=this._getValueArray(e,u.aml.vocabularies.document.variable,i);Array.isArray(o)&&(s.variables=o);let a=this._getValue(e,u.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(s.description=a);let n=e[this._getAmfKey(u.aml.vocabularies.document.dataNode,i)];if(Array.isArray(n)){let[l]=n;s.dataNode=this.unknownDataNode(l,i)}return s}endPointWithOperationsListItem(e,t){let i=this._getValue(e,u.aml.vocabularies.apiContract.path,t),r={id:e["@id"],path:i,operations:[]},s=this[Ie](e,u.aml.vocabularies.apiContract.supportedOperation,t);Array.isArray(s)&&s.length&&(r.operations=s.map(a=>this.operationListItem(a,t)));let o=this._getValue(e,u.aml.vocabularies.core.name,t);return o&&typeof o=="string"&&(r.name=o),r}operationListItem(e,t){let i={id:e["@id"],method:""},r=this._getValue(e,u.aml.vocabularies.apiContract.method,t);r&&typeof r=="string"&&(i.method=r);let s=this._getValue(e,u.aml.vocabularies.core.name,t);return s&&typeof s=="string"&&(i.name=s),i}};var Ni=class c{mime;opts;generator;constructor(e,t={}){this.mime=e,this.opts=Object.freeze({...t}),e.includes("json")?this.generator=new ns(t):e.includes("xml")&&(this.generator=new cs(t))}static asExample(e,t,i){return new c(t,i).toExample(e)}static asSchema(e,t,i){return new c(t,i).toValue(e)}generate(e){let{generator:t}=this;if(t)return t.generate(e)}toValue(e){return this.generate(e)}toExample(e){let t=this.generate(e);if(t==null)return;let i={id:`${e.id}/generated`,strict:!0,types:[u.aml.vocabularies.apiContract.Example],mediaType:this.mime,renderValue:t,customDomainProperties:[]},r=e;if(Array.isArray(r.examples)&&r.examples.length){let[s]=r.examples;s.value&&(i.value=s.value)}return i}};var tr=Object.freeze({processApiLink:"amfprocessapilink",processBuffer:"amfprocessbuffer",processApiFile:"amfprocessapifile",selectApiMainFile:"amfselectapimainfile"});var Nm=Object.freeze({processApiLink:async(c,e,t,i,r=globalThis)=>{let s=new CustomEvent(tr.processApiLink,{bubbles:!0,composed:!0,cancelable:!0,detail:{url:c,mainFile:e,md5:t,packaging:i}});return r.dispatchEvent(s),s.detail.result},processBuffer:async(c,e,t=globalThis)=>{let i=new CustomEvent(tr.processBuffer,{bubbles:!0,composed:!0,cancelable:!0,detail:{buffer:c,opts:e}});return t.dispatchEvent(i),i.detail.result},processApiFile:async(c,e=globalThis)=>{let t=new CustomEvent(tr.processApiFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{file:c}});return e.dispatchEvent(t),t.detail.result},selectApiMainFile:async(c,e=globalThis)=>{let t=new CustomEvent(tr.selectApiMainFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{candidates:c}});return e.dispatchEvent(t),t.detail.result}});var Uc=["string","number","boolean","date","datetime","time","binary","json"],ls;(function(c){c.string="string",c.number="number",c.boolean="boolean",c.date="date",c.datetime="datetime",c.time="time",c.file="binary",c.json="json"})(ls||(ls={}));var Id=["required","multiple","primary","index","unique","search","readOnly","writeOnly","deprecated","immutable"],Pd=["required","multiple"],Rd=["float","double","int32","int64"];function qo(c,e){return c==="number"?e?.format==="int32"||e?.format==="int64"?u.w3.xmlSchema.integer:u.w3.xmlSchema.number:c==="boolean"?u.aml.vocabularies.shapes.boolean:c==="date"?u.w3.xmlSchema.date:c==="datetime"?u.w3.xmlSchema.dateTime:c==="time"?u.aml.vocabularies.shapes.dateTimeOnly:u.w3.xmlSchema.string}var Ti=Symbol("noValue"),ds=class{increment=0;static noValue=Ti;generate(e,t){return t==="string"?this.generateString(e):t==="number"?this.generateNumber(e):t==="date"?this.generateDate(e):t==="time"?this.generateTime(e):t==="datetime"?this.generateDateTime(e):Ti}generateString(e){switch(e){case"random":return W(8);case"uuid-v4":return crypto.randomUUID();default:return Ti}}generateNumber(e){return e==="incremental"?`${this.increment++}`:Ti}generateDate(e){if(e==="now"){let t=new Date,i=t.getFullYear(),r=`${t.getMonth()+1}`.padStart(2,"0"),s=`${t.getDate()}`.padStart(2,"0");return`${i}-${r}-${s}`}return Ti}generateTime(e){if(e==="now"){let t=new Date,i=`${t.getHours()}`.padStart(2,"0"),r=`${t.getMinutes()}`.padStart(2,"0"),s=`${t.getSeconds()}`.padStart(2,"0");return`${i}:${r}:${s}`}return Ti}generateDateTime(e){if(e==="now"){let t=new Date,i=t.getFullYear(),r=`${t.getMonth()+1}`.padStart(2,"0"),s=`${t.getDate()}`.padStart(2,"0"),o=`${t.getHours()}`.padStart(2,"0"),a=`${t.getMinutes()}`.padStart(2,"0"),n=`${t.getSeconds()}`.padStart(2,"0");return`${i}-${r}-${s}T${o}:${a}:${n}`}return Ti}};var zc="anyOf",Tm="allOf",jm="oneOf",Cm="not",Vc="string",$d="binary",bi=class{#e;get valueGenerator(){return this.#e||(this.#e=new ds),this.#e}entity(e,t=new Set){if(t.has(e.key))return this.createRecursiveShape(e);t.add(e.key);let i=Xe.nodeShape(e.key);i.id=e.key,this.updateBaseProperties(e,i),i.properties=[];for(let r of e.listProperties()){let s=r.readBinding("web");if(s&&s.hidden)continue;let o=this.property(r);i.properties.push(o)}for(let r of e.listAssociations()){let s=r.readBinding("web");if(s&&s.hidden)continue;let o=this.associationProperty(r,t);i.properties.push(o)}for(let r of e.listParents()){let s=this.entity(r,t);i.inherits.push(s)}return i}property(e){let{required:t,key:i}=e,r=Xe.propertyShape(i);return r.path=`${u.aml.vocabularies.data.key}${e.info.name}`,t&&(r.minCount=1),r.range=this.getRange(e),this.updateBaseProperties(e,r),r.range.name&&(r.name=r.range.name),r}associationProperty(e,t=new Set){let{required:i,key:r}=e,s=Xe.propertyShape(r);return s.path=`${u.aml.vocabularies.data.key}${e.info.name}`,i&&(s.minCount=1),s.range=this.associationShape(e,t),this.updateBaseProperties(e,s),s}associationShape(e,t=new Set){let i=e.schema;if(!i?.embedded)return this.createLinkedShape(e);let r=this.associationUnion(e,t);if(!r)return;if(Array.isArray(r))return this.createUnionShape(e,r);if((i&&i.unionType||zc)===Cm){let o=Xe.anyShape(e.key);return o.id=`not-shape-${e.key}`,o.not=r,o}return e.multiple?this.refactorShapeToArray(e.key,r):r}createLinkedShape(e){let t=Xe.scalarShape(e.key);return t.id=`link-${e.key}`,t.dataType=qo(Vc),t}createUnionShape(e,t){let i=Xe.unionShape(e.key);this.updateBaseProperties(e,i),i.anyOf=[];let r=e.schema&&e.schema.unionType||zc;return r===zc?i.anyOf=t:r===Tm?i.and=t:r===jm?i.xone=t:i.not=t[0],e.multiple?this.refactorShapeToArray(e.key,i):i}associationUnion(e,t=new Set){let i=[];for(let r of e.listTargets())i.push(this.entity(r,t));if(i.length)return i.length>1?i:i[0]}getRange(e){let t=e.readBinding("web"),i;e.schema&&(i=e.schema);let{multiple:r,type:s}=e;return r?this.createArrayShape(e,i,t):s===$d?this.createFileShape(e,t):this.createScalarShape(e,i,t)}setShapeSchema(e,t,i,r,s){if(i.defaultValue){let{type:o}=i.defaultValue,{value:a}=i.defaultValue;if(o==="function"){let n=this.valueGenerator.generate(a,e.type);if(n!==ds.noValue){let l=jt.scalar(n,o);t.defaultValue=l.toJSON()}}else{let n=jt.scalar(a,r);t.defaultValue=n.toJSON()}}Array.isArray(i.enum)&&(t.values=i.enum.map(o=>jt.scalar(o,r).toJSON())),Array.isArray(i.examples)&&(s?t.examples=this.createArrayExamples(i.examples,r):t.examples=this.createExamples(i.examples,r))}createArrayShape(e,t,i){let r=Xe.arrayShape(e.key),{type:s}=e;if(s===$d?r.items=this.createFileShape(e,i):r.items=this.createScalarShape(e,void 0,i),t){let o=r.items.dataType;this.setShapeSchema(e,r,t,o,e.multiple)}return r}createScalarShape(e,t,i){let r=Xe.scalarShape(e.key);return this.updateBaseProperties(e,r),this.setScalarCommonProperties(r,e,i),r.dataType||(r.dataType=qo(e.type,i)),t&&this.setShapeSchema(e,r,t,r.dataType,e.multiple),r}createExamples(e,t){let i=[];for(let r of e){let s={id:W(),customDomainProperties:[],strict:!0,types:[...es.IAmfExampleTypes],structuredValue:jt.scalar(r,t).toJSON()};i.push(s)}return i}createArrayExamples(e,t){let i={id:W(),customDomainProperties:[],strict:!0,types:[...es.IAmfExampleTypes]},r=new jt("array");for(let s of e){let o=jt.scalar(s,t);r.addMember(o)}return i.structuredValue=r.toJSON(),[i]}createFileShape(e,t){let i=Xe.fileShape(e.key);return this.updateBaseProperties(e,i),t&&(Array.isArray(t.fileTypes)&&(i.fileTypes=t.fileTypes),this.setScalarCommonProperties(i,e,t)),i}setScalarCommonProperties(e,t,i){i?.name&&(e.name=i.name),i?.xml&&(e.xmlSerialization=i.xml);let{schema:r,type:s}=t;if(r&&(r.pattern&&(e.pattern=r.pattern),typeof r.multipleOf=="number"&&(e.multipleOf=r.multipleOf),typeof r.minimum=="number"&&(s===Vc?e.minLength=r.minimum:e.minimum=r.minimum),typeof r.maximum=="number"&&(s===Vc?e.maxLength=r.maximum:e.maximum=r.maximum),typeof r.exclusiveMinimum=="boolean"&&(e.exclusiveMinimum=r.exclusiveMinimum),typeof r.exclusiveMaximum=="boolean"&&(e.exclusiveMaximum=r.exclusiveMaximum)),i?.format)switch(i.format){case"double":e.format=u.w3.xmlSchema.double;break;case"float":e.format=u.w3.xmlSchema.float;break;case"int32":e.format=u.w3.xmlSchema.integer;break;case"int64":e.format=u.w3.xmlSchema.integer;break}typeof t.readOnly=="boolean"&&(e.readOnly=t.readOnly),typeof t.writeOnly=="boolean"&&(e.writeOnly=t.writeOnly);let o=r?.examples&&r.examples.length>0,a=r?.defaultValue?.value!==void 0;if(t.required&&!t.readOnly&&!o&&!a){let n="";t.type==="number"?n=0:t.type==="boolean"&&(n=!1);let l=("dataType"in e?e.dataType:void 0)||qo(t.type,i);e.examples=this.createExamples([String(n)],l)}}updateBaseProperties(e,t){t.name=e.info.name,t.displayName=e.info.displayName,t.description=e.info.description,(e.kind===be||e.kind===O)&&(t.deprecated=e.deprecated)}createRecursiveShape(e){return Xe.recursiveShape(e.key,e.key)}refactorShapeToArray(e,t){let i=Xe.arrayShape(e);return i.items=t,i}};var ir=class extends b{static code="E_DOMAIN_SCHEMA";static status=400;static message="Invalid domain schema configuration.";static help="Ensure that the property and entity configurations do not violate schema constraints."};var ps=class extends b{static code="E_INVALID_TYPE";static status=422;static message="Invalid type.";static help="Make sure you are initializing the object with the correct data."};var ki=class c extends lt{kind;info;required;multiple;primary;unique;index;search;readOnly;immutable;writeOnly;deprecated;tags=[];semantics=[];type="string";jsonSchema;jsonIndex;schema;bindings=[];lineage;static createSchema(e={}){let{key:t=W(),multiple:i,required:r,type:s=ls.string,index:o,search:a,primary:n,unique:l,readOnly:d,writeOnly:p,immutable:m,tags:h,semantics:f,deprecated:k,schema:w,bindings:S,jsonSchema:E,jsonIndex:A,lineage:_}=e;if(d===!0&&m===!0){let L=e.info?.name||e.key||"property";throw new ir(`Property '${L}' cannot be both readOnly and immutable.`)}if(typeof s=="string"&&!Uc.includes(s))throw new ps(`Invalid data property type ${s}`);let $=he.fromJSON(e.info,{name:"new_property"}).toJSON(),P={kind:be,key:t,info:$,type:s};E&&(P.jsonSchema=structuredClone(E)),A&&(P.jsonIndex=structuredClone(A)),typeof i=="boolean"&&(P.multiple=i),typeof r=="boolean"&&(P.required=r),typeof o=="boolean"&&(P.index=o),typeof a=="boolean"&&(P.search=a),typeof n=="boolean"&&(P.primary=n),typeof l=="boolean"&&(P.unique=l);let j=d;return n===!0&&d===void 0&&m===void 0&&(j=!0),typeof j=="boolean"&&(P.readOnly=j),typeof m=="boolean"&&(P.immutable=m),typeof p=="boolean"&&(P.writeOnly=p),typeof k=="boolean"&&(P.deprecated=k),Array.isArray(h)&&(P.tags=[...h]),Array.isArray(f)&&(P.semantics=[...f]),w&&(P.schema=structuredClone(w)),Array.isArray(S)?P.bindings=S.map(L=>structuredClone(L)):P.bindings=[],_&&(P.lineage=structuredClone(_)),P}parent;constructor(e,t,i={}){let r=c.createSchema(i);super(e,r.key),this.parent=t,this.kind=be,this.info=new he(r.info),this.type=r.type,typeof r.multiple=="boolean"&&(this.multiple=r.multiple),typeof r.required=="boolean"&&(this.required=r.required),typeof r.index=="boolean"&&(this.index=r.index),typeof r.search=="boolean"&&(this.search=r.search),typeof r.deprecated=="boolean"&&(this.deprecated=r.deprecated),typeof r.primary=="boolean"&&(this.primary=r.primary),typeof r.unique=="boolean"&&(this.unique=r.unique),typeof r.readOnly=="boolean"&&(this.readOnly=r.readOnly),typeof r.immutable=="boolean"&&(this.immutable=r.immutable),typeof r.writeOnly=="boolean"&&(this.writeOnly=r.writeOnly),Array.isArray(r.tags)?this.tags=[...r.tags]:this.tags=[],Array.isArray(r.semantics)?this.semantics=[...r.semantics]:this.semantics=[],r.schema&&(this.schema=structuredClone(r.schema)),r.jsonSchema&&(this.jsonSchema=structuredClone(r.jsonSchema)),r.jsonIndex&&(this.jsonIndex=structuredClone(r.jsonIndex)),Array.isArray(r.bindings)?this.bindings=r.bindings.map(s=>structuredClone(s)):this.bindings=[],r.lineage&&(this.lineage=structuredClone(r.lineage))}static validate(e,t={}){if(!e||typeof e!="object"&&e!==null)return!1;let i=e;return!(t.strict&&i.kind!==be)}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON(),type:this.type||ls.string};return typeof this.index=="boolean"&&(e.index=this.index),typeof this.search=="boolean"&&(e.search=this.search),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),typeof this.primary=="boolean"&&(e.primary=this.primary),typeof this.unique=="boolean"&&(e.unique=this.unique),typeof this.multiple=="boolean"&&(e.multiple=this.multiple),typeof this.required=="boolean"&&(e.required=this.required),typeof this.readOnly=="boolean"&&(e.readOnly=this.readOnly),typeof this.immutable=="boolean"&&(e.immutable=this.immutable),typeof this.writeOnly=="boolean"&&(e.writeOnly=this.writeOnly),Array.isArray(this.tags)&&this.tags.length&&(e.tags=[...this.tags]),Array.isArray(this.semantics)&&this.semantics.length&&(e.semantics=this.semantics.map(t=>structuredClone(t))),this.schema&&(e.schema=structuredClone(this.schema)),this.jsonSchema&&(e.jsonSchema=structuredClone(this.jsonSchema)),this.jsonIndex&&(e.jsonIndex=structuredClone(this.jsonIndex)),Array.isArray(this.bindings)&&this.bindings.length&&(e.bindings=this.bindings.map(t=>structuredClone(t))),this.lineage&&(e.lineage=structuredClone(this.lineage)),e}remove(){this.getParentInstance()?.removeProperty(this.key)}getParentInstance(){return this.root.graph.node(this.parent)}static isValidType(e){return typeof e!="string"?!1:Uc.includes(e)}static isValidAttribute(e){return typeof e!="string"?!1:Id.includes(e)}static isValidFormat(e){return e===void 0?!0:typeof e!="string"?!1:!!Rd.includes(e)}ensureSchema(){return this.schema||(this.schema={}),this.schema}getWebBinding(){let e=this.bindings.find(t=>t.type==="web");return e||(e={type:"web",schema:{}},this.bindings.push(e)),e.schema}readWebBinding(){return this.bindings.find(t=>t.type==="web")?.schema}getExposedName(){let e=this.readWebBinding()?.name||this.info.name;if(!e)throw new b(`Property ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}readBinding(e){return this.bindings.find(i=>i.type===e)?.schema||void 0}toApiShape(){return new bi().property(this)}toExample(e,t={}){let i=this.toApiShape();return i.range?new Ni(e,{renderExamples:t.renderExamples??!0,renderMocked:t.renderMocked??!0,renderOptional:t.renderOptional??!0,selectedUnions:t.selectedUnions}).generate(i):void 0}getDefaultValue(){return Fc(this)}addSemantic(e){this.root.ensureWritable();let t=at[e.id];if(!Ao(t))throw new ps(`Invalid semantic type: ${e.id}. Expected a property semantic.`);let i=this.semantics.findIndex(r=>r.id===e.id);i>=0?this.semantics[i]=e:this.semantics.push(e)}removeSemantic(e){this.root.ensureWritable();let t=this.semantics.findIndex(i=>i.id===e);t>=0&&this.semantics.splice(t,1)}hasSemantic(e){return this.semantics.some(t=>t.id===e)}getSemantic(e){return this.semantics.find(t=>t.id===e)}duplicate(){let e=this.getParentInstance();if(!e)throw new ir(`Cannot duplicate property ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(l=>l.key===this.key);if(t===-1)throw new ir(`Cannot duplicate property ${this.key} as it does not exist on the parent entity fields list.`);let i=this.info.name||"field",r=e.generateUniqueName(i),s=this.toJSON();delete s.key,delete s.primary,delete s.lineage,s.info?s.info.name=r:s.info={name:r};let o=e.addProperty(s),a=e.fields.length-1,n=e.fields[a];return e.fields.splice(a,1),e.fields.splice(t+1,0,n),o}setLineage(e,t){this.lineage={id:t,key:e.key,kind:e.kind},e.namespace!==this.root.key&&(this.lineage.domain=e.namespace)}};function Fc(c,e){let t,i;if(typeof c=="string"?(t=c,i=e):(t=c.type,i=c.schema?.defaultValue),!i||i.value===void 0||i.type==="function")return;let r=i.value;if(r===null)return null;switch(t){case"number":{if(typeof r=="number")return r;if(typeof r=="string"){let s=r.trim();if(s!==""){let o=Number(s);if(!Number.isNaN(o))return o}}return r}case"boolean":{if(typeof r=="boolean")return r;if(typeof r=="string"){let s=r.trim().toLowerCase();if(s==="true")return!0;if(s==="false")return!1}return r}case"json":{if(typeof r=="object")return r;if(typeof r=="string")try{return JSON.parse(r)}catch{return r}return r}default:return typeof r=="string"?r:String(r)}}var vi=class extends b{static code="E_REMOVE_PROPERTY";static status=500;static message="Error removing a data property.";static help="Make sure the property exists and can be removed."};function Ve(c,e){if(!c.hasNode(e))return;let t=c.node(e);if(t){if(t.kind===se){c.removeNode(e);return}for(let i of c.children(e))Ve(c,i);for(let i of c.outEdges(e)){let r=c.edge(i);r&&(r.type==="association"||r.type==="property")&&Ve(c,i.w)}c.removeNode(e)}}var qc=[],Kc=[],Od={},us={},ms={};function Nd(c){return typeof c=="string"?new RegExp("^"+c+"$","i"):c}function Ko(c,e){return c===e?e:c===c.toLowerCase()?e.toLowerCase():c===c.toUpperCase()?e.toUpperCase():c[0]===c[0].toUpperCase()?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():e.toLowerCase()}function Dm(c,e){return c.replace(/\$(\d{1,2})/g,function(t,i){return e[i]||""})}function Lm(c,e){return c.replace(e[0],function(t,i){let r=Dm(e[1],arguments);return Ko(t===""?c[i-1]:t,r)})}function Td(c,e,t){if(!c.length||Object.hasOwn(Od,c))return e;let i=t.length;for(;i--;){let r=t[i];if(r[0].test(e))return Lm(e,r)}return e}function jd(c,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?Ko(i,r):Object.prototype.hasOwnProperty.call(c,r)?Ko(i,c[r]):Td(r,i,t)}}function Cd(c,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?!0:Object.prototype.hasOwnProperty.call(c,r)?!1:Td(r,r,t)===r}}var ze=function(c,e,t){let i=e===1?ze.singular(c):ze.plural(c);return(t?e+" ":"")+i};ze.plural=jd(ms,us,qc);ze.isPlural=Cd(ms,us,qc);ze.singular=jd(us,ms,Kc);ze.isSingular=Cd(us,ms,Kc);ze.addPluralRule=function(c,e){qc.push([Nd(c),e])};ze.addSingularRule=function(c,e){Kc.push([Nd(c),e])};ze.addUncountableRule=function(c){if(typeof c=="string"){Od[c.toLowerCase()]=!0;return}ze.addPluralRule(c,"$0"),ze.addSingularRule(c,"$0")};ze.addIrregularRule=function(c,e){e=e.toLowerCase(),c=c.toLowerCase(),ms[c]=e,us[e]=c};[["I","we"],["me","us"],["he","they"],["she","they"],["them","them"],["myself","ourselves"],["yourself","yourselves"],["itself","themselves"],["herself","themselves"],["himself","themselves"],["themself","themselves"],["is","are"],["was","were"],["has","have"],["this","these"],["that","those"],["my","our"],["its","their"],["his","their"],["her","their"],["echo","echoes"],["dingo","dingoes"],["volcano","volcanoes"],["tornado","tornadoes"],["torpedo","torpedoes"],["genus","genera"],["viscus","viscera"],["stigma","stigmata"],["stoma","stomata"],["dogma","dogmata"],["lemma","lemmata"],["schema","schemata"],["anathema","anathemata"],["ox","oxen"],["axe","axes"],["die","dice"],["yes","yeses"],["foot","feet"],["eave","eaves"],["goose","geese"],["tooth","teeth"],["quiz","quizzes"],["human","humans"],["proof","proofs"],["carve","carves"],["valve","valves"],["looey","looies"],["thief","thieves"],["groove","grooves"],["pickaxe","pickaxes"],["passerby","passersby"],["canvas","canvases"]].forEach(function(c){ze.addIrregularRule(c[0],c[1])});[[/s?$/i,"s"],[/[^\u0000-\u007F]$/i,"$0"],[/([^aeiou]ese)$/i,"$1"],[/(ax|test)is$/i,"$1es"],[/(alias|[^aou]us|t[lm]as|gas|ris)$/i,"$1es"],[/(e[mn]u)s?$/i,"$1s"],[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i,"$1"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1i"],[/(alumn|alg|vertebr)(?:a|ae)$/i,"$1ae"],[/(seraph|cherub)(?:im)?$/i,"$1im"],[/(her|at|gr)o$/i,"$1oes"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,"$1a"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i,"$1a"],[/sis$/i,"ses"],[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i,"$1$2ves"],[/([^aeiouy]|qu)y$/i,"$1ies"],[/([^ch][ieo][ln])ey$/i,"$1ies"],[/(x|ch|ss|sh|zz)$/i,"$1es"],[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i,"$1ices"],[/\b((?:tit)?m|l)(?:ice|ouse)$/i,"$1ice"],[/(pe)(?:rson|ople)$/i,"$1ople"],[/(child)(?:ren)?$/i,"$1ren"],[/eaux$/i,"$0"],[/m[ae]n$/i,"men"],["thou","you"]].forEach(function(c){ze.addPluralRule(c[0],c[1])});[[/s$/i,""],[/(ss)$/i,"$1"],[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i,"$1fe"],[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i,"$1f"],[/ies$/i,"y"],[/(dg|ss|ois|lk|ok|wn|mb|th|ch|ec|oal|is|ck|ix|sser|ts|wb)ies$/i,"$1ie"],[/\b(l|(?:neck|cross|hog|aun)?t|coll|faer|food|gen|goon|group|hipp|junk|vegg|(?:pork)?p|charl|calor|cut)ies$/i,"$1ie"],[/\b(mon|smil)ies$/i,"$1ey"],[/\b((?:tit)?m|l)ice$/i,"$1ouse"],[/(seraph|cherub)im$/i,"$1"],[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i,"$1"],[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i,"$1sis"],[/(movie|twelve|abuse|e[mn]u)s$/i,"$1"],[/(test)(?:is|es)$/i,"$1is"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1us"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i,"$1um"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i,"$1on"],[/(alumn|alg|vertebr)ae$/i,"$1a"],[/(cod|mur|sil|vert|ind)ices$/i,"$1ex"],[/(matr|append)ices$/i,"$1ix"],[/(pe)(rson|ople)$/i,"$1rson"],[/(child)ren$/i,"$1"],[/(eau)x?$/i,"$1"],[/men$/i,"man"]].forEach(function(c){ze.addSingularRule(c[0],c[1])});["adulthood","advice","agenda","aid","aircraft","alcohol","ammo","analytics","anime","athletics","audio","bison","blood","bream","buffalo","butter","carp","cash","chassis","chess","clothing","cod","commerce","cooperation","corps","debris","diabetes","digestion","elk","energy","equipment","excretion","expertise","firmware","flounder","fun","gallows","garbage","graffiti","hardware","headquarters","health","herpes","highjinks","homework","housework","information","jeans","justice","kudos","labour","literature","machinery","mackerel","mail","media","mews","moose","music","mud","manga","news","only","personnel","pike","plankton","pliers","police","pollution","premises","rain","research","rice","salmon","scissors","series","sewage","shambles","shrimp","software","staff","swine","tennis","traffic","transportation","trout","tuna","wealth","welfare","whiting","wildebeest","wildlife","you",/pok[eé]mon$/i,/[^aeiou]ese$/i,/deer$/i,/fish$/i,/measles$/i,/o[iu]s$/i,/pox$/i,/sheep$/i].forEach(ze.addUncountableRule);var Et=ze;function Mm(c,e,t){let i=c.getExposedName(),r=i.charAt(0).toLowerCase()+i.slice(1),s=Et(r),o=new Set(Array.from(e.listFields()).map(n=>n.info.name).filter(Boolean)),a=o.has(s)?t.getExposedName():s;return o.has(a)&&(a=e.generateUniqueName(a)),a}var rr=class c extends lt{kind;info;link;bindings=[];_required;_multiple;_semantics=[];_schema;_onDelete;_readOnly;get required(){return this.link?this.getLinkedAssociation()?.required:this._required}set required(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set required on linked association "${this.key}". Required status is owned by the link target "${this.link?.key}".`);this._required=e}get multiple(){return this.link?this.getLinkedAssociation()?.multiple:this._multiple}set multiple(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set multiple on linked association "${this.key}". Multiplicity is owned by the link target "${this.link?.key}".`);this._multiple=e}get schema(){return this.link?this.getLinkedAssociation()?.schema:this._schema}set schema(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set schema on linked association "${this.key}". Schema is owned by the link target "${this.link?.key}".`);this._schema=e}parent;targets;get semantics(){if(this.link){let e=this.getLinkedAssociation();return Object.freeze(e?[...e.semantics]:[])}return this._semantics}set semantics(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set semantics on linked association "${this.key}". Semantics are owned by the link target "${this.link?.key}".`);this._semantics=e}get onDelete(){return this.link?this.getLinkedAssociation()?.onDelete:this._onDelete}set onDelete(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set onDelete on linked association "${this.key}". onDelete rule is owned by the link target "${this.link?.key}".`);this._onDelete=e}get readOnly(){return this.link?this.getLinkedAssociation()?.readOnly:this._readOnly}set readOnly(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot set readOnly on linked association "${this.key}". readOnly flag is owned by the link target "${this.link?.key}".`);this._readOnly=e}fields;static createSchema(e={}){let{key:t=W(),semantics:i=[]}=e,r=he.fromJSON(e.info,{name:"new_association"}).toJSON(),s={kind:se,key:t,info:r};return e.link&&(s.link=structuredClone(e.link)),Array.isArray(i)&&(s.semantics=[...i]),e.onDelete&&(s.onDelete=e.onDelete),typeof e.readOnly=="boolean"&&(s.readOnly=e.readOnly),e.schema&&(s.schema=structuredClone(e.schema)),typeof e.multiple=="boolean"&&(s.multiple=e.multiple),typeof e.required=="boolean"&&(s.required=e.required),Array.isArray(e.bindings)&&(s.bindings=e.bindings.map(o=>structuredClone(o))),Array.isArray(e.targets)&&(s.targets=e.targets.map(o=>({...o}))),Array.isArray(e.fields)&&(s.fields=[...e.fields]),s}constructor(e,t,i){let r=c.createSchema(i);super(e,r.key),this.parent=t,this.kind=se,this.info=new he(r.info),r.link&&(this.link=structuredClone(r.link)),r.schema&&(this._schema=structuredClone(r.schema)),typeof r.multiple=="boolean"&&(this._multiple=r.multiple),typeof r.required=="boolean"&&(this._required=r.required),Array.isArray(r.bindings)?this.bindings=r.bindings.map(s=>structuredClone(s)):this.bindings=[],Array.isArray(r.targets)?this.targets=r.targets.map(s=>({...s})):this.targets=[],Array.isArray(r.semantics)?this._semantics=r.semantics.map(s=>structuredClone(s)):this._semantics=[],r.onDelete&&(this._onDelete=r.onDelete),Array.isArray(r.fields)?this.fields=[...r.fields]:this.fields=[],typeof r.readOnly=="boolean"&&(this._readOnly=r.readOnly)}isLinked(){return!!this.link}getLinkedAssociation(e=new Set){if(!this.link)return;if(e.has(this.key))throw new Error(`Circular association link detected involving association key "${this.key}".`);e.add(this.key);let t=!this.link.domain||this.link.domain===this.root.key?this.root:this.root.dependencies.get(this.link.domain);if(!t)return;let i=t.graph.node(this.link.key);if(!i||i.kind!==se)return;let r=i;return r.isLinked()?r.getLinkedAssociation(e):r}addProperty(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot add property to linked association "${this.key}". Properties are owned by the link target "${this.link?.key}".`);if(e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a property ${e.key}, but it already exists`);let t=new ki(this.root,this.key,e);return this.root.graph.setNode(t.key,t),this.root.graph.setEdge(this.key,t.key,{type:"property"}),this.fields.push({type:"property",key:t.key}),t}get properties(){return this.listProperties()}*listProperties(){if(this.link){let e=this.getLinkedAssociation();e&&(yield*e.listProperties());return}for(let{key:e}of this.fields){let t=this.root.graph.node(e);!t||t.kind!==be||(yield t)}}removeProperty(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot remove property from linked association "${this.key}". Properties are owned by the link target "${this.link?.key}".`);let t=this.fields.findIndex(r=>r.key===e&&r.type==="property");if(!this.root.graph.hasNode(e))throw new vi(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new vi(`Trying to remove the ${e} property, but it doesn't belong to this association`);Ve(this.root.graph,e),t!==-1&&this.fields.splice(t,1)}generateUniqueName(e){let t=new Set;for(let s of this.listProperties())s.info.name&&t.add(s.info.name);let i=2,r=`${e}_copy`;for(;t.has(r);)r=`${e}_copy_${i}`,i++;return r}toJSON(){if(this.link){let t={kind:this.kind,key:this.key,info:this.info.toJSON(),link:structuredClone(this.link)};return Array.isArray(this.targets)&&this.targets.length&&(t.targets=this.targets.map(i=>({...i}))),Array.isArray(this.bindings)&&this.bindings.length&&(t.bindings=this.bindings.map(i=>structuredClone(i))),t}let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return this.schema&&(e.schema=structuredClone(this.schema)),typeof this.multiple=="boolean"&&(e.multiple=this.multiple),typeof this.required=="boolean"&&(e.required=this.required),Array.isArray(this.bindings)&&this.bindings.length&&(e.bindings=this.bindings.map(t=>structuredClone(t))),Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),Array.isArray(this.targets)&&this.targets.length&&(e.targets=this.targets.map(t=>({...t}))),Array.isArray(this.semantics)&&this.semantics.length&&(e.semantics=this.semantics.map(t=>structuredClone(t))),this.onDelete&&(e.onDelete=this.onDelete),typeof this.readOnly=="boolean"&&this.readOnly&&(e.readOnly=this.readOnly),e}getParentInstance(){return this.root.graph.node(this.parent)}remove(){this.getParentInstance()?.removeAssociation(this.key)}ensureSchema(){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot ensure schema on linked association "${this.key}". Schema is owned by the link target "${this.link?.key}".`);return this.schema||(this.schema={}),this.schema}static isValidAttribute(e){return typeof e!="string"?!1:Pd.includes(e)}getWebBinding(){this.root.ensureWritable();let e=this.bindings.find(t=>t.type==="web");return e||(e={type:"web",schema:{}},this.bindings.push(e)),e.schema}readWebBinding(){return this.bindings?.find(t=>t.type==="web")?.schema}getExposedName(){let e=this.readWebBinding()?.name||this.info.name;if(!e)throw new b(`Association ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}readBinding(e){return this.bindings.find(i=>i.type===e)?.schema||void 0}addTarget(e,t){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot add targets to linked association "${this.key}". Targets are determined by the reciprocal relationship with "${this.link?.key}".`);let i;if(typeof e=="string"?i=e:(i=e.key,e.domain.key!==this.root.key&&(t=e.domain.key)),t&&t===this.root.key&&(t=void 0),this.targets.some(a=>a.key===i&&a.domain===t)){let a=`Target ${i} already exists.`;throw new Error(a)}if(t&&!this.root.dependencies.has(t))throw new Error(`Foreign namespace "${t}" does not exist.`);let r={key:i};t&&(r.domain=t),this.targets.push(r);let s=t?`${t}:${i}`:i,o={type:"association"};t&&(o.domain=t,o.foreign=!0),this.root.graph.setEdge(this.key,s,o),this.synchronizePeerReciprocalAssociations()}removeTarget(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot remove targets from linked association "${this.key}". Targets are determined by the reciprocal relationship with "${this.link?.key}".`);let t;typeof e=="string"?t=e:t=e.key;let i=this.targets.findIndex(r=>r.key===t);i>=0&&this.targets.splice(i,1),this.root.graph.removeEdge(this.key,t),this.synchronizePeerReciprocalAssociations()}*listTargets(){for(let e of this.targets){let{key:t,domain:i}=e,r=i?`${i}:${t}`:t,s=this.root.graph.node(r);s&&(yield s)}}toApiShape(){return new bi().associationProperty(this)}checkPreconditions(e){let t=at[e];if(!(!t||!Xi(t)||!t.preconditions||t.preconditions.length===0)){for(let i of t.preconditions)if(i.kind==="associationMultiple"){if(this.multiple!==i.multiple)throw new b(i.unmetMessage||`Semantic ${e} requires association multiple to be ${i.multiple}.`,{status:400})}else if(i.kind==="entityPairs"){let r=this.getParentInstance(),s=Array.from(this.listTargets());if(!r)throw new b(i.unmetMessage||`Parent entity is required to evaluate entity pairing preconditions for semantic ${e}.`,{status:400});if(!i.entityPairs.some(a=>(Array.isArray(a.parent)?a.parent.some(d=>r.hasSemantic(d)):r.hasSemantic(a.parent))?s.some(d=>Array.isArray(a.target)?a.target.some(p=>d.hasSemantic(p)):d.hasSemantic(a.target)):!1))throw new b(i.unmetMessage||`Association entity pairing precondition check failed for semantic ${e}.`,{status:400})}}}getReciprocalAssociations(e){let t=[],i=this.getParentInstance()?.key;if(!i)return t;let r=this.root.getIncomingAssociations(i);for(let s of r)if(s.key!==this.key){if(s.link&&s.link.key===this.key&&(!e||s.hasSemantic(e))){t.push(s);continue}for(let o of s.semantics)if(o.link&&o.link.key===this.key&&(!e||o.id===e)){t.push(s);break}}return t}toggleOptionalSemanticProperty(e,t,i){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot toggle edge properties on linked reciprocal association "${this.key}". Edge properties belong to the source of truth association.`);let r=at[e];if(!r||!Xi(r))throw new Error(`Invalid semantic type: ${e}. Expected an association semantic.`);if(this.getSemantic(e)?.link)throw new Error(`Cannot toggle edge properties on linked reciprocal semantic ${e}. Edge properties belong to the source of truth association.`);let o=r.properties?.find(l=>l.value.info?.name===t);if(!o)throw new Error(`Property "${t}" is not defined in semantic blueprint ${e}.`);let n=Array.from(this.listProperties()).find(l=>l.info.name===t||l.lineage?.id===e&&l.info.name===t);if(i){if(n)return n;let l={...o.value,lineage:{key:this.key,kind:se,domain:this.root.key,id:e}};return this.addProperty(l)}else{n&&n.remove();return}}addSemantic(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot add semantics to linked association "${this.key}". Semantics are owned by the link target "${this.link?.key}".`);let t=at[e.id];if(!Xi(t))throw new Error(`Invalid semantic type: ${e.id}. Expected an association semantic.`);this.checkPreconditions(e.id);let i=this.semantics.findIndex(r=>r.id===e.id);i>=0?this.semantics[i]=e:this.semantics.push(e),e.link||t.properties?.forEach(r=>{if(!r.meta.required)return;let s=r.value.info?.name;if(!Array.from(this.listProperties()).find(a=>a.info.name===s||a.lineage?.id===e.id&&a.info.name===s)){let a={...r.value,lineage:{key:this.key,kind:se,domain:this.root.key,id:e.id}};this.addProperty(a)}}),this.synchronizePeerReciprocalAssociations()}removeSemantic(e){if(this.root.ensureWritable(),this.isLinked())throw new Error(`Cannot remove semantics from linked association "${this.key}". Semantics are owned by the link target "${this.link?.key}".`);let t=this.getReciprocalAssociations(e),i=this.semantics.findIndex(s=>s.id===e);i>=0&&this.semantics.splice(i,1);let r=Array.from(this.listProperties()).filter(s=>s.lineage?.id===e);for(let s of r)s.remove();for(let s of t)s.isLinked()?s.remove():(s.removeSemantic(e),s.semantics.length===0&&s.remove());e===g.PeerRelation&&this.synchronizePeerReciprocalAssociations()}hasSemantic(e){return this.link?this.getLinkedAssociation()?.hasSemantic(e)??!1:this._semantics.some(t=>t.id===e)}getSemantic(e){return this.link?this.getLinkedAssociation()?.getSemantic(e):this._semantics.find(t=>t.id===e)}isManyToMany(){return this.link?this.getLinkedAssociation()?.isManyToMany()??!1:this.multiple?this.semantics.some(e=>{let t=at[e.id];return!!t&&Xi(t)&&t.isManyToMany===!0}):!1}isManyToManyLinkReciprocal(){return this.multiple?this.link?this.isManyToMany():this.semantics.some(e=>{if(!e.link)return!1;let t=at[e.id];return!!t&&Xi(t)&&t.isManyToMany===!0}):!1}isLinkedReciprocal(e){return this.link?!e||this.hasSemantic(e):this.semantics.some(t=>t.link?!e||t.id===e:!1)}synchronizePeerReciprocalAssociations(){if(this.root.readOnly||this.isLinked())return;let e=this.getSemantic(g.PeerRelation);if(!e)return;if(!(e.config?.symmetry==="mutual")){let a=this.getReciprocalAssociations(g.PeerRelation);for(let n of a)n.remove();return}let i=this.getParentInstance();if(!i)return;let r=Array.from(this.listTargets()),s=new Set(r.map(a=>a.key)),o=this.getReciprocalAssociations(g.PeerRelation);for(let a of o){let n=a.getParentInstance();(!n||!s.has(n.key))&&a.remove()}for(let a of r){if(a.domain.key!==this.root.key)throw new b(`Cannot apply symmetry "mutual" on association "${this.getExposedName()}": target entity "${a.info.getLabel()}" belongs to foreign domain "${a.domain.key}". Reciprocal associations cannot be synthesized on read-only foreign domains. Use symmetry "directed" or target only local entities.`,{status:400});if(Array.from(a.listAssociations()).some(p=>p.link&&p.link.key===this.key||p.semantics.some(m=>m.id===g.PeerRelation&&m.link?.key===this.key)))continue;let l=Mm(i,a,this),d=i.info.displayName?Et(i.info.displayName):l;a.addAssociation({info:{name:l,displayName:d},targets:[{key:i.key}],link:{kind:se,key:this.key}})}}duplicate(){if(this.isLinked())throw new Error(`Cannot duplicate linked association "${this.key}". Duplicate the primary association instead.`);let e=this.getParentInstance();if(!e)throw new Error(`Cannot duplicate association ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(l=>l.key===this.key);if(t===-1)throw new Error(`Cannot duplicate association ${this.key} as it does not exist on the parent entity fields list.`);let i=this.info.name||"field",r=e.generateUniqueName(i),s=this.toJSON();delete s.key,delete s.targets,delete s.fields,s.info?s.info.name=r:s.info={name:r};let o=e.addAssociation(s);for(let l of this.listProperties()){let d=l.toJSON();delete d.key,o.addProperty(d)}for(let l of this.targets)o.addTarget(l.key,l.domain);let a=e.fields.length-1,n=e.fields[a];return e.fields.splice(a,1),e.fields.splice(t+1,0,n),o}};var ji=class extends Error{messages;status=422;code="E_VALIDATION_ERROR";constructor(e,t){let i=t?.message||"Validation failure";super(i,t),this.messages=e;let r=this.constructor;"captureStackTrace"in Error&&Error.captureStackTrace(this,r)}get[Symbol.toStringTag](){return this.constructor.name}toString(){return`${this.name} [${this.code}]: ${this.message}`}};var sr=class c extends lt{kind;#e;#t;#i;#r;info;tags;semantics=[];fields;deprecated;static createSchema(e={}){let{key:t=W(),tags:i,semantics:r,fields:s,deprecated:o}=e,a=he.fromJSON(e.info,{name:"new_entity"}).toJSON(),n={kind:O,key:t,info:a};return Array.isArray(i)&&(n.tags=[...i]),Array.isArray(r)&&(n.semantics=[...r]),Array.isArray(s)&&(n.fields=[...s]),typeof o=="boolean"&&(n.deprecated=o),n}constructor(e,t){let i=c.createSchema(t);super(e,i.key),this.kind=O,this.info=new he(i.info),Array.isArray(i.tags)?this.tags=[...i.tags]:this.tags=[],Array.isArray(i.semantics)?this.semantics=i.semantics.map(r=>structuredClone(r)):this.semantics=[],Array.isArray(i.fields)?this.fields=[...i.fields]:this.fields=[],typeof i.deprecated=="boolean"&&(this.deprecated=i.deprecated)}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),Array.isArray(this.semantics)&&this.semantics.length&&(e.semantics=this.semantics.map(t=>structuredClone(t))),Array.isArray(this.tags)&&this.tags.length&&(e.tags=[...this.tags]),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),e}getParentInstance(){let e=this.root.graph.parent(this.key);if(e)return this.root.graph.node(e)}getExposedName(){let e=this.info.name;if(!e)throw new b(`Entity ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}getDatabaseTableName(){return Il(this.getExposedName(),this.namespace)}addProperty(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a property ${e.key}, but it already exists`);let t=new ki(this.root,this.key,e);return this.root.graph.setNode(t.key,t),this.root.graph.setEdge(this.key,t.key,{type:"property"}),this.fields.push({type:"property",key:t.key}),t}removeProperty(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new vi(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new vi(`Trying to remove the ${e} property, but it doesn't belong to this entity`);Ve(this.root.graph,e),this.removeField(e)}get properties(){return this.listProperties()}*listProperties(){for(let{key:e,type:t}of this.fields){if(t!=="property")continue;let i=this.root.graph.node(e);!i||i.kind!==be||(yield i)}}withInheritedProperties(){if(this.root.readOnly&&this.#e)return this.#e.values();let e=new Map,t=this.listAllParents("up");for(let i of t)for(let r of i.properties)r.info.name&&e.set(r.info.name,r);for(let i of this.properties)i.info.name&&e.set(i.info.name,i);return this.root.readOnly&&(this.#e=Array.from(e.values())),e.values()}hasProperties(){return this.fields.some(e=>e.type==="property")}get parents(){return this.listParents()}*listParents(){for(let e of this.root.graph.outEdges(this.key)){let t=this.root.graph.edge(e);if(!t||t.type!=="parent")continue;let i=this.root.graph.node(e.w);i&&(yield i)}}listAllParents(e="up"){if(this.root.readOnly&&this.#t?.[e])return this.#t[e];let t=new Set,i=[],r=[...this.listParents()],s=0;for(;s<r.length;){let o=r[s++];t.has(o.key)||(t.add(o.key),i.push(o),r.push(...o.listParents()))}return e==="down"&&i.reverse(),this.root.readOnly&&(this.#t||(this.#t={}),this.#t[e]=i),i}addParent(e,t){this.root.ensureWritable();let i=this.domain.buildReferenceKey(e,t);if(i===this.key){let s="Entity cannot be a parent of itself";throw new ji([{field:"parents",message:s,rule:"circular"}],{message:s})}let{graph:r}=this.root;if(!r.hasNode(i)){let s=`Entity with key "${e}" not found`;throw t&&(s+=` in domain "${t}"`),new ji([{field:"parents",message:s,rule:"required"}],{message:s})}if(this.hasCircularParent(i)){let s=`Circular inheritance detected. Cannot add ${e} as a parent`;throw new ji([{field:"parents",message:s,rule:"circular"}],{message:s})}if(r.outEdges(this.key,i).next().value){let s=`Parent ${e} already exists`;throw new ji([{field:"parents",message:s,rule:"unique"}],{message:s})}return t?r.setEdge(this.key,i,{type:"parent",domain:t,foreign:!0}):r.setEdge(this.key,i,{type:"parent"}),this}removeParent(e,t){this.root.ensureWritable();let{graph:i}=this.root,r=this.domain.buildReferenceKey(e,t);if(!i.hasEdge(this.key,r)){let o=`Trying to remove a parent ${e} from ${this.key}, but it doesn't exist`;throw t&&(o=`Trying to remove a foreign parent ${e} from domain "${t}" from ${this.key}, but it doesn't exist`),new Error(o)}let s=i.edge(this.key,r);if(!s||s.type!=="parent"){let o=`Edge between ${this.key} and ${e} exists but is not a parent relationship`;throw t&&(o=`Edge between ${this.key} and ${e} in domain "${t}" exists but is not a parent relationship`),new Error(o)}return i.removeEdge(this.key,r),this}hasParents(){for(let e of this.root.graph.outEdges(this.key))if(this.root.graph.edge(e)?.type==="parent")return!0;return!1}hasCircularParent(e){let{graph:t}=this.root;for(let r of t.outEdges(e,this.key))if(t.edge(r)?.type==="parent")return!0;let i=t.node(e);for(;i;){if(i.key===this.key)return!0;let r=[...i.listParents()];if(r.length===0)break;i=r[0]}return!1}breadcrumbs(){let e=[];e.push({key:this.key,name:this.info.getLabel("Unnamed entity"),kind:O});let t=this.getParentInstance();if(t){e.push({key:t.key,kind:t.kind,name:t.info.getLabel("Unnamed model")});let i=t.getParentInstance();for(;i&&i!==this.root;)e.push({key:i.key,kind:i.kind,name:i.info.getLabel("Unnamed namespace")}),i=i.getParentInstance()}return e.push({key:this.root.key,name:this.root.info.getLabel("Unnamed data domain"),kind:this.root.kind}),e.reverse()}addAssociation(e={}){this.root.ensureWritable();let{graph:t}=this.root,i={...e},r=i.targets;delete i.targets;let s=Array.isArray(r)&&r.length;if(s)for(let a of r){if(!a.key)throw new Error("Missing key for target");if(a.domain&&a.domain!==this.root.key){let n=`${a.domain}:${a.key}`;if(!t.hasNode(n))throw new Error(`Foreign entity ${n} not found`)}else if(!t.hasNode(a.key))throw new Error(`Target entity ${a.key} not found`)}let o=new rr(this.root,this.key,i);if(t.setNode(o.key,o),t.setEdge(this.key,o.key,{type:"association"}),s)if(o.isLinked())for(let a of r){let n=a.domain?`${a.domain}:${a.key}`:a.key,l={key:a.key};a.domain&&(l.domain=a.domain),o.targets.push(l);let d={type:"association"};a.domain&&(d.domain=a.domain,d.foreign=!0),t.setEdge(o.key,n,d)}else for(let a of r)o.addTarget(a.key,a.domain);return this.fields.push({type:"association",key:o.key}),o.synchronizePeerReciprocalAssociations(),o}addLinkedAssociation(e,t){let i=e.getParentInstance();if(!i)throw new Error(`Cannot link to association "${e.key}" because it has no parent entity.`);let r=i.domain.key!==this.root.key?i.domain.key:void 0,s={key:i.key};r&&(s.domain=r);let o={kind:se,key:e.key};return r&&(o.domain=r),this.addAssociation({info:t,targets:[s],link:o})}removeAssociation(e){if(this.root.ensureWritable(),!this.root.graph.hasEdge(this.key,e))throw new Error(`Unable to find a connection between this entity and the ${e} association`);let t=this.root.graph.edge(this.key,e);if(!t||t.type!=="association")throw new Error(`Association ${e} does not exist`);let i=this.root.graph.node(e);if(i){let r=i.getReciprocalAssociations();for(let s of r)s.remove()}Ve(this.root.graph,e),this.removeField(e)}get associations(){return this.listAssociations()}*listAssociations(){for(let{key:e,type:t}of this.fields){if(t!=="association")continue;let i=this.root.graph.node(e);!i||i.kind!==se||(yield i)}}hasAssociations(){return this.fields.some(e=>e.type==="association")}*listFields(){for(let{key:e}of this.fields){let t=this.root.graph.node(e);t&&(t.kind===se||t.kind===be)&&(yield t)}}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}toApiShape(){return new bi().entity(this)}toExample(e,t={}){let i=this.toApiShape();return new Ni(e,{renderExamples:t.renderExamples??!0,renderMocked:t.renderMocked??!0,renderOptional:t.renderOptional??!0,selectedUnions:t.selectedUnions}).generate(i)}isChildOf(e){if(this.key===e)return!1;let t=this.getParentInstance();return t?t.key===e?!0:t.isChildOf(e):!1}primaryKey(){for(let t of this.properties)if(t.primary)return t;let e;for(let t of this.listParents()){let i=t.primaryKey();i&&(e=i)}return e}addSemantic(e){this.root.ensureWritable();let t=at[e.id];if(!Sl(t))throw new Error(`Invalid semantic type: ${e.id}. Expected an entity semantic.`);let i=this.semantics.findIndex(r=>r.id===e.id);i>=0?this.semantics[i]=e:this.semantics.push(e),t.properties?.forEach(r=>{r.meta.required&&this.addProperty(r.value)})}removeSemantic(e){this.root.ensureWritable();let t=this.semantics.findIndex(i=>i.id===e);t>=0&&this.semantics.splice(t,1)}hasSemantic(e){return this.semantics.some(t=>t.id===e)}getSemantic(e){return this.semantics.find(t=>t.id===e)}withInheritedAssociations(){if(this.root.readOnly&&this.#i)return this.#i.values();let e=new Map,t=this.listAllParents("up");for(let i of t)for(let r of i.associations)r.info.name&&e.set(r.info.name,r);for(let i of this.associations)i.info.name&&e.set(i.info.name,i);return this.root.readOnly&&(this.#i=Array.from(e.values())),e.values()}listAllSemantics(){if(this.root.readOnly&&this.#r)return this.#r;let e=new Map,t=this.listAllParents("up");for(let r of t)for(let s of r.semantics)e.set(s.id,s);for(let r of this.semantics)e.set(r.id,r);let i=Array.from(e.values());return this.root.readOnly&&(this.#r=i),i}generateUniqueName(e){let t=new Set;for(let s of this.listFields())s.info.name&&t.add(s.info.name);let i=2,r=`${e}_copy`;for(;t.has(r);)r=`${e}_copy_${i}`,i++;return r}*getSystemFields(){let e=this.root.getIncomingAssociations(this.key);for(let t of e){if(!t.multiple||t.isManyToMany())continue;let i=t.getParentInstance();if(!i)continue;let r=i.primaryKey();if(!r)continue;yield{name:Pl({entityName:i.getExposedName(),assocName:t.getExposedName(),pkName:r.getExposedName()}),primaryKey:r,sourceEntity:i,association:t}}}};var or=class extends b{static code="E_REMOVE_ENTITY";static status=500;static message="Error removing a data entity.";static help="Make sure the entity exists and can be removed."};var Qe=class extends b{static code="E_ATTACH";static status=500;static message="Error attaching the object.";static help="Make sure you are attaching the right object."};var Ut=class extends b{static code="E_DETACH";static status=500;static message="Error detaching the object.";static help="Make sure you are detaching the right object."};var wi=class c extends lt{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=W(),fields:i,deprecated:r}=e,s=he.fromJSON(e.info,{name:"New model"}).toJSON(),o={kind:Oe,key:t,info:s};return Array.isArray(i)&&(o.fields=[...i]),typeof r=="boolean"&&(o.deprecated=r),o}constructor(e,t){let i=c.createSchema(t);super(e,i.key),this.kind=Oe,this.info=new he(i.info),Array.isArray(i.fields)?this.fields=[...i.fields]:this.fields=[],typeof i.deprecated=="boolean"?this.deprecated=i.deprecated:this.deprecated=void 0}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),e}getParentInstance(){let e=this.root.graph.parent(this.key);return e?this.root.graph.node(e):this.root}addEntity(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Entity with key ${e?.key} already exists`);let t=new sr(this.root,e);return this.root.graph.setNode(t.key,t),this.root.graph.setParent(t.key,this.key),this.fields.push({key:t.key,type:"entity"}),t}removeEntity(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new or(`Trying to remove the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==O)throw new or(`Trying to remove the ${e} entity, but it is not an entity`);if(t.getParentInstance()!==this)throw new or(`Trying to remove the ${e} entity, but it is not a child of this model`);Ve(this.root.graph,e),this.removeField(e)}attachEntity(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Qe(`Trying to attach the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==O)throw new Qe(`Trying to attach the ${e} entity, but it is not a entity`);if(t.domain.key!==this.root.key)throw new Qe(`Trying to attach the ${e} entity, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Qe(`Trying to attach the ${e} entity, but it is already a child of this model`);if(i.detachEntity(e),this.fields.some(s=>s.key===e)||this.fields.push({type:"entity",key:e}),this.root.graph.setParent(e,this.key),this.root.graph.parent(e)!==this.key)throw new Qe(`Trying to attach the ${e} entity, but it is not a child of this model`);return this}detachEntity(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e);if(t===-1)throw new Ut(`Trying to detach the ${e} entity, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==O)throw new Ut(`Trying to detach the ${e} entity, but it is not an entity`);if(i.getParentInstance()!==this)throw new Ut(`Trying to detach the ${e} entity, but it is not a child of this model`);return this.fields.splice(t,1),this.root.graph.setParent(e),this}*listEntities(){for(let{key:e,type:t}of this.fields){if(t!=="entity")continue;let i=this.root.graph.node(e);!i||i.kind!==O||(yield i)}}hasEntities(){return this.fields.some(e=>e.type==="entity")}breadcrumbs(){let e=[];e.push({key:this.key,name:this.info.getLabel("Unnamed model"),kind:Oe});let t=this.getParentInstance();for(;t&&t!==this.root;)e.push({key:t.key,kind:t.kind,name:t.info.getLabel("Unnamed namespace")}),t=t.getParentInstance();return e.push({key:this.root.key,name:this.root.info.getLabel("Unnamed data domain"),kind:this.root.kind}),e.reverse()}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}isChildOf(e){if(this.key===e)return!1;let t=this.getParentInstance();return t?t.key===e?!0:t===this.root?!1:t.isChildOf(e):!1}};var Ci=class extends b{static code="E_REMOVE_NAMESPACE";static status=500;static message="Error removing a domain namespace.";static help="Make sure the namespace exists and can be removed."};var hs=class extends b{static code="E_REMOVE_MODEL";static status=500;static message="Error removing a domain model.";static help="Make sure the model exists and can be removed."};var ar=class c extends lt{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=W(),fields:i,deprecated:r}=e,s=he.fromJSON(e.info,{name:"New namespace"}).toJSON(),o={kind:Le,key:t,info:s};return Array.isArray(i)&&(o.fields=[...i]),typeof r=="boolean"&&(o.deprecated=r),o}constructor(e,t){let i=c.createSchema(t);super(e,i.key),this.kind=Le,this.info=new he(i.info),Array.isArray(i.fields)?this.fields=[...i.fields]:this.fields=[],typeof i.deprecated=="boolean"?this.deprecated=i.deprecated:this.deprecated=void 0}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON()};return Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),e}addNamespace(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a namespace to ${this.key}, but it already exists`);let t=new c(this.root,e);return this.root.graph.setNode(t.key,t),this.root.graph.setParent(t.key,this.key),this.fields.push({type:"namespace",key:t.key}),t}removeNamespace(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Ci(`Trying to remove the ${e} namespace, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Le)throw new Ci(`Trying to remove the ${e} namespace, but it is not a namespace`);return Ve(this.root.graph,e),this.removeField(e),this}attachNamespace(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Error(`Trying to attach the ${e} namespace, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Le)throw new Error(`Trying to attach the ${e} namespace, but it is not a namespace`);if(t.domain.key!==this.root.key)throw new Error(`Trying to attach the ${e} namespace, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Qe(`Trying to attach the ${e} entity, but it is already a child of this model`);return this.root!==i&&i.detachNamespace(e),this.fields.push({type:"namespace",key:e}),this.root.graph.setParent(e,this.key),this}detachNamespace(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e);if(t===-1)throw new Ci(`Trying to detach the ${e} namespace, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Le)throw new Ci(`Trying to detach the ${e} namespace, but it is not a namespace`);return this.fields.splice(t,1),this.root.graph.setParent(e),this}*listNamespaces(){for(let{key:e,type:t}of this.fields){if(t!=="namespace")continue;let i=this.root.graph.node(e);!i||i.kind!==Le||(yield i)}}hasNamespaces(){return this.fields.some(e=>e.type==="namespace")}addModel(e){if(this.root.ensureWritable(),e&&e.key&&this.root.graph.hasNode(e.key))throw new Error(`Trying to add a model to ${this.key}, but it already exists`);let t=new wi(this.root,e);return this.root.graph.setNode(t.key,t),this.root.graph.setParent(t.key,this.key),this.fields.push({type:"model",key:t.key}),t}removeModel(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new hs(`Trying to remove the ${e} model, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Oe)throw new hs(`Trying to remove the ${e} model, but it is not a model`);return Ve(this.root.graph,e),this.removeField(e),this}attachModel(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Qe(`Trying to attach the ${e} model, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Oe)throw new Qe(`Trying to attach the ${e} model, but it is not a model`);if(t.domain.key!==this.root.key)throw new Qe(`Trying to attach the ${e} model, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Qe(`Trying to attach the ${e} model, but it is already a child of this namespace`);return this.root!==i&&i.detachModel(e),this.fields.push({type:"model",key:e}),this.root.graph.setParent(e,this.key),this}detachModel(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e);if(t===-1)throw new Ut(`Trying to detach the ${e} model, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Oe)throw new Ut(`Trying to detach the ${e} model, but it is not a model`);if(i.getParentInstance()!==this)throw new Ut(`Trying to detach the ${e} model, but it is not a child of this namespace`);return this.fields.splice(t,1),this.root.graph.setParent(e),this}*listModels(){for(let{key:e,type:t}of this.fields){if(t!=="model")continue;let i=this.root.graph.node(e);!i||i.kind!==Oe||(yield i)}}hasModels(){return this.fields.some(e=>e.type==="model")}getParentInstance(){let e;for(let t of this.root.graph.parents(this.key)){e=t;break}return e?this.root.graph.node(e):this.root}*listFields(){for(let{key:e}of this.fields){let t=this.root.graph.node(e);t&&(t.kind===Le||t.kind===Oe)&&(yield t)}}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}isChildOf(e){if(this.key===e)return!1;let t=this.getParentInstance();return t?t.key===e?!0:t===this.root?!1:t.isChildOf(e):!1}};function nr(c,e,t){return c+""+e+""+(t||"\0")}function Bc(c,e,t){let i={v:c,w:e};return t&&(i.name=t),i}var Bo=class c{isDirectedValue;isMultigraphValue;isCompoundValue;graphLabelValue;nodesValue;#e;get parentValue(){if(!this.isCompoundValue)throw new Error("Cannot access parentValue in a non-compound graph");return this.#e||(this.#e=new Map),this.#e}#t;get childrenValue(){if(!this.isCompoundValue)throw new Error("Cannot access childrenValue in a non-compound graph");return this.#t||(this.#t=new Map),this.#t}inValue;predecessorsValue;outValue;successorsValue;edgeObjectsValue;edgeLabelsValue;nodeCountValue;edgeCountValue;constructor(e={}){this.isDirectedValue=typeof e.directed=="boolean"?e.directed:!0,this.isMultigraphValue=typeof e.multigraph=="boolean"?e.multigraph:!1,this.isCompoundValue=typeof e.compound=="boolean"?e.compound:!1,this.graphLabelValue=void 0,this.nodesValue=new Map,this.isCompoundValue&&this.childrenValue.set("\0",new Set),this.inValue=new Map,this.outValue=new Map,this.predecessorsValue=new Map,this.successorsValue=new Map,this.edgeObjectsValue=new Map,this.edgeLabelsValue=new Map,this.nodeCountValue=0,this.edgeCountValue=0,this.defaultNodeLabelFn=()=>{},this.defaultEdgeLabelFn=()=>{}}isDirected(){return this.isDirectedValue}isMultigraph(){return this.isMultigraphValue}isCompound(){return this.isCompoundValue}setGraph(e){return this.graphLabelValue=e,this}graph(){return this.graphLabelValue}defaultNodeLabelFn(e){}defaultEdgeLabelFn(e,t,i){}setDefaultNodeLabel(e){return typeof e=="function"?this.defaultNodeLabelFn=e:this.defaultNodeLabelFn=()=>e,this}nodeCount(){return this.nodeCountValue}nodes(){return this.nodesValue.keys()}*sources(){for(let e of this.nodes()){let t=this.inValue.get(e);(!t||t.size===0)&&(yield e)}}*sinks(){for(let e of this.nodes()){let t=this.outValue.get(e);(!t||t.size===0)&&(yield e)}}setNodes(e,t){if(typeof t>"u")for(let i of e)this.setNode(i);else for(let i of e)this.setNode(i,t);return this}setNode(e,t){return this.nodesValue.has(e)?(t&&this.nodesValue.set(e,t),this):(this.nodesValue.set(e,t||this.defaultNodeLabelFn(e)),this.isCompoundValue&&(this.parentValue.set(e,new Set(["\0"])),this.childrenValue.set(e,new Set),this.childrenValue.get("\0").add(e)),this.inValue.set(e,new Map),this.predecessorsValue.set(e,new Map),this.outValue.set(e,new Map),this.successorsValue.set(e,new Map),++this.nodeCountValue,this)}node(e){return this.nodesValue.get(e)}hasNode(e){return this.nodesValue.has(e)}removeNode(e){if(!this.hasNode(e))return this;if(this.nodesValue.delete(e),this.isCompoundValue){this.removeFromParentsChildList(e),this.parentValue.delete(e);for(let r of this.children(e))this.removeParent(r,e);this.childrenValue.delete(e)}let t=this.inValue.get(e);if(t){for(let r of t.keys()){let s=this.edgeObjectsValue.get(r);s&&this.removeEdge(s)}this.inValue.delete(e)}this.predecessorsValue.delete(e);let i=this.outValue.get(e);if(i){for(let r of i.keys()){let s=this.edgeObjectsValue.get(r);s&&this.removeEdge(s)}this.outValue.delete(e)}return this.successorsValue.delete(e),this.nodeCountValue-=1,this}setParent(e,t="\0"){if(!this.isCompoundValue)throw new Error("Cannot set parent in a non-compound graph");return t!=="\0"&&(this.checkParentCycle(e,t),this.nodesValue.has(t)||this.setNode(t)),this.nodesValue.has(e)||this.setNode(e),this.removeFromParentsChildList(e),this.parentValue.set(e,new Set),this.parentValue.get(e).add(t),this.childrenValue.has(t)||this.childrenValue.set(t,new Set),this.childrenValue.get(t).add(e),this}checkParentCycle(e,t){for(let i of this.parents(t)){if(i===e)throw new Error(`Setting ${t} as parent of ${e} would create a cycle`);this.checkParentCycle(e,i)}}addParent(e,t){if(!this.isCompoundValue)throw new Error("Cannot set parent in a non-compound graph");return this.checkParentCycle(e,t),this.nodesValue.has(t)||this.setNode(t),this.nodesValue.has(e)||this.setNode(e),this.parentValue.has(e)||this.parentValue.set(e,new Set),this.parentValue.get(e).add(t),this.childrenValue.has(t)||this.childrenValue.set(t,new Set),this.childrenValue.get(t).add(e),this}removeParent(e,t){if(!this.isCompoundValue)throw new Error("Cannot remove parent in a non-compound graph");return this.nodesValue.has(e)?(t?(this.childrenValue.get(t)?.delete(e),this.parentValue.get(e)?.delete(t)):(this.removeFromParentsChildList(e),this.parentValue.set(e,new Set),this.parentValue.get(e).add("\0"),this.childrenValue.get("\0").add(e)),this):this}removeFromParentsChildList(e){let t=this.parentValue.get(e);if(t)for(let i of t)this.childrenValue.get(i)?.delete(e)}*parents(e){if(this.isCompoundValue){let t=this.parentValue.get(e);if(t)for(let i of t)i!=="\0"&&(yield i)}}hasParents(e){for(let t of this.parents(e))return!0;return!1}hasParent(e,t){if(this.isCompoundValue){let i=this.parentValue.get(e);if(i)return i.has(t)}return!1}parent(e){for(let t of this.parents(e))return t}*children(e="\0"){if(this.isCompoundValue){let t=this.childrenValue.get(e);if(t)for(let i of t.keys())yield i}else if(e==="\0")for(let t of this.nodes())yield t}hasChildren(e="\0"){if(this.isCompoundValue){let t=this.childrenValue.get(e);if(!t)return!1;for(let i of t.keys())return!0;return!1}else if(e==="\0"){for(let t of this.nodes())return!0;return!1}return!1}*predecessors(e){let t=this.predecessorsValue.get(e);if(t)for(let i of t.keys())yield i}*successors(e){let t=this.successorsValue.get(e);if(t)for(let i of t.keys())yield i}*neighbors(e){if(!this.hasNode(e))return;let t=new Set;for(let i of this.predecessors(e))t.has(i)||(t.add(i),yield i);for(let i of this.successors(e))t.has(i)||(t.add(i),yield i)}isLeaf(e){if(this.isDirected()){for(let t of this.successors(e))return!1;return!0}for(let t of this.neighbors(e))return!1;return!0}filterNodes(e){let t=new c({directed:this.isDirectedValue,multigraph:this.isMultigraphValue,compound:this.isCompoundValue}),i=this.graph();t.setGraph(i);let r=new Set;if(this.nodesValue.forEach((s,o)=>{e(o)&&(t.setNode(o,s),r.add(o))}),this.edgeObjectsValue.forEach(s=>{r.has(s.v)&&r.has(s.w)&&t.setEdge(s,this.edge(s))}),this.isCompoundValue){let s=new Map;for(let o of t.nodes()){let a=[...this.parents(o)],n=[];for(;a.length>0;){let l=!1;for(let p of a)t.hasNode(p)&&(n.push(p),l=!0);if(l)break;let d=[];for(let p of a)for(let m of this.parents(p))d.push(m);a=d}n.length===0&&n.push("\0"),s.set(o,n)}for(let[o,a]of s){this.removeParent(o);for(let n of a)t.addParent(o,n)}}return t}setDefaultEdgeLabel(e){return typeof e=="function"?this.defaultEdgeLabelFn=e:this.defaultEdgeLabelFn=()=>e,this}edgeCount(){return this.edgeCountValue}edges(){return this.edgeObjectsValue.values()}setPath(e,t){if(!Array.isArray(e)||!e.length)return this;let i=arguments.length>1;return e.reduce((r,s)=>(i?this.setEdge(r,s,t):this.setEdge(r,s),s)),this}setEdge(e,t,i,r){if(typeof e=="object"&&e!==null&&"v"in e){let s=e;arguments.length>1?this._setEdge({loop:0},s,t):this._setEdge({loop:0},s)}else if(typeof t=="string"){let s=Bc(e,t,r);arguments.length>2?this._setEdge({loop:0},s,i):this._setEdge({loop:0},s)}else throw new Error("Invalid arguments for setEdge");return this}_setEdge(e,t,i){let r=!1,s;arguments.length>2&&(s=i,r=!0);let o=nr(t.v,t.w,t.name);if(this.edgeLabelsValue.has(o)){if(r&&this.edgeLabelsValue.set(o,s),e.loop===0&&!this.isDirectedValue&&t.w!==t.v){let p=Bc(t.w,t.v,t.name);r?this._setEdge({loop:1},p,i):this._setEdge({loop:1},p)}return}if(t.name&&!this.isMultigraphValue)throw new Error("Cannot set a named edge when isMultigraph = false");this.hasNode(t.v)||this.setNode(t.v),this.hasNode(t.w)||this.setNode(t.w);let n=r?s:this.defaultEdgeLabelFn(t.v,t.w,t.name);this.edgeLabelsValue.set(o,n),this.edgeObjectsValue.set(o,t);let l=this.predecessorsValue.get(t.w);if(l){let p=(l.get(t.v)||0)+1;l.set(t.v,p)}let d=this.successorsValue.get(t.v);if(d){let p=(d.get(t.w)||0)+1;d.set(t.w,p)}if(this.inValue.get(t.w).set(o,t),this.outValue.get(t.v).set(o,t),this.edgeCountValue++,e.loop===0&&!this.isDirectedValue&&t.w!==t.v){let p=Bc(t.w,t.v,t.name);r?this._setEdge({loop:1},p,i):typeof n=="object"&&n!==null?this._setEdge({loop:1},p,n):this._setEdge({loop:1},p)}}edge(e,t,i){let r;return typeof e=="object"?r=nr(e.v,e.w,e.name):r=nr(e,t,i),this.edgeLabelsValue.get(r)}hasEdge(e,t,i){let r;return typeof e=="object"?r=nr(e.v,e.w,e.name):r=nr(e,t,i),this.edgeLabelsValue.has(r)}removeEdge(e,t,i){return typeof e=="object"?this._removeEdge({loop:0},e.v,e.w,e.name):this._removeEdge({loop:0},e,t,i),this}_removeEdge(e,t,i,r){let s=nr(t,i,r),o=this.edgeObjectsValue.get(s);if(o){this.edgeLabelsValue.delete(s),this.edgeObjectsValue.delete(s);let a=this.predecessorsValue.get(o.w);if(a){let l=(a.get(o.v)||0)-1;l<=0?a.delete(o.v):a.set(o.v,l)}let n=this.successorsValue.get(o.v);if(n){let l=(n.get(o.w)||0)-1;l<=0?n.delete(o.w):n.set(o.w,l)}this.inValue.get(o.w)?.delete(s),this.outValue.get(o.v)?.delete(s),this.edgeCountValue--}!this.isDirectedValue&&e.loop===0&&this._removeEdge({loop:1},i,t,r)}*inEdges(e,t){let i=this.inValue.get(e);if(i){let r=i.values();if(!t){for(let s of r)yield s;return}for(let s of r)s.v===t&&(yield s)}}*outEdges(e,t){let i=this.outValue.get(e);if(!i)return;let r=i.values();if(!t){for(let s of r)yield s;return}for(let s of r)s.w===t&&(yield s)}*nodeEdges(e,t){for(let i of this.inEdges(e,t))yield i;for(let i of this.outEdges(e,t))i.v!==i.w&&(yield i)}};function Um(c,e){let t=[];for(let i of c.nodes()){let r=c.node(i);if(!r||r.domain.key!==e)continue;let s=[...c.parents(i)],o={v:i};o.value=r.toJSON(),s.length&&(o.parents=s),t.push(o)}return t}function zm(c,e){let t=[];for(let i of c.edges()){let r=c.edge(i);if(!r)continue;let s=c.node(i.v),o=c.node(i.w);if(!s||!o||s.domain.key!==e||o.domain.key!==e&&r.type!=="association"&&r.type!=="parent")continue;let a={v:i.v,w:i.w};i.name&&(a.name=i.name),a.value=structuredClone(r),t.push(a)}return t}function Vm(c,e){let t=[],i=new Set;for(let r of c.nodes()){let s=c.node(r);s&&s.domain.key===e&&i.add(r)}for(let r of i){let s=c.node(r);if(s){if(s.kind===be||s.kind===se){let a=[...c.inEdges(r)].filter(n=>{let l=c.node(n.v);return l&&l.domain.key===e});if(a.length===0){let n=s.kind===be?"Property":"Association";t.push(`${n} "${s.info.name}" (${r}) has no parent entity edge. This will cause deserialization to fail.`)}else if(a.length>1){let n=s.kind===be?"Property":"Association",l=a.map(d=>d.v).join(", ");t.push(`${n} "${s.info.name}" (${r}) has multiple parent edges: ${l}. This may cause deserialization issues.`)}else{let n=a[0],l=c.node(n.v);if(!l||l.kind!==O&&l.kind!==se){let d=s.kind===be?"Property":"Association";t.push(`${d} "${s.info.name}" (${r}) has a parent that is not an entity or association. Parent: ${l?.kind||"unknown"} (${n.v})`)}}}if(s.kind===O&&([...c.parents(r)].some(n=>{let l=c.node(n);return l&&l.kind===Oe})||t.push(`Entity "${s.info.name}" (${r}) has no model parent. Entities must belong to a model.`)),s.kind===Oe){let o=[...c.parents(r)],a=o.some(n=>{let l=c.node(n);return l&&l.kind===Le});if(o.length>0&&!a){let n=o.map(l=>`${c.node(l)?.kind||"unknown"} (${l})`).join(", ");t.push(`Model "${s.info.name}" (${r}) has invalid parent types: ${n}. Models can only belong to namespaces or be at root level.`)}}}}for(let r of i){let s=c.node(r);if(s&&s.kind===se){let o=s,n=[...c.outEdges(r)].filter(l=>{let d=c.edge(l);return d&&d.type==="association"});n.length;for(let l of n){let d=c.node(l.w);d?d.kind!==O&&t.push(`Association "${o.info.name}" (${r}) references non-entity target: ${d.kind} (${l.w})`):t.push(`Association "${o.info.name}" (${r}) references non-existent target: ${l.w}`)}}}if(t.length>0)throw new Error(`Graph consistency validation failed for domain "${e}":
|
|
52
52
|
`+t.map(r=>` - ${r}`).join(`
|
|
53
|
-
`))}function Ld(c,e){return Vm(c,e),{options:{directed:c.isDirected(),multigraph:c.isMultigraph(),compound:c.isCompound()},nodes:Um(c,e),edges:zm(c,e)}}function Md(c,e){for(let t of c.nodes()){let i=c.node(t);i&&i.domain.key===e&&c.removeNode(t)}}function Gc(c,e,t){let i=new Set,r=new Set;for(let o of e.nodes()){let a=e.node(o);if(!a)continue;let n=`${t}:${o}`;c.setNode(n,a),i.add(n)}for(let o of e.edges()){let a=e.edge(o);if(!a)continue;let n=`${t}:${o.v}`,l=`${t}:${o.w}`;c.setEdge(n,l,{foreign:!0,domain:t,...a}),r.add(`${n}|${l}`)}let s=new Set;for(let o of e.nodes()){let a=`${t}:${o}`;for(let n of e.parents(o)){let l=`${t}:${n}`,d=c.node(a),p=c.node(l);d.kind===$&&p.kind===$?s.has(a)?c.addParent(a,l):(s.add(a),c.setParent(a,l)):c.setParent(a,l)}}return{nodes:i,edges:r}}function Dd(c,e){for(let t of e)if(t.w===c)return t.v}function Fm(c,e,t,i,r){if(!e){let o={type:"malformed_entry",severity:"error",message:"Unable to restore data domain graph. Malformed node entry"};if(r.push(o),i==="strict")throw new Error(o.message);return}let s=e;if(!s.kind){let o={type:"malformed_entry",severity:"error",message:"Unable to restore data domain graph. Node entry missing kind property",affectedKey:s.key};if(r.push(o),i==="strict")throw new Error(o.message);return}try{if(s.kind===Le)return new ar(c,s);if(s.kind===Oe)return new wi(c,s);if(s.kind===$)return new sr(c,s);if(s.kind===be){let a=s,n=Dd(a.key,t);if(!n){let l={type:"missing_edge",severity:"error",message:`Property "${a.info?.name||a.key}" has no parent entity edge`,affectedKey:a.key,resolution:i==="lenient"?"Property will be skipped":void 0};if(r.push(l),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new ki(c,n,a)}if(s.kind===se){let a=s,n=Dd(a.key,t);if(!n){let l={type:"missing_edge",severity:"error",message:`Association "${a.info?.name||a.key}" has no parent entity edge`,affectedKey:a.key,resolution:i==="lenient"?"Association will be skipped":void 0};if(r.push(l),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new rr(c,n,a)}let o={type:"unknown_kind",severity:"error",message:`Unknown node kind: ${s.kind}`,affectedKey:s.key};if(r.push(o),i==="strict")throw new Error(`Unable to restore data domain graph. Unknown node kind ${s.kind}`);return}catch(o){let a={type:"malformed_entry",severity:"error",message:`Failed to create node: ${o instanceof Error?o.message:String(o)}`,affectedKey:s.key};if(r.push(a),i==="strict")throw o;return}}function Ud(c,e={}){let{json:t,dependencies:i,mode:r="strict"}=e,s=new Bo({compound:!0,multigraph:!0,directed:!0}),o=[],a=new Set,n=new Set;if(i)for(let d of i)try{let p=Gc(s,d.graph,d.key);p.edges.size&&(n=new Set([...n,...p.edges])),p.nodes.size&&(a=new Set([...a,...p.nodes])),c.dependencies.set(d.key,d)}catch(p){let m=`Failed to merge dependency "${d.key}": ${p instanceof Error?p.message:String(p)}`;if(r==="strict")throw new Error(m,{cause:p});let h={type:"missing_dependency",severity:"error",message:m,affectedKey:d.key,resolution:"Dependency will be skipped"};o.push(h)}if(!t)return{graph:s,issues:o,success:!0};if(Array.isArray(t.nodes)){let d=new Map;for(let p of t.nodes){let m=Fm(c,p.value,t.edges,r,o);m&&(s.setNode(p.v,m),p.parents&&d.set(p.v,p.parents))}for(let[p,m]of d){if(!s.hasNode(p)){let h={type:"missing_node",severity:"warning",message:`Cannot set parents for missing node: ${p}`,affectedKey:p,resolution:"Parent relationship will be skipped"};o.push(h);continue}for(let h of m){if(!s.hasNode(h)){let f={type:"missing_node",severity:"warning",message:`Parent node "${h}" not found for child "${p}"`,affectedKey:p,context:{parentKey:h},resolution:"Parent relationship will be skipped"};o.push(f);continue}try{s.setParent(p,h)}catch(f){let w={type:"invalid_parent",severity:"warning",message:`Failed to set parent "${h}" for child "${p}": ${f instanceof Error?f.message:String(f)}`,affectedKey:p,context:{parentKey:h},resolution:"Parent relationship will be skipped"};o.push(w)}}}}if(Array.isArray(t.edges))for(let d of t.edges){if(!d.value){let p="Edge entry missing value";if(r==="strict")throw new Error(p);let m={type:"malformed_entry",severity:"error",message:p,context:{edge:d}};o.push(m);continue}if(d.value.foreign&&!a.has(d.w)){let p={type:"missing_node",severity:"warning",message:`Missing foreign node: ${d.w}`,affectedKey:d.w,resolution:"Edge will be skipped"};o.push(p);continue}if(a.has(d.v)||a.has(d.w)){if(!s.hasNode(d.v)||!s.hasNode(d.w)){let p={type:"missing_node",severity:"warning",message:`Missing foreign node for edge: ${d.v} -> ${d.w}`,context:{sourceNode:d.v,targetNode:d.w},resolution:"Edge will be skipped"};o.push(p);continue}}else{if(!s.hasNode(d.v)){let p={type:"missing_node",severity:"warning",message:`Source node not found for edge: ${d.v}`,affectedKey:d.v,resolution:"Edge will be skipped"};o.push(p);continue}if(!s.hasNode(d.w)){let p={type:"missing_node",severity:"warning",message:`Target node not found for edge: ${d.w}`,affectedKey:d.w,resolution:"Edge will be skipped"};o.push(p);continue}}try{s.setEdge({v:d.v,w:d.w,name:d.name},d.value)}catch(p){let h={type:"malformed_entry",severity:"warning",message:`Failed to create edge ${d.v} -> ${d.w}: ${p instanceof Error?p.message:String(p)}`,context:{sourceNode:d.v,targetNode:d.w},resolution:"Edge will be skipped"};o.push(h)}}for(let d of s.nodes()){let p=s.node(d);if(p){if(p.kind===be){let m=p,h=m.parent?s.node(m.parent):void 0;h&&Array.isArray(h.fields)&&(h.fields.some(k=>k.key===m.key&&k.type==="property")||h.fields.push({type:"property",key:m.key}))}else if(p.kind===se){let m=p,h=m.parent?s.node(m.parent):void 0;h&&Array.isArray(h.fields)&&(h.fields.some(k=>k.key===m.key&&k.type==="association")||h.fields.push({type:"association",key:m.key}))}}}let l=o.some(d=>d.severity==="error");return{graph:s,issues:o,success:!l}}var cr=class extends EventTarget{dependencies=new Map;dependencyList=[];constructor(e=[],t=[]){super(),this.dependencyList=[...e];for(let i of t)this.dependencies.set(i.key,i)}};var Me=class c extends cr{kind;key;graph;info;lifecycle;previousVersion;#e=!0;#t=!1;readOnly;get domain(){return this}#i;get fields(){return this.#i}set fields(e){this.#i=e}issues=[];static createSchema(e={}){let{key:t=W(),fields:i,lifecycle:r="draft",previousVersion:s}=e,o=he.fromJSON(e.info,{name:"Unnamed domain"}).toJSON(),a={kind:Ee,key:t,info:o,lifecycle:r};return s&&(a.previousVersion=s),e.dependencyList&&(a.dependencyList=structuredClone(e.dependencyList)),e.graph&&(a.graph=e.graph),Array.isArray(i)&&(a.fields=[...i]),a}constructor(e,t=[],i){let r=c.createSchema(e),s=[];for(let n of t)if(n instanceof c)n.readOnly?s.push(n):(console.warn(`Domain ${n.key} is not read only, cloning it. This may have performance implications.`),s.push(n.clone({readOnly:!0})));else if(typeof n=="object"&&n.kind===Ee&&n.key){let l=new c(n,void 0,{readOnly:!0});s.push(l)}else throw new Error(`Invalid foreign domain dependency: ${n}`);super(r.dependencyList,s),this.kind=r.kind,this.key=r.key,this.info=new he(r.info),this.readOnly=i?.readOnly||!1,this.lifecycle=r.lifecycle||"draft",this.previousVersion=r.previousVersion;let o=i?.mode||"strict",a=Ud(this,{json:r.graph,dependencies:s,mode:o});this.graph=a.graph,a.issues.length>0&&o==="lenient"&&(this.issues=a.issues),Array.isArray(r.fields)?this.fields=[...r.fields]:this.fields=[],Array.isArray(r.dependencyList)?this.dependencyList=[...r.dependencyList]:this.dependencyList=[],this.#e=!1}clone(e){let t=this.toJSON(),i=Array.from(this.dependencies.values()).map(s=>s.clone()),r={readOnly:this.readOnly,...e};return new c(t,i,r)}toJSON(){let e={info:this.info.toJSON(),kind:this.kind,key:this.key,graph:Ld(this.graph,this.key),lifecycle:this.lifecycle};return this.previousVersion&&(e.previousVersion=this.previousVersion),this.dependencyList.length>0&&(e.dependencyList=structuredClone(this.dependencyList)),Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),e}notifyChange(){this.#t||this.#e||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;let e=new Event("change");this.dispatchEvent(e)}))}changeLifecycle(e,t){if(e!==this.lifecycle){if(this.lifecycle==="published"){if(e!=="draft")throw new Error(`Cannot transition from published to ${e}`);if(!t)throw new Error("A new version must be specified when creating a draft from a published domain");if(t===this.info.version)throw new Error("The new version must be different from the current published version");this.previousVersion=this.info.version,this.info.version=t,this.lifecycle="draft",this.notifyChange();return}if(e==="draft"){if(this.lifecycle!=="committed")throw new Error(`Cannot transition from ${this.lifecycle} to draft`);this.lifecycle="draft",this.notifyChange();return}if(e==="committed"){if(this.lifecycle!=="draft")throw new Error(`Cannot transition from ${this.lifecycle} to committed`);this.lifecycle="committed",this.notifyChange();return}if(e==="published"){this.lifecycle="published",this.notifyChange();return}throw new Error(`Unknown lifecycle state: ${e}`)}}ensureWritable(){if(this.lifecycle!=="draft")throw new Error(`Cannot modify the data domain when it is in "${this.lifecycle}" lifecycle state`)}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}hasFields(){return this.fields.length>0}*listFields(){for(let{key:e}of this.fields){let t=this.graph.node(e);t&&(t.kind===Le||t.kind===Oe)&&(yield t)}}addNamespace(e,t){if(this.ensureWritable(),t){if(!this.graph.hasNode(t))throw new Error(`Parent namespace ${t} does not exist`);let r=this.graph.node(t);if(!r||r.kind!==Le)throw new Error(`Parent namespace ${t} is not a valid namespace`);if(r.domain.key!==this.key)throw new Error("Cannot add a namespace to a foreign domain");return r.addNamespace(e)}let i=new ar(this,e);return this.graph.setNode(i.key,i),this.fields.push({type:"namespace",key:i.key}),i}removeNamespace(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Namespace ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==Le)throw new Error(`Namespace ${e} not found`);if(t.domain.key!==this.key)throw new Error("Cannot remove a namespace from a foreign domain");let i=t.getParentInstance();return i===this?(Ve(this.graph,e),this.removeField(e)):i.removeNamespace(e),this}*listNamespaces(){for(let{key:e,type:t}of this.fields){if(t!=="namespace")continue;let i=this.graph.node(e);!i||i.kind!==Le||(yield i)}}*listForeignNamespaces(e){let t=this.dependencies.get(e);if(!t)throw new Error(`Foreign domain ${e} not found`);for(let i of t.listNamespaces()){let r=`${e}:${i.key}`;this.graph.node(r)&&(yield i)}}hasNamespaces(){return this.fields.some(e=>e.type==="namespace")}*listGraphNamespaces(e){for(let t of this.graph.children(e)){let i=this.graph.node(t);i.kind===Le&&i.domain.key===this.key&&(yield i)}}buildReferenceKey(e,t){if(t&&t!==this.key){if(typeof t!="string"||t.length===0)throw new Error(`Invalid namespace key. Expected a string, got ${typeof t}`);if(!this.dependencies.get(t))throw new Error(`Foreign domain ${t} not found`);return`${t}:${e}`}return e}findNamespace(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===Le)return i}moveNamespace(e,t){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Namespace ${e} does not exist`);let i=this.findNamespace(e);if(!i)throw new Error(`Namespace ${e} not found in the graph`);if(t){let o=this.findNamespace(t);if(o&&o.domain.key!==this.key)throw new Error("Cannot move a namespace to a foreign domain");if(!o)throw new Error(`Parent namespace ${t} does not exist`)}if(e===t)throw new Error("Cannot move a namespace to itself");if(i.domain.key!==this.key)throw new Error("Cannot move a namespace from a foreign domain");let r;if(t){if(r=this.findNamespace(t),!r)throw new Error(`Parent namespace ${t} not found`);if(this.isChildOf(t,e))throw new Error("Cannot move a namespace to its own child")}let s=this.graph.parent(e);return s&&!t?this.graph.node(s).detachNamespace(e):s||this.removeField(e),t&&r?r.attachNamespace(e):this.fields.push({type:"namespace",key:e}),this}isChildOf(e,t){let i=this.graph.children(t);for(let r of i)if(r===e||this.isChildOf(e,r))return!0;return!1}addModel(e,t){if(this.ensureWritable(),t){if(!this.graph.hasNode(t))throw new Error(`Parent ${t} does not exist`);let r=this.findNamespace(t);if(!r)throw new Error(`Parent namespace ${t} is not a valid namespace`);if(r.domain.key!==this.key)throw new Error("Cannot add a model to a foreign domain");return r.addModel(e)}let i=new wi(this,e);return this.graph.setNode(i.key,i),this.fields.push({type:"model",key:i.key}),i}removeModel(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Data model ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==Oe)throw new Error(`Data model ${e} not found`);if(t.domain.key!==this.key)throw new Error("Cannot remove a model from a foreign domain");let i=t.getParentInstance();return i===this?(Ve(this.graph,e),this.removeField(e)):i.removeModel(e),this}*listModels(e){let t=e?.domain,i=e?.includeForeign??!1,r=e?.foreignOnly??!1;if(t){let s=t===this.key?this:this.dependencies.get(t);if(!s)throw new Error(`Foreign domain ${t} not found`);for(let o of s.listModels()){let a=t===this.key?o.key:`${t}:${o.key}`,n=this.graph.node(a);n&&(yield n)}return}if(!r)for(let{key:s,type:o}of this.fields){if(o!=="model")continue;let a=this.graph.node(s);a&&a.kind===Oe&&(yield a)}if(i||r)for(let[s,o]of this.dependencies)for(let a of o.listModels()){let n=`${s}:${a.key}`,l=this.graph.node(n);l&&(yield l)}}*listForeignModels(e){yield*this.listModels({domain:e})}hasModels(){return this.fields.some(e=>e.type==="model")}*listGraphModels(e){for(let t of this.graph.children(e)){let i=this.graph.node(t);i.kind===Oe&&i.domain.key===this.key&&(yield i)}}findModel(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===Oe)return i}moveModel(e,t){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Data model ${e} does not exist`);let i=this.findModel(e);if(!i)throw new Error(`Data model ${e} not found in the graph`);if(t){let s=this.findNamespace(t);if(s&&s.domain.key!==this.key)throw new Error("Cannot move a model to a foreign domain");if(!s)throw new Error(`Parent namespace ${t} does not exist`)}if(i.domain.key!==this.key)throw new Error("Cannot move a data model to a foreign domain");let r=this.graph.parent(e);if(r&&!t){let s=this.findNamespace(r);if(!s)throw new Error(`The parent namespace ${r} not found`);s.detachModel(e)}else r||this.removeField(e);return t?this.findNamespace(t).attachModel(e):this.fields.push({type:"model",key:e}),this}addEntity(e,t){if(this.ensureWritable(),!e)throw new Error("An entity expects a DomainModel parent");if(!this.graph.hasNode(e))throw new Error(`The parent ${e} does not exist`);let i=this.findModel(e);if(!i)throw new Error(`Parent model ${e} is not a valid model`);if(i.domain.key!==this.key)throw new Error("Cannot add an entity to a foreign domain");return i.addEntity(t)}removeEntity(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Entity ${e} does not exist`);let t=this.graph.parent(e);if(!t)throw new Error(`Parent model not found for entity ${e}`);let i=this.findModel(t);if(!i)throw new Error(`Parent model ${t} not found`);if(i.domain.key!==this.key)throw new Error("Cannot remove an entity from a foreign domain");return i.removeEntity(e),this}*listEntities(e){let t,i,r=!1,s=!1;if(typeof e=="string"?t=e:e&&typeof e=="object"&&(t=e.parent,i=e.domain,r=e.includeForeign??!1,s=e.foreignOnly??!1),i&&i!==this.key&&!this.dependencies.get(i))throw new Error(`Foreign domain ${i} not found`);let o=t?this.graph.children(t):this.graph.nodes();for(let a of o){let n=this.graph.node(a);if(n&&n.kind===$){let l=n.domain.key===this.key;if(i){n.domain.key===i&&(yield n);continue}s?l||(yield n):r?yield n:l&&(yield n)}}}*listForeignEntities(e){yield*this.listEntities({domain:e})}*listAllForeignEntities(){yield*this.listEntities({foreignOnly:!0})}findEntity(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===$)return i}moveEntity(e,t,i){if(this.ensureWritable(),t===i)throw new Error("Cannot move an entity to the same model");if(!this.graph.hasNode(e))throw new Error(`Entity ${e} does not exist`);if(!this.graph.hasNode(t))throw new Error(`Source model ${t} does not exist`);if(!this.graph.hasNode(i))throw new Error(`Target model ${i} does not exist`);let r=this.findEntity(e),s=this.findModel(t),o=this.findModel(i);if(!r||!s||!o)throw new Error("Entity or models not found in the graph");if(r.domain.key!==this.key)throw new Error("Cannot move an entity from a foreign domain");if(o.domain.key!==this.key)throw new Error("Cannot move an entity to a foreign domain");o.attachEntity(e)}addAssociation(e,t){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Source entity ${e} not found`);let i=this.findEntity(e);if(!i)throw new Error(`Source entity ${e} not found`);if(i.domain.key!==this.key)throw new Error("Cannot add an association to a foreign domain");return i.addAssociation(t)}removeAssociation(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Association ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==se)throw new Error(`Association ${e} not found`);let i=t.getParentInstance();if(!i)throw new Error(`Parent entity not found for association ${e}`);if(i.domain.key!==this.key)throw new Error("Cannot remove an association from a foreign domain");return i.removeAssociation(e),this}findAssociation(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===se)return i}getIncomingAssociations(e){let t=[];for(let i of this.graph.inEdges(e)){let r=this.graph.node(i.v);r&&r.kind===se&&t.push(r)}return t}findAssociationBetween(e,t){let i=this.graph.node(e);if(!i||i.kind!==$)return;let r=i;for(let s of r.listAssociations())for(let o of s.targets)if(this.buildReferenceKey(o.key,o.domain)===t)return s}*associationsBetween(e,t){let i=this.findEntity(e.key,e.domain);if(!i||!this.findEntity(t.key,t.domain))return;let s=this.buildReferenceKey(t.key,t.domain);for(let o of i.withInheritedAssociations())for(let a of o.targets)if(this.buildReferenceKey(a.key,a.domain)===s){yield o;break}}resolveOwnershipPath(e){let t=this.findEntity(e);if(!t)return null;if(t.hasSemantic(g.User))return[];for(let s of t.listAssociations())if(s.hasSemantic(g.ResourceOwnerIdentifier))return[s];let i=[{key:e,path:[]}],r=new Set([e]);for(;i.length>0;){let s=i.shift();if(!s)continue;let o=this.findEntity(s.key);if(!o)continue;let a=[...o.listAssociations()].filter(p=>p.hasSemantic(g.CreatedBy)||p.hasSemantic(g.UpdatedBy)||p.hasSemantic(g.DeletedBy)?!1:p.hasSemantic(g.RelationalResourceOwner)||p.hasSemantic(g.ResourceOwnerIdentifier)?!0:p.listTargets().some(m=>m.hasSemantic(g.User))),l=this.getIncomingAssociations(s.key).filter(p=>{if(p.hasSemantic(g.CreatedBy)||p.hasSemantic(g.UpdatedBy)||p.hasSemantic(g.DeletedBy))return!1;let m=p.getParentInstance();return m?m.hasSemantic(g.User)||p.schema?.embedded===!0:!1}),d=[...a,...l];for(let p of d){let m=p.getParentInstance();if(!m)continue;let h=[...p.listTargets()];if(h.length!==0)for(let f of h){let k=s.key===m.key?f.key:m.key;if(r.has(k))continue;let w=this.findEntity(k);if(!w)continue;let S=[...s.path,p];if(w.hasSemantic(g.User)||p.hasSemantic(g.ResourceOwnerIdentifier))return S;r.add(k),i.push({key:k,path:S})}}}return null}addProperty(e,t){if(this.ensureWritable(),!e)throw new Error("A property expects a DomainEntity parent");if(!this.graph.hasNode(e))throw new Error(`Parent entity ${e} does not exist`);let i=this.findEntity(e);if(!i)throw new Error(`Parent entity ${e} not found`);if(i.domain.key!==this.key)throw new Error("Cannot add a property to a foreign domain");return i.addProperty(t)}removeProperty(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Property ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==be)throw new Error(`Property ${e} not found`);let i=t.getParentInstance();if(!i)throw new Error(`Parent entity not found for property ${e}`);if(i.domain.key!==this.key)throw new Error("Cannot remove a property from a foreign domain");return i.removeProperty(e),this}findProperty(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===be)return i}registerForeignDomain(e){this.ensureWritable();let{info:t,key:i}=e;if(!t.version)throw new Error(`Foreign domain ${i} does not have a version set`);if(this.dependencies.has(i))throw new Error(`Foreign domain with key ${i} already registered`);this.dependencies.set(i,e),this.dependencyList.push({key:i,version:t.version}),Gc(this.graph,e.graph,e.key)}unregisterForeignDomain(e){this.ensureWritable();let t=this.dependencies.get(e);if(!t)throw new Error(`Foreign domain with key ${e} not found`);this.dependencies.delete(e),this.dependencyList=this.dependencyList.filter(i=>i.key!==e),Md(this.graph,t.key)}removeDomainElement(e,t){switch(t){case Le:this.removeNamespace(e);break;case Oe:this.removeModel(e);break;case $:this.removeEntity(e);break;case be:this.removeProperty(e);break;case se:this.removeAssociation(e);break;default:throw new Error(`Unknown kind ${t} for the object ${e}`)}}search(e={}){let{query:t,nodeTypes:i,includeForeignDomains:r=!1,caseSensitive:s=!1}=e,o=[],a=!t&&(!i||i.length===0),n=m=>!i||i.length===0?!0:i.includes(m),l=m=>{if(!m||!t)return!t;if(t instanceof RegExp)return t.test(m);let h=s?m:m.toLowerCase(),f=s?t:t.toLowerCase();return h.includes(f)},d=m=>{if(!t)return[];let h=[],{info:f}=m;return l(f.name)&&h.push("name"),l(f.displayName)&&h.push("displayName"),l(f.description)&&h.push("description"),h},p=m=>m.includes(":");for(let m of this.graph.nodes()){let h=this.graph.node(m);if(!h||!h.info)continue;let f=p(m);if(f&&!r||!n(h.kind))continue;if(a){o.push({node:h,matchedFields:[],key:m,isForeign:f});continue}let k=d(h);(!t||k.length>0)&&o.push({node:h,matchedFields:k,key:m,isForeign:f})}return o}};var zt=class{constructor(e=new Z,t=F()){this.fileManager=e;this.client=t}fileManager;client;async loadDomain(e,t){let i=await this.fileManager.read(e,t);if(i.kind!==ni)throw new Error(`File '${t}' is not a data domain. The file kind is '${i.kind}', but expected '${ni}'.`);let r=await this.fileManager.readMedia(e,t),s=r.media;if(s.kind!==Ee)throw new Error(`Invalid data domain schema format. The media kind is '${s.kind}', but expected '${Ee}'.`);let o=[];if(s.dependencyList&&s.dependencyList.length>0){y.debug(`[domain:load] Fetching dependencies: ${JSON.stringify(s.dependencyList)}`);try{o=(await this.client.dataCatalog.listDependencies(s.dependencyList,{token:this.client.token})).data||[]}catch(n){y.debug(`[domain:load] Failed to fetch dependencies: ${n}`)}}return{domain:new Me(s,o,{readOnly:!1}),fileMeta:i,metaVersion:r.meta.version,originalSchema:s}}};var Fe=class extends Ae{fileManager;domainLoader;constructor(e,t,i=new Z,r=new zt(i)){super(e,t),this.fileManager=i,this.domainLoader=r}async resolveFileId(e,t="Select a data domain file:"){let i=this.options.file||this.options.id;if(!i&&process.stdout.isTTY){y.debug("[domain] File ID not provided; listing data domain files for selection...");try{let r=await this.fileManager.list(e,{kind:"domain"});r.length>0&&(i=await Ce(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){y.debug(`[domain] Failed to list domain files for selection: ${r}`)}}return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1)),i}async loadDomain(e,t){try{return await this.domainLoader.loadDomain(e,t)}catch(i){i instanceof Error&&i.message.includes("is not a data domain")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1)),i instanceof Error&&i.message.includes("Invalid data domain schema format")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1));let r=U(i);this.formatter.error(r),process.exit(1)}}validateDomain(e,t={}){y.debug("[domain] Validating data domain structure...");let r=new Zi(e).validate();if(r&&r.length>0){let s=r.filter(a=>a.severity==="error"),o=r.filter(a=>a.severity==="warning");if(s.length>0&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:s.length===1&&!t.logWarnings?"Data domain validation failed.":`Data domain validation failed with ${s.length} error(s).`,detail:JSON.stringify(r,null,2)}),process.exit(1)),t.logWarnings&&o.length>0&&this.formatter.format!=="json"){console.log(ie.yellow(`\u26A0 Data domain validation reported ${o.length} warning(s):`));for(let a of o)console.log(ie.yellow(` - [${a.rule||"WARNING"}] ${a.message}`))}}}};var Go=class extends Fe{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[domain:list] Searching data domain files for org: ${e}, parent: ${this.options.parent||"all"}`);try{let t=await this.fileManager.search(e,{kind:"domain",parent:this.options.parent});y.debug(`[domain:list] Found ${t.length} domain files.`);let i=t.map(r=>({id:r.key,name:r.info?.name||"",parent:r.parents&&r.parents.length>0?r.parents[r.parents.length-1]:"root",isShortcut:r.isShortcut?"Yes":"No"}));this.formatter.list(i,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var Jo=class extends Fe{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[domain:create] Creating domain file: name=${this.options.name}, org=${e}, parent=${this.options.parent}, media=${this.options.media}, stdin=${this.options.stdin}`),this.options.media&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let t=this.options.name;!t&&process.stdout.isTTY&&(t=await pe("Enter data domain name:")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));try{let i=await this.fileManager.parseMediaInput({mediaPath:this.options.media,stdin:this.options.stdin});if(i!==void 0){let s=i.content;s.kind&&s.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${s.kind}', but expected '${Ee}'.`}),process.exit(1))}let r=await this.fileManager.create(e,{name:t,kind:"domain",parent:this.options.parent,mediaContent:i?.content,key:i?.key});this.formatter.success("Data domain created successfully!",r)}catch(i){i instanceof Error&&(i.message.startsWith("Media file not found")||i.message==="Cannot specify both media path and STDIN.")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1));let s=U(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var Wo=class extends Fe{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;y.debug(`[domain:read] Reading domain file: file=${t}, org=${e}, meta=${this.options.meta}, media=${this.options.media}`);let i=await this.resolveFileId(e,"Select a data domain file to read:");try{if(this.options.media){y.debug(`[domain:read] Fetching media schema for domain file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;y.debug("[domain:read] Media retrieved successfully."),this.formatter.format==="json"?console.log(JSON.stringify(s,null,2)):console.log(typeof s=="object"&&s!==null?JSON.stringify(s,null,2):s)}else{y.debug(`[domain:read] Fetching metadata for domain file ID '${i}'...`);let r=await this.fileManager.read(e,i);y.debug("[domain:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}};var Pe=class c extends Error{static E_VALIDATION_ERROR="E_VALIDATION_ERROR";code=c.E_VALIDATION_ERROR;issues;constructor(e,t){let i=e[0];super(t??`Validation failed: ${i?.path??""} - ${i?.message??""}`),this.name="OperationValidationException",this.issues=e,Error.captureStackTrace&&Error.captureStackTrace(this,c)}};function zd(c,e="/"){return c.replace(/~0/g,"~").replace(/~1/g,e)}function Jc(c,e="/"){let t="",i=c;typeof i=="number"&&(i=String(i));for(let r=0,s=i.length;r<s;r++){let o=i.charAt(r);o==="~"?t+="~0":o===e?t+="~1":t+=o}return t}function Re(c,e="/"){let t="";for(let i=0,r=c.length;i<r;i++)t+=e+Jc(c[i],e);return t}function _t(c,e="/"){if(Array.isArray(c))return c;if(c.length===0)return[];if(c.charAt(0)!==e)throw new Pe([{message:"Invalid pointer.",path:c}]);let t=[""],i=0;for(let r=1,s=c.length;r<s;r++){let o=c.charAt(r);if(o===e){let a=t[t.length-1];if(a==="constructor"||a==="__proto__")throw new Error("Prototype pollution attempt");t.push(""),i++}else o==="~"?c.charAt(r+1)==="1"?(t[i]+=e,r++):c.charAt(r+1)==="0"?(t[i]+="~",r++):t[i]+=o:t[i]+=o}return t}var Vt;(function(c){c.add="add",c.remove="remove",c.replace="replace",c.copy="copy",c.move="move",c.test="test"})(Vt||(Vt={}));function Ho(c,e){if(c==="-")return;let t=new Pe([{message:"Invalid pointer",path:`/${c}`}]),{length:i}=c;if(i>1&&c[0]==="0")throw t;let r=+c;if(Number.isNaN(r)||Math.abs(r).toString()!==c||r<0||r>e)throw t}function lr(c,e){let{length:t}=e,i=c,r;for(let s=0;s<t-1;s++){if(r=e[s],Array.isArray(i))Ho(r,i.length);else if(typeof i!="object"||i===null)throw new Error("Cannot be walked");i instanceof Map?i=i.get(r):i instanceof Set?i=Array.from(i)[+r]:i=i[r]}if(r=e[t-1],Array.isArray(i))Ho(r,i.length);else if(typeof i!="object"||i===null)throw new Error("Invalid target");return{token:r,parent:i}}function Yo(c,e,t){let i,r;return typeof c=="string"?i=_t(c,t):i=c,typeof e=="string"?r=[e]:r=e,Re(i.concat(r),t)}function qm(c,e){if(c instanceof Set){let t=0;for(let i of c)e(i,t+=1)}else if(Array.isArray(c)||c instanceof Map)c.forEach(e);else if(typeof c=="object"&&c!==null)Object.keys(c).forEach(t=>{e(c[t],t)});else throw new TypeError(`${c} is not a structure`)}function Vd(c,e,t,i){i(c,e,t),!(c===null||typeof c!="object")&&qm(c,(r,s)=>{Vd(r,s,c,i)})}function Xo(c,e){let t=Object.create(null);function i(s){for(let o in t)if(t[o]===s)return o}function r(s,o,a){let n=Yo(a&&i(a),o);t[n]=s}Vd(c,void 0,void 0,(s,o,a)=>{if(s!==null&&typeof s=="object"&&(a===void 0||o===void 0?r(s,[],""):r(s,o.toString(),a)),o===void 0||a===void 0)e(s,"");else{let n=i(a);e(s,Yo(n,o.toString()),a,n)}})}var ge=class c{_raw="";_tokens=[];_separator;_index;_parent;constructor(e,t="/"){if(e instanceof c&&e.separator===t)return e;this._separator=t,Array.isArray(e)?(this._tokens=e,this._raw=Re(e,this._separator)):typeof e=="string"?(this._raw=e,this._tokens=_t(e,this._separator)):(this._raw=e._raw,this._tokens=e._tokens)}get raw(){return this._raw}get tokens(){return[...this._tokens]}get separator(){return this._separator}getToken(e){return e<0||e>=this._tokens.length?null:this._tokens[e]}getParent(){return this._parent!==void 0?this._parent:(this._tokens.length===0||this._tokens.length===1&&this._tokens[0]===""?this._parent=null:this._parent=new c(this._tokens.slice(0,-1),this._separator),this._parent)}isRoot(){return this._tokens.length===0||this._tokens[0]===""}append(e){return new c([...this._tokens,String(e)],this._separator)}prefix(e){if(e<0||e>this._tokens.length)throw new Error("Levels out of bound.");return new c(this._tokens.slice(0,e),this._separator)}escape(e){return Jc(e,this._separator)}unescape(e){return zd(e,this._separator)}static encode(e,t="/"){return Re(e,t)}encode(e=this._separator){return Re(this._tokens,e)}static decode(e,t="/"){return _t(e,t)}find(e){let{tokens:t}=this;if(t.length===0)return e;let i;try{i=lr(e,t)}catch{return}let{token:r,parent:s}=i;return s[r]}findValue(e){return this.isRoot()?e:this.find(e)}findParentValue(e){return this.isRoot()?e:this.getParent().find(e)}static find(e,t){return new c(t).find(e)}findAndTest(e,t){let i=this.find(e);return{found:i!==void 0,value:i,equal:i===t}}static isValidArrayToken(e,t){if(e==="-")return;let i=new Pe([{message:"Invalid pointer.",path:`/${e}`}]),{length:r}=e;if(r>1&&e[0]==="0")throw i;let s=+e;if(Number.isNaN(s)||Math.abs(s).toString()!==e||s<0||s>t)throw i}getIndex(){if(this._index!==void 0)return this._index;let e=this._tokens;if(e.length===0)return null;let t=e[e.length-1];if(t==="-")return-1;let i=parseInt(t,10);return isNaN(i)?null:i}static getIndex(e){return new c(e).getIndex()}setIndex(e){let t=this._tokens,i=t[t.length-1];if(i===void 0)return new c(`/${e}`,this._separator);if(isNaN(+i))return new c([...t,e.toString()],this._separator);let r=Array.from(t);return r[r.length-1]=e.toString(),new c(r,this._separator)}static index(e){let t=Object.create(null);return Xo(e,(i,r)=>{t[r]=i}),t}static join(e,t,i){let r,s;if(typeof e=="string"?r=_t(e,i):r=e,typeof t=="string"){if(!t)return Re(r,i);let o=t,a=i||"/";o.startsWith(a)||(o=`${a}${o}`),s=_t(o,i)}else s=t;return Re(r.concat(s),i)}static unflatten(e){let t=Object.keys(e),i=e[""];for(let r of t){if(r==="")continue;let s=_t(r),o=lr(i,s),{parent:a,token:n}=o;a instanceof Map?a.set(n,e[r]):a instanceof Set?a.add(e[r]):Array.isArray(a)?a.push(e[r]):a[n]=e[r]}return i}static flatten(e){let t=Object.create(null);return Xo(e,(i,r)=>{let s;Array.isArray(i)?s=[]:i instanceof Map?s=new Map:i instanceof Set?s=new Set:typeof i=="object"&&i!==null?s={}:s=i,t[r]=s}),t}equals(e){return e?["","/"].includes(this._raw)&&["/",""].includes(e._raw)?!0:this.raw===e.raw:!1}isAfter(e){let t=e.getIndex(),i=this.getIndex();return t===null||i===null||t===-1||i===-1?!1:t<i}isAfterOrAt(e){let t=e.getIndex(),i=this.getIndex();return t===null||i===null||t===-1||i===-1?!1:t!==null&&i!==null&&t<=i}contains(e){if(this.isRoot())return!0;let t=e.tokens;if(t.length<=this._tokens.length)return!1;for(let i=0;i<this._tokens.length;i++)if(this._tokens[i]!==t[i])return!1;return!0}parentEquals(e){let t=this.getParent();return t&&e?t.equals(e):t===e}};function xt(c,e){let t=e.tokens,i=t.length;if(i===0||i===1&&t[0]==="")throw new Pe([{message:"Cannot walk empty path.",path:e.raw}]);try{let r=lr(c,t);return{token:r.token,parent:r.parent}}catch{throw new Pe([{message:"Path not found.",path:e.raw}])}}function Ft(c,e,t){let i=new ge(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:c};let{token:s,parent:o}=xt(c,i),a,n;if(Array.isArray(o))s==="-"?(o.push(r),n=o.length-1):o.splice(parseInt(s,10),0,r);else{a=o[s];let l=o;l[s]=r}return{doc:c,previous:a,idx:n}}function Di(c,e){let t=new ge(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return c;let{parent:i,token:r}=xt(c,t);if(Array.isArray(i))ge.isValidArrayToken(r,i.length);else if(typeof i=="object"&&i!==null&&!(r in i))throw new Pe([{path:`/${r}`,message:"The target does not exists."}]);return i[r]}function dr(c,e,t){let i=new ge(e),r=new ge(t),s=Di(c,i);return e===""||e==="/"?{doc:s,previous:c}:Ft(c,r,s)}function ei(c,e){let t=new ge(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return{doc:void 0,previous:c};let{parent:i,token:r}=xt(c,t),s=i[r];if(s===void 0)throw new Pe([{message:"Parent does not exists.",path:t.raw}]);return Array.isArray(i)?i.splice(parseInt(r,10),1):delete i[r],{doc:c,previous:s}}function fs(c,e,t){let i=new ge(e),r=new ge(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:ei(c,i).previous,previous:c};let s=ei(c,i);return Ft(s.doc,r,s.previous)}function pr(c,e,t){let i=new ge(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:c};let{parent:s,token:o}=xt(c,i),a=s[o];if(a===void 0)throw new Pe([{message:"Location not found.",path:i.raw}]);return s[o]=r,{doc:c,previous:a}}var Km=["boolean","string","number","null"];function Si(c){let e=typeof c;if(e==="boolean"||e==="string")return e;if(e==="number"&&Number.isFinite(c))return"number";if(e==="object"){if(Array.isArray(c)||c instanceof Set)return"array";if(c instanceof Map)return"object";if(c===null)return"null";if(e==="object")return"object"}}function Zo(c){return c===void 0?!0:Km.includes(c)}function Fd(c){let e=[];return c.forEach(t=>{e.push(t)}),e}function qd(c){let e=Object.create(null);return c.forEach((t,i)=>{e[i]=t}),e}function Wc(c,e,t,i){let r=Si(c),s=Si(e);if(r!==s)return!1;switch(r){case"number":return c===0&&1/c===-1/0?e===0&&1/e===-1/0:c===e;case"string":case"null":case"boolean":return c===e;default:}let o,a,n=t.indexOf(c);if(n!==-1)return i[n]===e;if(t.push(c),i.push(e),r==="array"){c instanceof Set&&(c=Fd(c)),e instanceof Set&&(e=Fd(e));let l=c,d=e;if(l.length!==d.length)return t.pop(),i.pop(),!1;for(o=0,a=l.length;o<a;o++)if(!Wc(l[o],d[o],t,i))return t.pop(),i.pop(),!1;return!0}if(r==="object"){c instanceof Map&&(c=qd(c)),e instanceof Map&&(e=qd(e));let l=c,d=e,p=Object.keys(l),m=Object.keys(d);if(p.length!==m.length)return t.pop(),i.pop(),!1;for(p.sort(),m.sort(),o=0,a=p.length;o<a;o++){let h=p[o],f=m[o];if(h!==f||!Object.prototype.hasOwnProperty.call(d,h)||!Wc(l[h],d[h],t,i))return t.pop(),i.pop(),!1}return t.pop(),i.pop(),!0}return t.pop(),i.pop(),!0}function qt(c,e){return Wc(c,e,[],[])}function Qo(c,e,t){let i=new ge(e),r=Di(c,i);if(!qt(r,t))throw new Pe([{path:i.raw,message:"Test operation failed. The values are not equal."}]);return{doc:c}}var fR=Object.freeze({add:Ft,copy:dr,move:fs,remove:ei,replace:pr,test:Qo});function Bd(c){return Array.isArray(c)?new Array(c.length).fill(0).map((e,t)=>`${t}`):Object.keys(c)}function gs(c){switch(typeof c){case"object":return JSON.parse(JSON.stringify(c));case"undefined":return null;default:return c}}function Bm(c,e,t={}){if(JSON.stringify(c)===JSON.stringify(e))return[];let i=[...c],r=[...e],s=[],o=0,a=0;for(;o<i.length||a<r.length;)if(o>=i.length){let n=t.fixedIndexes?a:-1;s.push({op:"add",index:n,value:r[a]}),a++}else if(a>=r.length)s.push({op:"remove",index:o}),o++;else if(qt(i[o],r[a]))o++,a++;else{let n=-1,l=-1;for(let d=o;d<i.length;d++)if(qt(i[d],r[a])){n=d;break}for(let d=a;d<r.length;d++)if(qt(r[d],i[o])){l=d;break}if(n===-1&&l===-1)s.push({op:"replace",index:a,value:r[a]}),o++,a++;else if(n===-1)s.push({op:"add",index:a,value:r[a]}),a++;else if(l===-1)s.push({op:"remove",index:o}),o++;else{s.push({op:"move",index:a,from:n});let d=i[n];i.splice(n,1),i.splice(o,0,d),o++,a++}}return s.sort((n,l)=>n.op==="remove"&&l.op==="remove"?l.index-n.index:0)}function Hc(c,e,t,i=[],r={}){if(c===e)return;if(c==null&&e!==null&&e!==void 0){t.push({op:"replace",path:"",value:e});return}if(e==null&&c!==null&&c!==void 0){t.push({op:"replace",path:"",value:null});return}typeof e.toJSON=="function"&&(e=e.toJSON());let s=Si(c),o=Si(e),a=Zo(s),n=Zo(o);if(a&&n){qt(c,e)||t.push({op:"replace",path:Re(i),value:e});return}if(o!==s){t.push({op:s===void 0?"add":"replace",path:Re(i),value:e});return}if(s==="array"){let p=c,h=Bm(p,e,r);for(let f of h){let k=f.index===-1?"-":f.index.toString(),w=[...i,k];f.op==="remove"?(r.invertible&&t.push({op:"test",path:Re(w),value:gs(p[f.index])}),t.push({op:f.op,path:Re(w)})):f.op==="replace"&&typeof f.value=="object"&&f.value!==null?Hc(p[f.index],f.value,t,w,r):f.op==="move"?t.push({op:"move",from:Re([...i,f.from.toString()]),path:Re(w)}):t.push({op:f.op,path:Re(w),value:f.value})}return}let l=Bd(e),d=Bd(c);for(let p of l){let m=c[p],h=e[p];Object.prototype.hasOwnProperty.call(c,p)?typeof m=="object"&&m!=null&&typeof h=="object"&&h!==null&&Array.isArray(m)===Array.isArray(h)?Hc(m,h,t,[...i,p],r):qt(m,h)||(r.invertible&&t.push({op:"test",path:Re([...i,p]),value:gs(m)}),t.push({op:"replace",path:Re([...i,p]),value:gs(h)})):t.push({op:"add",path:Re([...i,p]),value:gs(h)})}for(let p of d)Object.prototype.hasOwnProperty.call(e,p)||(r.invertible&&t.push({op:"test",path:Re([...i,p]),value:gs(c[p])}),t.push({op:"remove",path:Re([...i,p])}))}function ti(c,e,t){let i=[];return Hc(c,e,i,[],t),i}var ur=Object.create(null);ur.add=0;ur.remove=1;ur.replace=2;ur.move=3;ur.copy=4;ur.test=5;var ea=class extends Fe{constructor(t,i,r,s=new Z,o=new zt(s)){super(i,r,s,o);this.stateOption=t}stateOption;async execute(){let t=this.resolveOrgId();y.debug(`[domain:transition] Transitioning domain lifecycle. Options: file=${this.options.file}, org=${t}, ver=${this.options.ver}, state=${this.stateOption}`);let i=await this.resolveFileId(t),r=await this.resolveTargetState(),s=await this.loadDomain(t,i),o=this.options.ver;if(s.domain.lifecycle==="published"&&r==="draft"&&!o){if(process.stdout.isTTY){let l=s.domain.info.version;o=await pe(`Enter new version (current published version is ${l}):`)}o||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"A new version must be specified when creating a draft from a published domain.",detail:"Provide a version with --ver <ver>."}),process.exit(1))}y.debug(`[domain:transition] Changing lifecycle state from '${s.domain.lifecycle}' to '${r}'...`),s.domain.changeLifecycle(r,o),this.validateDomain(s.domain);let a=s.domain.toJSON(),n=ti(s.originalSchema,a);if(n.length===0){y.debug("[domain:transition] No changes in domain lifecycle detected."),this.formatter.success(`Data domain is already in '${r}' state.`);return}try{let l=await this.fileManager.patchMedia(t,i,{patchOps:n,version:s.metaVersion});y.debug(`[domain:transition] Patch applied successfully. New file version: ${l.newVersion}`),this.formatter.success(`Successfully transitioned data domain state to '${r}' (new file version: ${l.newVersion}).`,{fileId:i,state:r,version:s.domain.info.version,fileVersion:l.newVersion})}catch(l){let d=U(l);this.formatter.error(d),process.exit(1)}}async resolveTargetState(){let t=this.stateOption,i=["draft","committed","published"];return!t&&process.stdout.isTTY&&(t=await Ce("Select target lifecycle state:",[{name:"Draft (draft)",value:"draft"},{name:"Committed (committed)",value:"committed"},{name:"Published (published)",value:"published"}])),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Target lifecycle state is required.",detail:`Specify state as a positional argument (allowed: ${i.join(", ")}).`}),process.exit(1)),i.includes(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle state '${t}'.`,detail:`Allowed states: ${i.join(", ")}`}),process.exit(1)),t}};var Li=class c{key;get kind(){return Wt}catalogKey;scope;lifecycle;version;publishedBy;unpublishedAt;deprecated;deprecatedAt;deprecatedBy;deprecationReason;createdAt;updatedAt;changelog;static createSchema(e){let{key:t="",scope:i="private",publishedBy:r="",createdAt:s=0,updatedAt:o=0,catalogKey:a="",lifecycle:n="stable",version:l=""}=e;if(["public","private","organization"].indexOf(i)===-1)throw new Error(`Invalid scope: ${i}`);let d={key:t,kind:Wt,scope:i,publishedBy:r,createdAt:s,updatedAt:o,catalogKey:a,lifecycle:n,version:l};return typeof e.deprecated=="boolean"&&(d.deprecated=e.deprecated),typeof e.deprecatedAt=="number"&&(d.deprecatedAt=e.deprecatedAt),typeof e.deprecatedBy=="string"&&(d.deprecatedBy=e.deprecatedBy),typeof e.changelog=="string"&&(d.changelog=e.changelog),typeof e.deprecationReason=="string"&&(d.deprecationReason=e.deprecationReason),typeof e.unpublishedAt=="number"&&(d.unpublishedAt=e.unpublishedAt),d}constructor(e={}){let t=c.createSchema(e);this.key=t.key,this.catalogKey=t.catalogKey,this.lifecycle=t.lifecycle,this.scope=t.scope,this.version=t.version,this.publishedBy=t.publishedBy,this.createdAt=t.createdAt,this.updatedAt=t.updatedAt,typeof t.changelog=="string"&&(this.changelog=t.changelog),typeof t.deprecated=="boolean"&&(this.deprecated=t.deprecated),typeof t.deprecatedAt=="number"&&(this.deprecatedAt=t.deprecatedAt),typeof t.deprecatedBy=="string"&&(this.deprecatedBy=t.deprecatedBy),typeof t.deprecationReason=="string"&&(this.deprecationReason=t.deprecationReason),typeof t.unpublishedAt=="number"&&(this.unpublishedAt=t.unpublishedAt)}toJSON(){let e={key:this.key,kind:Wt,scope:this.scope,publishedBy:this.publishedBy,createdAt:this.createdAt,updatedAt:this.updatedAt,catalogKey:this.catalogKey,lifecycle:this.lifecycle,version:this.version};return typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),typeof this.deprecatedAt=="number"&&(e.deprecatedAt=this.deprecatedAt),typeof this.deprecatedBy=="string"&&(e.deprecatedBy=this.deprecatedBy),typeof this.deprecationReason=="string"&&(e.deprecationReason=this.deprecationReason),typeof this.unpublishedAt=="number"&&(e.unpublishedAt=this.unpublishedAt),typeof this.changelog=="string"&&this.changelog&&(e.changelog=this.changelog),e}};var Zc;(function(c){c[c.Initializing=0]="Initializing",c[c.PendingDns=1]="PendingDns",c[c.Issuing=2]="Issuing",c[c.Active=3]="Active",c[c.Error=4]="Error"})(Zc||(Zc={}));var ta=class extends Fe{client=F();constructor(e,t,i=new Z,r=new zt(i)){super(e,t,i,r)}async execute(){let e=this.resolveOrgId(),t=await this.resolveFileId(e,"Select a data domain file to publish:"),i=await this.loadDomain(e,t),r=await this.checkPublicationStatus(t,e),s=await this.resolvePublishParams(i.domain,r,t,e);this.prepareDomainLifecycle(i.domain,s.version),this.validateDomain(i.domain,{logWarnings:!0});let o=await this.patchDomainMedia(e,t,i.domain,i.originalSchema,i.metaVersion),a=await this.publishToCatalog(s,r);this.reportSuccess(s,a,o)}async checkPublicationStatus(e,t){y.debug(`[domain:publish] Checking publication status for file '${e}' in org '${t}'...`);try{let i=await this.client.dataCatalog.checkPublicationStatus(e,t,{token:this.client.token});return y.debug(`[domain:publish] Domain already published. Catalog key: ${i.key}`),i}catch(i){let r=U(i);if(r.status===404)return y.debug("[domain:publish] Domain is not published yet (404)."),null;this.formatter.error(r),process.exit(1)}}async resolvePublishParams(e,t,i,r){let s=this.options.catalogVersion||this.options.ver;if(!s&&process.stdout.isTTY){let h=e.info.version||"1.0.0";s=await pe("Enter semantic version:",h)}let o=s||e.info.version||"1.0.0",a=this.options.scope;!a&&process.stdout.isTTY&&(a=await Ce("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),a||(a="public");let n=["public","organization","private"];n.includes(a)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${a}'.`,detail:`Allowed: ${n.join(", ")}`}),process.exit(1));let l=["dev","beta","stable"];l.includes(this.options.lifecycle)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${this.options.lifecycle}'.`,detail:`Allowed: ${l.join(", ")}`}),process.exit(1));let d=this.options.lifecycle,p=this.options.name,m=this.options.description;return t?(p=p||t.name||e.info.name||"",m=m||t.description||e.info.description||""):(!p&&e.info.name&&(p=e.info.name),!p&&process.stdout.isTTY&&(p=await pe("Enter catalog entry name:",e.info.name||"")),p||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required for publishing a new data catalog entry.",detail:"Specify --name <name>."}),process.exit(1)),!m&&e.info.description&&(m=e.info.description),!m&&process.stdout.isTTY&&(m=await pe("Enter catalog entry description:",e.info.description||"")),m||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Description is required for publishing a new data catalog entry.",detail:"Specify --description <desc>."}),process.exit(1))),{fileId:i,orgId:r,version:o,scope:a,lifecycle:d,name:p,description:m,changelog:this.options.changelog||void 0}}prepareDomainLifecycle(e,t){y.debug(`[domain:publish] Preparing domain lifecycle from '${e.lifecycle}' to 'committed' with version '${t}'...`),e.lifecycle==="published"?(e.changeLifecycle("draft",t),e.changeLifecycle("committed")):e.lifecycle==="committed"?e.info.version!==t&&(e.changeLifecycle("draft"),e.info.version=t,e.changeLifecycle("committed")):(e.info.version=t,e.changeLifecycle("committed"))}async patchDomainMedia(e,t,i,r,s){let o=i.toJSON(),a=ti(r,o);if(a.length===0)return y.debug("[domain:publish] No changes in domain schema detected, skipping patch."),s;y.debug(`[domain:publish] Sending patch request (${a.length} ops) to file media...`);try{let n=await this.fileManager.patchMedia(e,t,{patchOps:a,version:s});return y.debug(`[domain:publish] File media patched. New file version: ${n.newVersion}`),n.newVersion}catch(n){let l=U(n);this.formatter.error(l),process.exit(1)}}async publishToCatalog(e,t){let i;if(t)i=t.key,y.debug(`[domain:publish] Using existing catalog entry key: ${i}`);else{y.debug("[domain:publish] Publishing new data catalog entry...");let s={key:"",kind:wt,organization:e.orgId,file:e.fileId,scope:e.scope,name:e.name,description:e.description,publishedBy:"",publishedAt:0,createdAt:0,updatedAt:0,tags:[]};try{i=(await this.client.dataCatalog.publish(s,{token:this.client.token})).key,y.debug(`[domain:publish] Created catalog entry key: ${i}`)}catch(o){let a=U(o);this.formatter.error(a),process.exit(1)}}let r=Li.createSchema({scope:e.scope,lifecycle:e.lifecycle,version:e.version,changelog:e.changelog||void 0});y.debug(`[domain:publish] Publishing version '${e.version}' for catalog key '${i}'...`);try{let s=await this.client.dataCatalog.publishVersion(i,r,{token:this.client.token});return y.debug(`[domain:publish] Version published successfully with key: ${s.key}`),{catalogKey:i,versionKey:s.key,version:e.version}}catch(s){let o=U(s);this.formatter.error(o),process.exit(1)}}reportSuccess(e,t,i){this.formatter.success(`Successfully published version '${e.version}' of data domain to the data catalog!`,{fileId:e.fileId,catalogKey:t.catalogKey,versionKey:t.versionKey,version:e.version,scope:e.scope,lifecycle:e.lifecycle,fileVersion:i})}};var ia=class extends Fe{constructor(t,i,r,s=new Z,o=new zt(s)){super(i,r,s,o);this.file=t}file;async execute(){let t=this.resolveOrgId();y.debug(`[domain:mutate] Mutating domain. File=${this.file}, org=${t}, stdin=${this.options.stdin}, dryRun=${this.options.dryRun}, noValidate=${this.options.noValidate}`),this.validateInputParameters();let i=await this.loadAndValidateLocalSchema(),r=i.key;this.validateTargetFileId(r),this.options.validate!==!1&&!this.options.noValidate&&this.runPreflightValidation(i);let o=await this.loadDomain(t,r);this.assertEditableLifecycle(o.domain.lifecycle,r);let a=ti(o.originalSchema,i);if(a.length===0){this.handleNoOp(r,o.metaVersion);return}if(this.options.dryRun){this.handleDryRun(r,a);return}if(!await this.confirmDestructiveChanges(r,a)){console.log(ie.yellow("Mutation cancelled by user."));return}await this.applyPatch(t,r,a,o.metaVersion)}async loadDomain(t,i){try{return await this.domainLoader.loadDomain(t,i)}catch(r){r instanceof Error&&r.message.includes("is not a data domain")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:r.message}),process.exit(1)),r instanceof Error&&r.message.includes("Invalid data domain schema format")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:r.message}),process.exit(1)),(r&&typeof r=="object"&&"status"in r&&r.status===404||r instanceof Error&&(r.message.includes("not found")||r.message.includes("does not exist")))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Data domain '${i}' does not exist in organization '${t}'.`,detail:"Use 'apinow domain create' to create a new data domain."}),process.exit(1));let s=U(r);this.formatter.error(s),process.exit(1)}}validateInputParameters(){this.file&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),!this.file&&!this.options.stdin&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"A schema file path or --stdin is required.",detail:"Specify [file] or use --stdin."}),process.exit(1))}async loadAndValidateLocalSchema(){try{let t=await this.fileManager.parseMediaInput({mediaPath:this.file,stdin:this.options.stdin});t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"No schema input was provided."}),process.exit(1));let i=t.content;return i.kind&&i.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${i.kind}', but expected '${Ee}'.`}),process.exit(1)),i}catch(t){t instanceof Error&&(t.message.startsWith("Media file not found")||t.message==="Cannot specify both media path and STDIN."||t.message==="invalid API now platform file")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:t.message}),process.exit(1));let r=U(t);this.formatter.error(r),process.exit(1)}}validateTargetFileId(t){let i=this.options.file||this.options.id;i&&i!==t&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Mismatched file ID. The provided schema has key '${t}', but '--file' was specified as '${i}'.`}),process.exit(1))}runPreflightValidation(t){y.debug("[domain:mutate] Running pre-flight local schema validation...");try{let i=new Me(t,[],{readOnly:!0});this.validateDomain(i,{logWarnings:!0})}catch(i){this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Pre-flight data domain schema validation failed.",detail:i instanceof Error?i.message:String(i)}),process.exit(1)}}assertEditableLifecycle(t,i){(t==="committed"||t==="published")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Data domain '${i}' is in '${t}' state and cannot be mutated.`,detail:"Transition the domain to 'draft' state first using 'apinow domain transition draft --ver <newVer>'."}),process.exit(1))}handleNoOp(t,i){y.debug("[domain:mutate] No changes detected between local schema and remote domain."),this.formatter.format==="json"?console.log(JSON.stringify({fileId:t,updated:!1,version:i,message:"No changes detected. Data domain is already up-to-date."},null,2)):this.formatter.success("No changes detected. Data domain is already up-to-date.")}handleDryRun(t,i){if(y.debug(`[domain:mutate] Dry-run completed with ${i.length} patch operation(s).`),this.formatter.format==="json")console.log(JSON.stringify({fileId:t,dryRun:!0,operationsCount:i.length,patch:i},null,2));else{console.log(ie.cyan(`\u2139 [Dry-run] Computed ${i.length} patch operation(s) for domain '${t}':`));for(let r of i){let s=r.op==="add"?ie.green("+"):r.op==="remove"?ie.red("-"):ie.yellow("~");console.log(` ${s} [${r.op}] ${r.path}`)}console.log(""),this.formatter.success("Dry-run completed successfully. No changes were applied to the server.")}}async confirmDestructiveChanges(t,i){return i.some(s=>s.op==="remove")&&!this.options.yes&&process.stdout.isTTY?await oo(`This mutation will remove elements from data domain '${t}'. Do you want to proceed?`,!1):!0}async applyPatch(t,i,r,s){try{let o=await this.fileManager.patchMedia(t,i,{patchOps:r,version:s});y.debug(`[domain:mutate] Patch applied successfully. New file version: ${o.newVersion}`),this.formatter.success(`Successfully mutated data domain '${i}' (new file version: ${o.newVersion}, ${r.length} operation(s) applied).`,{fileId:i,fileVersion:o.newVersion,operationsCount:r.length,updated:!0})}catch(o){let a=U(o);this.formatter.error(a),process.exit(1)}}};var ra=class extends Fe{constructor(t,i,r,s=new Z){super(i,r,s);this.queryArg=t}queryArg;async execute(){let t=this.resolveOrgId(),i=await this.resolveQueries();y.debug(`[domain:search] Searching data domain files for org: ${t}, queries: ${i.join(",")}, parent: ${this.options.parent||"all"}, limit: ${this.options.limit||"none"}`);try{let r=await this.fileManager.search(t,{kind:"domain",query:i,parent:this.options.parent,limit:this.options.limit});y.debug(`[domain:search] Found ${r.length} matching data domain files.`);let s=r.map(o=>({id:o.key,name:o.info?.name||"",parent:o.parents&&o.parents.length>0?o.parents[o.parents.length-1]:"root",isShortcut:o.isShortcut?"Yes":"No"}));this.formatter.list(s,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}async resolveQueries(){let t=[];if(this.queryArg&&t.push(this.queryArg),this.options.query&&this.options.query.length>0&&t.push(...this.options.query),t.length===0&&process.stdout.isTTY){let i=await pe("Enter search query:");i&&i.trim()&&t.push(i.trim())}return t.length===0&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Search query is required.",detail:"Specify <query> or --query <query...>."}),process.exit(1)),t}};function Jd(c){let e=c.command("domain").description("Manage Data Domains");e.command("list").description("List data domain files in an organization").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Filter by parent folder ID").action(async t=>{let i=new K({format:N.resolved.format});await new Go(t,i).execute()}),e.command("search [query]").description("Search data domain files by name or keyword").option("--query <query...>","Search query keywords").option("--parent <parent>","Filter by parent folder ID").option("--limit <limit>","Maximum number of results to return",Yi).option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new ra(t,i,r).execute()}),e.command("create").description("Create a new data domain file record (and optionally upload domain schema media)").option("--name <name>","Name of the data domain").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Parent folder ID").option("--media <path>","Local path to the domain schema JSON to upload").option("--stdin","Read domain schema content from STDIN").action(async t=>{let i=new K({format:N.resolved.format});await new Jo(t,i).execute()}),e.command("read").description("Read data domain file metadata or schema media content").option("--file <fid>","File ID of the data domain").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--meta","Read file metadata (default)").option("--media","Read domain schema media content").action(async t=>{let i=new K({format:N.resolved.format});await new Wo(t,i).execute()}),e.command("transition [state]").description("Transition the lifecycle state of a data domain (draft, committed, published)").option("--file <fid>","File ID of the data domain").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--ver <ver>","New version (required when transitioning from published to draft)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new ea(t,i,r).execute()}),e.command("publish").description("Publish a data domain file to the data catalog").option("--file <fid>","File ID of the data domain").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--ver <ver>","Semantic version to publish (e.g. 1.0.0)").option("--catalog-version <ver>","Semantic version alias (e.g. 1.0.0)").option("--scope <scope>","Publish scope: public, organization, private","public").option("--name <name>","Name for the catalog entry (defaults to domain name)").option("--description <desc>","Description of the catalog entry (defaults to domain description)").option("--lifecycle <lifecycle>","Version lifecycle status (dev, beta, stable)","stable").option("--changelog <changelog>","Changelog description for this version").action(async t=>{let i=new K({format:N.resolved.format});await new ta(t,i).execute()}),e.command("mutate [file]").alias("apply").description("Mutate a data domain by computing and applying a JSON patch against the server version").option("--stdin","Read domain schema content from STDIN").option("--file <fid>","File ID of the data domain (optional, defaults to key in schema)").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--dry-run","Compute diff and preview patch operations without applying them").option("--no-validate","Skip local pre-flight domain schema validation").option("-y, --yes","Automatically accept confirmation prompts for destructive changes").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new ia(t,i,r).execute()})}var et=class extends Ae{fileManager;constructor(e,t,i=new Z){super(e,t),this.fileManager=i}async resolveFileId(e,t="Select an API model file:"){let i=this.options.file||this.options.id;if(!i&&process.stdout.isTTY){y.debug("[api] File ID not provided; searching API model files for selection...");try{let r=await this.fileManager.search(e,{kind:"api"});r.length>0&&(i=await Ce(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){y.debug(`[api] Failed to search API files for selection: ${r}`)}}return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1)),i}};var sa=class extends et{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[api:list] Searching API model files for org: ${e}, parent: ${this.options.parent||"all"}`);try{let t=await this.fileManager.search(e,{kind:"api",parent:this.options.parent});y.debug(`[api:list] Found ${t.length} API files.`);let i=t.map(r=>({id:r.key,name:r.info?.name||"",parent:r.parents&&r.parents.length>0?r.parents[r.parents.length-1]:"root",isShortcut:r.isShortcut?"Yes":"No"}));this.formatter.list(i,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var oa=class extends et{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[api:create] Creating API model file: name=${this.options.name}, org=${e}, parent=${this.options.parent}, media=${this.options.media}, stdin=${this.options.stdin}`),this.options.media&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let t=this.options.name;!t&&process.stdout.isTTY&&(t=await pe("Enter API model name:")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));try{let i=await this.fileManager.parseMediaInput({mediaPath:this.options.media,stdin:this.options.stdin});if(i!==void 0){let s=i.content;s.kind&&s.kind!==ke&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${s.kind}', but expected '${ke}'.`}),process.exit(1))}let r=await this.fileManager.create(e,{name:t,kind:"api",parent:this.options.parent,mediaContent:i?.content,key:i?.key});this.formatter.success("API model created successfully!",r)}catch(i){i instanceof Error&&(i.message.startsWith("Media file not found")||i.message==="Cannot specify both media path and STDIN.")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1));let s=U(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var aa=class extends et{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;y.debug(`[api:read] Reading API model file: file=${t}, org=${e}, meta=${this.options.meta}, media=${this.options.media}`);let i=await this.resolveFileId(e,"Select an API model file to read:");try{if(this.options.media){y.debug(`[api:read] Fetching media schema for API model file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;y.debug("[api:read] Media retrieved successfully."),this.formatter.format==="json"?console.log(JSON.stringify(s,null,2)):console.log(typeof s=="object"&&s!==null?JSON.stringify(s,null,2):s)}else{y.debug(`[api:read] Fetching metadata for API model file ID '${i}'...`);let r=await this.fileManager.read(e,i);y.debug("[api:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}};var na=class extends et{constructor(t,i,r,s=new Z){super(i,r,s);this.queryArg=t}queryArg;async execute(){let t=this.resolveOrgId(),i=await this.resolveQueries();y.debug(`[api:search] Searching API model files for org: ${t}, queries: ${i.join(",")}, parent: ${this.options.parent||"all"}, limit: ${this.options.limit||"none"}`);try{let r=await this.fileManager.search(t,{kind:"api",query:i,parent:this.options.parent,limit:this.options.limit});y.debug(`[api:search] Found ${r.length} matching API files.`);let s=r.map(o=>({id:o.key,name:o.info?.name||"",parent:o.parents&&o.parents.length>0?o.parents[o.parents.length-1]:"root",isShortcut:o.isShortcut?"Yes":"No"}));this.formatter.list(s,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}async resolveQueries(){let t=[];if(this.queryArg&&t.push(this.queryArg),this.options.query&&this.options.query.length>0&&t.push(...this.options.query),t.length===0&&process.stdout.isTTY){let i=await pe("Enter search query:");i&&i.trim()&&t.push(i.trim())}return t.length===0&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Search query is required.",detail:"Specify <query> or --query <query...>."}),process.exit(1)),t}};import ri from"node:fs";import Is from"node:path";function Kt(c,e){let t=c.domain||e;return t?`${t}:${c.key}`:c.key}function ys(c){if(!c)throw new b("Cannot generate parameter name from an empty string.",{code:"E_INVALID_PARAM_NAME",help:"The entity name used for path parameter generation is empty."});let e=c.replace(/([a-z])([A-Z])/g,"$1 $2");e=e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");let i=e.replace(/[^a-zA-Z0-9]/g," ").split(/\s+/).filter(Boolean);if(i.length===0)throw new b(`Cannot generate a valid parameter name from "${c}".`,{code:"E_INVALID_PARAM_NAME",help:"The entity name must contain alphanumeric characters to generate a path parameter."});let s=i.map((o,a)=>{let n=o.toLowerCase();return a===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join("");return/^[0-9]/.test(s)&&(s="_"+s),`${s}Id`}function Ai(c){let e=c.trim(),t=e.startsWith("/")?e:`/${e}`;return t==="/"?"/":t.replace(/\/+$/,"")}function ca(c,e){let t=c.endsWith("/")?c.slice(0,-1):c,i=e.startsWith("/")?e:`/${e}`;return`${t}${i}`}var ne=class{key;type;parent;isIdentityConstraining=!1;isBroadIdentityRule=!1;constructor(e,t={}){this.parent=e,this.key=t.key||W(),this.type=t.type??""}static isAccessRule(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.type=="string"&&t.kind!=="predicateGroup"}toJSON(){return{key:this.key,type:this.type}}};var bs=class c{description;key;rate;interval;burst;constructor(e={}){this.description=e.description,this.key=c.isRateLimitRuleKey(e.key)?structuredClone(e.key):void 0,this.rate=typeof e.rate=="number"?e.rate:void 0,this.interval=c.isRateLimitRuleInterval(e.interval)?e.interval:void 0,this.burst=typeof e.burst=="number"?e.burst:void 0}toJSON(){let e={};return this.description&&(e.description=this.description),c.isRateLimitRuleKey(this.key)&&(e.key=structuredClone(this.key)),typeof this.rate=="number"&&(e.rate=this.rate),c.isRateLimitRuleInterval(this.interval)&&(e.interval=this.interval),typeof this.burst=="number"&&(e.burst=this.burst),e}static isRateLimitRuleInterval(e){return typeof e!="string"?!1:["second","minute","hour","day"].includes(e)}static isRateLimitRuleKey(e){if(typeof e!="object"||e===null)return!1;let t=e;return"type"in t&&(t.type==="ip"||t.type==="userId"||t.type==="role")}};var ii=class{rules;constructor(e={}){this.rules=e.rules?.map(t=>new bs(t))||[]}toJSON(){return{rules:this.rules.map(e=>e.toJSON())}}};var Mi=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,t),this.type="allowAuthenticated"}};var la=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,t),this.type="allowPublic"}};var da=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;domains;requireVerified;constructor(e,t={}){super(e,t),this.type="matchEmailDomain",this.domains=t.domains?[...t.domains]:[],this.requireVerified=t.requireVerified??!0}toJSON(){return{...super.toJSON(),domains:structuredClone(this.domains),requireVerified:this.requireVerified}}};var Ui=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;target;constructor(e,t={}){super(e,t),this.type="matchResourceOwner",this.association=t.association?{...t.association}:void 0,this.target=t.target??"association"}toJSON(){let e={...super.toJSON(),target:this.target};return this.association&&(e.association={...this.association}),e}};var pa=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;parameters;constructor(e,t={}){super(e,t),this.type="matchPathParameter",this.parameters=Array.isArray(t.parameters)?t.parameters.map(i=>({...i})):[]}toJSON(){return{...super.toJSON(),parameters:this.parameters.map(t=>({...t}))}}};var zi=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;attribute;operator;value;values;constructor(e,t={}){super(e,t),this.type="matchResourceAttribute",this.attribute=t.attribute??"",this.operator=t.operator??"equal",this.value=t.value!==void 0?t.value:"",t.values!==void 0?this.values=Array.isArray(t.values)?[...t.values]:t.values:this.values=[]}static isArrayOperator(e){return e==="in"||e==="notIn"}static isScalarOperator(e){return e==="equal"||e==="notEqual"||e==="greaterThan"||e==="greaterThanOrEqual"||e==="lessThan"||e==="lessThanOrEqual"||e==="startsWith"||e==="endsWith"||e==="contains"}static isArray(e){return typeof e=="string"?c.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?c.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isScalarOperator(e.operator):!1}static assertArray(e){if(!c.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!c.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return c.isArrayOperator(this.operator)}get isScalar(){return c.isScalarOperator(this.operator)}toJSON(){let e=super.toJSON();return this.isArray?{...e,type:"matchResourceAttribute",attribute:this.attribute,operator:this.operator,values:Array.isArray(this.values)?[...this.values]:[]}:{...e,type:"matchResourceAttribute",attribute:this.attribute,operator:this.operator,value:this.value}}};var ua=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;allowedStatuses;deniedStatuses;constructor(e,t={}){super(e,t),this.type="lifecycleStatus",this.allowedStatuses=t.allowedStatuses?[...t.allowedStatuses]:[],this.deniedStatuses=t.deniedStatuses?[...t.deniedStatuses]:[]}toJSON(){let e={...super.toJSON()};return this.allowedStatuses.length>0&&(e.allowedStatuses=structuredClone(this.allowedStatuses)),this.deniedStatuses.length>0&&(e.deniedStatuses=structuredClone(this.deniedStatuses)),e}};var Vi=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;property;operator;value;values;constructor(e,t={}){super(e,t),this.type="matchUserProperty",this.property=t.property??"",this.operator=t.operator??"equal",this.value=t.value!==void 0?t.value:"",t.values!==void 0?this.values=Array.isArray(t.values)?[...t.values]:t.values:this.values=[]}static isArrayOperator(e){return e==="in"||e==="notIn"}static isScalarOperator(e){return e==="equal"||e==="notEqual"||e==="greaterThan"||e==="greaterThanOrEqual"||e==="lessThan"||e==="lessThanOrEqual"||e==="startsWith"||e==="endsWith"||e==="contains"}static isArray(e){return typeof e=="string"?c.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?c.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isScalarOperator(e.operator):!1}static assertArray(e){if(!c.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!c.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return c.isArrayOperator(this.operator)}get isScalar(){return c.isScalarOperator(this.operator)}toJSON(){let e=super.toJSON();return this.isArray?{...e,type:"matchUserProperty",property:this.property,operator:this.operator,values:Array.isArray(this.values)?[...this.values]:[]}:{...e,type:"matchUserProperty",property:this.property,operator:this.operator,value:this.value}}};var ma=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;mode;allowed;denied;minimumRole;maximumRole;roleMatch;constructor(e,t={}){super(e,t),this.type="matchUserRole",this.mode=t.mode??"allowlist",Array.isArray(t.allowed)&&(this.allowed=[...t.allowed]),Array.isArray(t.denied)&&(this.denied=[...t.denied]),typeof t.minimumRole=="string"&&(this.minimumRole=t.minimumRole),typeof t.maximumRole=="string"&&(this.maximumRole=t.maximumRole),t.roleMatch&&(this.roleMatch=t.roleMatch)}toJSON(){let t={...super.toJSON(),mode:this.mode};return this.allowed!==void 0&&(t.allowed=[...this.allowed]),this.denied!==void 0&&(t.denied=[...this.denied]),this.minimumRole!==void 0&&(t.minimumRole=this.minimumRole),this.maximumRole!==void 0&&(t.maximumRole=this.maximumRole),this.roleMatch!==void 0&&(t.roleMatch=this.roleMatch),t}};var Fi=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;isIdentityConstraining=!0;isBroadIdentityRule=!1;roles;constructor(e,t={}){super(e,t),this.roles=Array.isArray(t.roles)?[...t.roles]:typeof t.roles=="string"?[t.roles]:[]}toJSON(){return{...super.toJSON(),roles:[...this.roles]}}};var ha=class c extends Fi{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchOrganizationRole"}};var fa=class c extends Fi{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchProjectRole"}toJSON(){return{...super.toJSON(),type:"matchProjectRole",roles:[...this.roles]}}};var ga=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchProjectStakeholder"}toJSON(){return{...super.toJSON(),type:"matchProjectStakeholder"}}};var ya=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;allowedRoles;constructor(e,t={}){super(e,t),this.type="matchAssociation",this.association=t.association?{...t.association}:{key:""},this.allowedRoles=t.allowedRoles?[...t.allowedRoles]:[]}toJSON(){let e=super.toJSON();return e.type="matchAssociation",e.association={...this.association},this.allowedRoles&&this.allowedRoles.length>0&&(e.allowedRoles=[...this.allowedRoles]),e}};var ba=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="relationalResourceOwner"}toJSON(){return{...super.toJSON()}}};function Wd(c,e){switch(e.type){case"allowAuthenticated":return new Mi(c,e);case"allowPublic":return new la(c,e);case"matchEmailDomain":return new da(c,e);case"matchResourceOwner":return new Ui(c,e);case"relationalResourceOwner":return new ba(c,e);case"matchPathParameter":return new pa(c,e);case"matchResourceAttribute":return new zi(c,e);case"lifecycleStatus":return new ua(c,e);case"matchUserProperty":return new Vi(c,e);case"matchUserRole":return new ma(c,e);case"matchOrganizationRole":return new ha(c,e);case"matchProjectRole":return new fa(c,e);case"matchProjectStakeholder":return new ga(c,e);case"matchAssociation":return new ya(c,e);default:throw new b("Unknown access rule kind",{code:"E_UNKNOWN_ACCESS_RULE_KIND",status:422})}}var qe=class c{kind="predicateGroup";key;label;style;children;parent;constructor(e,t={}){this.parent=e,this.key=t.key||W(),t.label!==void 0&&(this.label=t.label),this.style=t.style==="or"?"or":"and",this.children=Array.isArray(t.children)?t.children.map(i=>i instanceof c||i instanceof ne?i:c.isPredicateGroup(i)?new c(this.parent,i):Wd(this.parent,i)):[]}static isPredicateGroup(e){return!e||typeof e!="object"?!1:e.kind==="predicateGroup"}getLeafRules(){let e=[];for(let t of this.children)t instanceof c?e.push(...t.getLeafRules()):e.push(t);return e}findChild(e){for(let t of this.children){if(t.key===e)return t;if(t instanceof c){let i=t.findChild(e);if(i)return i}}}findRule(e){for(let t of this.children)if(t instanceof c){let i=t.findRule(e);if(i)return i}else if(t.key===e)return t}findGroup(e){for(let t of this.children)if(t instanceof c){if(t.key===e)return t;let i=t.findGroup(e);if(i)return i}}removeChild(e){let t=this.children.findIndex(i=>i.key===e);if(t!==-1)return this.children.splice(t,1),!0;for(let i of this.children)if(i instanceof c&&i.removeChild(e))return!0;return!1}toJSON(){let e={kind:"predicateGroup",key:this.key,style:this.style,children:this.children.map(t=>t.toJSON())};return this.label!==void 0&&this.label!==""&&(e.label=this.label),e}};var It=class{key;label;predicate;parent;constructor(e,t={}){this.parent=e,this.key=t.key||W(),t.label!==void 0&&(this.label=t.label),t.predicate instanceof qe?this.predicate=t.predicate:this.predicate=new qe(this.parent,t.predicate??{kind:"predicateGroup",key:W(),style:"and",children:[]})}findChild(e){return this.predicate.key===e?this.predicate:this.predicate.findChild(e)}findRule(e){return this.predicate.findRule(e)}findGroup(e){return this.predicate.key===e?this.predicate:this.predicate.findGroup(e)}removeChild(e){return this.predicate.removeChild(e)}toJSON(){let e={key:this.key,predicate:this.predicate.toJSON()};return this.label!==void 0&&this.label!==""&&(e.label=this.label),e}};var Te=class{kind;accessScenarios;overrideParentScenarios;rateLimiting;projection;parent;constructor(e,t={}){this.kind=t.kind??"",this.accessScenarios=t.accessScenarios?t.accessScenarios.map(i=>new It(this,i)):[],this.overrideParentScenarios=t.overrideParentScenarios??!1,t.rateLimiting&&(this.rateLimiting=new ii(t.rateLimiting)),t.projection&&(this.projection=structuredClone(t.projection)),this.parent=e}toJSON(){let e={kind:this.kind};return this.accessScenarios.length>0&&(e.accessScenarios=this.accessScenarios.map(t=>t.toJSON())),this.overrideParentScenarios&&(e.overrideParentScenarios=!0),this.rateLimiting&&(e.rateLimiting=this.rateLimiting.toJSON()),this.projection&&(e.projection=structuredClone(this.projection)),e}getAllScenarios(){if(this.overrideParentScenarios)return[...this.accessScenarios];let e=[...this.accessScenarios,...this.parent?.accessScenarios??[],...this.parent?.api?.accessScenarios??[]],t=new Set,i=[];for(let r of e)t.has(r.key)||(t.add(r.key),i.push(r));return i}getAllRateLimiters(){let e=this.parent.getAllRateLimiters();return this.rateLimiting&&e.push(this.rateLimiting),e}};var ks=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="create"}toJSON(){return{...super.toJSON(),kind:"create"}}static isCreateAction(e){return e.kind==="create"}static isCreateActionSchema(e){return e.kind==="create"}};var tt=class extends Te{kind;strategy;retentionPeriod;constructor(e,t={}){super(e,t),this.kind="delete",this.strategy=t.strategy||"soft",this.retentionPeriod=t.retentionPeriod??30}toJSON(){return{...super.toJSON(),kind:"delete",strategy:this.strategy,retentionPeriod:this.retentionPeriod}}static isDeleteAction(e){return e.kind==="delete"}static isDeleteActionSchema(e){return e.kind==="delete"}};var Pt=class extends Te{kind;cacheTtl;constructor(e,t={}){super(e,t),this.kind="list",this.cacheTtl=t.cacheTtl}toJSON(){let e={...super.toJSON(),kind:"list"};return this.cacheTtl!==void 0&&(e.cacheTtl=this.cacheTtl),e}static isListAction(e){return e.kind==="list"}static isListActionSchema(e){return e.kind==="list"}};var qi=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="read"}toJSON(){return{...super.toJSON(),kind:"read"}}static isReadAction(e){return e.kind==="read"}static isReadActionSchema(e){return e.kind==="read"}};var Rt=class extends Te{kind;maxAstDepth;constructor(e,t={}){super(e,t),this.kind="search",this.maxAstDepth=t.maxAstDepth}toJSON(){let e={...super.toJSON(),kind:"search"};return this.maxAstDepth!==void 0&&(e.maxAstDepth=this.maxAstDepth),e}static isSearchActionSchema(e){return e.kind==="search"}static isSearchAction(e){return e.kind==="search"}};var Ki=class extends Te{kind;allowedMethods;constructor(e,t={}){super(e,t),this.kind="update",this.allowedMethods=t.allowedMethods?[...t.allowedMethods]:["PATCH"]}toJSON(){return{...super.toJSON(),kind:"update",allowedMethods:structuredClone(this.allowedMethods)}}static isUpdateAction(e){return e.kind==="update"}static isUpdateActionSchema(e){return e.kind==="update"}};var vs=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="link"}toJSON(){return{...super.toJSON(),kind:"link"}}static isLinkAction(e){return e.kind==="link"}static isLinkActionSchema(e){return e.kind==="link"}};var ws=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="unlink"}toJSON(){return{...super.toJSON(),kind:"unlink"}}static isUnlinkAction(e){return e.kind==="unlink"}static isUnlinkActionSchema(e){return e.kind==="unlink"}};var Bi=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="restore"}toJSON(){return{...super.toJSON(),kind:"restore"}}static isRestoreAction(e){return e.kind==="restore"}static isRestoreActionSchema(e){return e.kind==="restore"}};function Qc(c,e){switch(e.kind){case"list":return new Pt(c,e);case"read":return new qi(c,e);case"create":return new ks(c,e);case"update":return new Ki(c,e);case"delete":return new tt(c,e);case"search":return new Rt(c,e);case"link":return new vs(c,e);case"unlink":return new ws(c,e);case"restore":return new Bi(c,e);default:throw new b("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}function Hd(c,e){switch(e){case"list":return new Pt(c);case"read":return new qi(c);case"create":return new ks(c);case"update":return new Ki(c);case"delete":return new tt(c);case"search":return new Rt(c);case"link":return new vs(c);case"unlink":return new ws(c);case"restore":return new Bi(c);default:throw new b("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}var hr=class c{kind;key;entity;hasCollection;collectionPath;resourcePath;isRoot;parent;actions;accessScenarios;rateLimiting;paginationContract;truncated;api;static createSchema(e={}){let{key:t=W(),entity:i={key:""},collectionPath:r,resourcePath:s="/",hasCollection:o=!0,isRoot:a,parent:n,actions:l=[],accessScenarios:d,rateLimiting:p,truncated:m,paginationContract:h}=e,f=!!n?.selfRoute,k={kind:Ht,key:t,entity:{...i},hasCollection:f?!1:o,resourcePath:f?"/me":s,actions:l.map(w=>({...w}))};return!f&&r!==void 0&&(k.collectionPath=r),a!==void 0&&(k.isRoot=f?!1:a),n!==void 0&&(k.parent={key:n.key,...n.association?{association:{...n.association}}:{},...n.selfRoute!==void 0?{selfRoute:n.selfRoute}:{}}),Array.isArray(d)&&(k.accessScenarios=d.map(w=>({...w}))),p!==void 0&&(k.rateLimiting={...p}),m!==void 0&&(k.truncated=m),h!==void 0&&(k.paginationContract=structuredClone(h)),k}constructor(e,t){this.api=e;let i=c.createSchema(t);this.kind=i.kind,this.key=i.key,this.entity=i.entity,this.hasCollection=i.hasCollection,this.collectionPath=i.collectionPath,this.resourcePath=i.resourcePath,this.isRoot=i.isRoot,this.parent=i.parent,this.actions=i.actions?i.actions.map(r=>Qc(this,r)):[],this.accessScenarios=i.accessScenarios?i.accessScenarios.map(r=>new It(this,r)):[],i.rateLimiting&&(this.rateLimiting=new ii(i.rateLimiting)),this.truncated=i.truncated,i.paginationContract&&(this.paginationContract=structuredClone(i.paginationContract))}toJSON(){let e={kind:this.kind,key:this.key,entity:{...this.entity},resourcePath:this.resourcePath,actions:this.actions.map(t=>t.toJSON()),hasCollection:this.hasCollection};return this.collectionPath!==void 0&&(e.collectionPath=this.collectionPath),this.isRoot!==void 0&&(e.isRoot=this.isRoot),this.parent!==void 0&&(e.parent={key:this.parent.key,...this.parent.association?{association:{...this.parent.association}}:{},...this.parent.selfRoute!==void 0?{selfRoute:this.parent.selfRoute}:{}}),Array.isArray(this.accessScenarios)&&this.accessScenarios.length>0&&(e.accessScenarios=this.accessScenarios.map(t=>t.toJSON())),this.rateLimiting!==void 0&&(e.rateLimiting=this.rateLimiting.toJSON()),this.truncated!==void 0&&(e.truncated=this.truncated),this.paginationContract&&(e.paginationContract=structuredClone(this.paginationContract)),e}setCollectionPath(e){if(!this.hasCollection)throw new b("Cannot set collection path on an exposure that does not have a collection",{code:"E_PATH_MISSING",help:"The exposed entity you are trying to set a collection path for does not have a collection."});let i=Ai(e).split("/").filter(Boolean);if(i.length!==1)throw new b(`Collection path must contain exactly one segment. Received: "${e}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set path must have a single path segment (e.g., `/products`)"});let r=`/${i[0]}`;if(this.isRoot&&this.api.findCollectionPathCollision(r,this.key))throw new b(`Collection path "${r}" is already in use by another root entity.`,{code:"E_PATH_INUSE",help:"The set path is already in use by another root entity."});let s="";if(this.resourcePath&&this.resourcePath!=="/"){let n=this.resourcePath.split("/").filter(Boolean)[1];n&&/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(n)&&(s=n)}if(!s){let a=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!a||!a.info.name)throw new b("Cannot generate a semantic parameter name because the associated entity or its name is missing.",{code:"E_ENTITY_NOT_FOUND",help:"Ensure the exposed entity points to a valid domain entity with a defined name."});s=`{${ys(a.info.name)}}`}let o=`${r}/${s}`;this.#i(o),this.collectionPath=r,this.resourcePath=o}setResourcePath(e){let t=Ai(e),i=t.split("/").filter(Boolean);if(this.hasCollection){if(!this.collectionPath)throw new b("Cannot set resource path: missing collection path for this exposure",{code:"E_PATH_MISSING",help:"Set the collection path on the exposed entity first."});let r=this.collectionPath.split("/").filter(Boolean);if(r.length!==1)throw new b(`Invalid stored collection path "${this.collectionPath}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set collection path must have a single path segment (e.g., `/products`)"});if(i.length!==2)throw new b(`Resource path must be exactly two segments (collection + parameter). Received: "${t}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set resource path must have exactly two segments (collection + parameter)."});let[s,o]=i;if(s!==r[0])throw new b(`Resource path must start with the collection segment "${r[0]}". Received: "${s}"`,{code:"E_PATH_MISMATCH",help:"Set the resource path to the same value as the collection path + the parameter value."});if(!/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(o))throw new b(`The second segment must be a parameter in braces, e.g. {id}. Received: "${o}"`,{code:"E_PARAMETER_INVALID",help:"Use the braces to surround the parameter name, e.g., {productId}."});this.resourcePath!==t&&(this.#i(`/${s}/${o}`),this.resourcePath=`/${s}/${o}`);return}if(i.length!==1)throw new b(`Resource path must contain exactly one segment when no collection is present. Received: "${t}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set resource path must have exactly one segment."});if(this.isRoot&&this.api.findResourcePathCollision(t,this.key))throw new b(`Resource path "${t}" is already in use by another root entity.`,{code:"E_PATH_INUSE",help:"The set path is already in use by another root entity."});this.resourcePath!==t&&(this.#i(`/${i[0]}`),this.resourcePath=`/${i[0]}`)}#e(e){let i=[...e.join("/").matchAll(/\{([^}]+)\}/g)].map(s=>s[1]),r=new Set;for(let s of i){if(r.has(s))throw new b(`Duplicate path parameter "{${s}}" detected in branch hierarchy.`,{code:"E_PATH_PARAM_COLLISION",help:"Change the parameter name in either this resource or its ancestor to ensure unique parameter names."});r.add(s)}}#t(e,t){for(let i of this.api.exposes.values())if(i.parent?.key===e){let r=[...t,i.resourcePath];this.#e(r),this.#t(i.key,r)}}#i(e){let t=[e],i=this.parent?.key;for(;i;){let r=this.api.exposes.get(i);if(!r)break;t.unshift(r.resourcePath),i=r.parent?.key}this.#e(t),this.#t(this.key,t)}getAbsoluteResourcePath(){let e=Ai(this.resourcePath);if(this.parent?.selfRoute){let s=this.api.exposes.get(this.parent.key)?.getAbsoluteCollectionPath();return s?ca(s,e):e}let t=e,i=this.parent?.key;for(;i;){let r=this.api.exposes.get(i);if(!r)break;let s=Ai(r.resourcePath);t=ca(s,t),i=r.parent?.key}return t}getAbsoluteCollectionPath(){if(!this.hasCollection||!this.collectionPath)return;let e=Ai(this.collectionPath),t=this.parent?.key;for(;t;){let i=this.api.exposes.get(t);if(!i)break;let r=Ai(i.resourcePath);e=ca(r,e),t=i.parent?.key}return e}getAllRateLimiters(){let e=[];this.api.rateLimiting&&e.push(this.api.rateLimiting);let t=this;for(;t;)t.rateLimiting&&e.push(t.rateLimiting),t=t.parent?this.api.exposes.get(t.parent.key):void 0;return e}getAllRateLimiterRules(){let e=[];this.api.rateLimiting&&e.push(...this.api.rateLimiting.rules);let t=this;for(;t;)t.rateLimiting&&e.push(...t.rateLimiting.rules),t=t.parent?this.api.exposes.get(t.parent.key):void 0;return e}addAction(e){if(this.actions.some(i=>i.kind===e.kind))throw new b(`Action of kind "${e.kind}" already exists for this exposure`,{code:"E_ACTION_USED",help:"There's no need to add an API action again."});if(this.parent?.selfRoute&&!["read","update","delete","unlink"].includes(e.kind))throw new b(`Action "${e.kind}" is not allowed on a selfRoute exposure. Allowed actions are: read, update, delete, unlink.`,{code:"E_INVALID_ACTION",help:"Only 'read', 'update', 'delete', and 'unlink' actions are permitted on a selfRoute."});let t=Qc(this,e);if(this.parent?.selfRoute){let i=new It(t,{key:`${this.key}-current-user-scenario`,label:"Current User Invariant"});i.predicate.children=[new Mi(t),new Ui(t,{target:"user-entity"})],t.accessScenarios=[i]}return this.actions.push(t),t}addActionFromKind(e){if(this.actions.some(i=>i.kind===e))throw new b(`Action of kind "${e}" already exists for this exposure`,{code:"E_ACTION_USED",help:"There's no need to add an API action again."});if(this.parent?.selfRoute&&!["read","update","delete","unlink"].includes(e))throw new b(`Action "${e}" is not allowed on a selfRoute exposure. Allowed actions are: read, update, delete, unlink.`,{code:"E_INVALID_ACTION",help:"Only 'read', 'update', 'delete', and 'unlink' actions are permitted on a selfRoute."});let t=Hd(this,e);if(this.parent?.selfRoute){let i=new It(t,{key:`${this.key}-current-user-scenario`,label:"Current User Invariant"});i.predicate.children=[new Mi(t),new Ui(t,{target:"user-entity"})],t.accessScenarios=[i]}return this.actions.push(t),t}createPaginationContract(){let e=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!e)throw new b(`Entity "${this.entity.key}" not found"`,{code:"E_ENTITY_NOT_FOUND",help:"The set entity does not exist."});this.paginationContract?(this.paginationContract.filterableFields=[],this.paginationContract.searchableFields=[],this.paginationContract.sortableFields=[]):this.paginationContract={filterableFields:[],searchableFields:[],sortableFields:[]};for(let t of e.properties)t.index&&(this.paginationContract.filterableFields.push(t.key),this.paginationContract.sortableFields.push(t.key)),t.search&&this.paginationContract.searchableFields.push(t.key)}getSubResources(e=!1){let t=[],i=r=>{for(let s of this.api.exposes.values())s.parent?.key===r&&(t.push(s),e&&i(s.key))};return i(this.key),t}findSubResource(e,t=!1){let i=this.getSubResources(t),r=Ai(e);return i.find(s=>{if(s.key===e||s.entity.key===e)return!0;let o=this.api.domain?.findEntity(s.entity.key,s.entity.domain);if(o&&o.info.name===e)return!0;if(s.hasCollection&&s.collectionPath){if(s.collectionPath===e||s.collectionPath===r)return!0;let n=s.getAbsoluteCollectionPath();if(n&&(n===e||n===r))return!0}if(s.resourcePath===e||s.resourcePath===r)return!0;let a=s.getAbsoluteResourcePath();return!!(a&&(a===e||a===r))})}getParentExposedEntity(){if(this.parent)return this.api.exposes.get(this.parent.key)}readDomainEntity(){let{entity:e,api:t}=this;if(t.domain)return t.domain.findEntity(e.key,e.domain)}getPathParameters(e={}){return e.absolute?[...this.getAbsoluteResourcePath().matchAll(/\{([^}]+)\}/g)].map(i=>i[1]):this.hasCollection?[...this.resourcePath.matchAll(/\{([^}]+)\}/g)].map(i=>i[1]):[]}exposeEntity(e,t){let i=this.api.domain;if(!i)throw new b("No domain attached to API model",{code:"E_NO_DOMAIN",help:"Attach a data domain to the API model before exposing entities."});let r=this.api.exposes.get(this.key);if(!r)throw new b(`Parent exposure not found: ${this.key}`,{code:"E_PARENT_NOT_FOUND",help:"Make sure the parent exposure key you provided is correct."});let s=r.readDomainEntity();if(!s)throw new b(`Parent entity not found in domain: ${r.entity.key}`,{code:"E_NO_ENTITY",help:"Make sure the parent entity exists in the data domain."});let o=i.findEntity(e.key,e.domain);if(!o)throw new b(`Entity not found in domain: ${e.key}`,{code:"E_NO_ENTITY",help:"Make sure the entity you are trying to expose exists in the data domain."});let a=i.findAssociation(t.key,t.domain);if(!a)throw new b(`No association found from "${s.info.getLabel()||s.key}" to "${e.key}"`,{code:"E_ASSOCIATION_NOT_FOUND",help:"Ensure there is a defined association in the data domain connecting these entities."});let n=s.key,l=o.key,d=a.getParentInstance()?.key,p=d===n||s.listAllParents("up").some(L=>L.key===d),m=a.targets.some(L=>L.key===l||o.listAllParents("up").some(P=>P.key===L.key));if(!p||!m)throw new b(`Association "${t.key}" does not connect parent "${s.info.getLabel()||n}" to "${o.info.getLabel()||l}".`,{code:"E_ASSOCIATION_NOT_FOUND",help:"Ensure there is a defined association in the data domain connecting these entities."});let h=Kt(e,i.key),f=Kt(t,i.key);for(let L of this.api.exposes.values())if(L.parent?.key===r.key&&Kt(L.entity,i.key)===h&&L.parent.association&&Kt(L.parent.association,i.key)===f)throw new b(`Entity ${e.key} is already exposed under this parent with this association.`,{code:"E_ENTITY_ALREADY_EXPOSED",help:"Do not try to expose the same entity with the same association under the same parent."});let k=a.getExposedName(),w=!!a.multiple,S=w?Et(k.toLocaleLowerCase()):k.toLocaleLowerCase(),E=ys(o.info.name||""),A=w?`/${S}`:void 0,_=w?`/${S}/{${E}}`:`/${S}`;if(w&&A){let L=new Set;for(let x of this.api.exposes.values())x.parent?.key===r.key&&x.hasCollection&&x.collectionPath&&L.add(x.collectionPath);let P=1,R=A;for(;L.has(A);)A=`${R}-${P}`,_=`${A}/{${E}}`,P++}let O=a.namespace&&this.api.domain?.key&&a.namespace!==this.api.domain.key,I={kind:Ht,key:W(),entity:{...e},actions:[],isRoot:!1,collectionPath:A,resourcePath:"",hasCollection:w,parent:{key:r.key,association:{key:a.key,...O?{domain:a.namespace}:{}}}},j=new c(this.api,I);return j.setResourcePath(_),this.api.exposes.set(j.key,j),this.api.notifyChange(),j}};var Ss=(c={})=>{let e={...ka,...c};return c.metadata&&(e.metadata={...c.metadata}),{id:g.Currency,config:e}},ka={storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1,validateCurrencyCode:!0},o1={USD_DECIMAL:Ss({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),USD_CENTS:Ss({storageFormat:"integer_cents",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),MULTI_CURRENCY:Ss({storageFormat:"complex_object",allowedCurrencies:["USD","EUR","GBP","JPY","CAD"],decimalPlaces:2,allowNegative:!1}),WITH_NEGATIVES:Ss({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!0}),HIGH_PRECISION:Ss({storageFormat:"decimal",defaultCurrency:"BTC",decimalPlaces:8,allowNegative:!1})};var va={requireVerification:!0,allowSubaddressing:!0,allowInternational:!0};var Yd={requireCountryCode:!0,format:"international",allowExtension:!1,requireVerification:!1,verificationMethod:"sms"};var el=["allowAuthenticated","allowPublic","matchEmailDomain","matchResourceOwner","relationalResourceOwner","matchPathParameter","matchResourceAttribute","lifecycleStatus","matchUserProperty","matchAssociation","matchProjectRole","matchProjectStakeholder"],Xm={allowAuthenticated:["api","exposure","action"],allowPublic:["api","exposure","action"],matchEmailDomain:["api","exposure","action"],matchUserRole:["api","exposure","action"],matchUserProperty:["api","exposure","action"],matchOrganizationRole:["exposure","action"],matchProjectRole:["exposure","action"],matchProjectStakeholder:["exposure","action"],matchResourceOwner:["exposure","action"],relationalResourceOwner:["exposure","action"],matchResourceAttribute:["exposure","action"],matchAssociation:["exposure","action"],matchPathParameter:["exposure","action"],lifecycleStatus:["exposure","action"]};function Xd(c,e){let t;switch(c){case"RBAC":t=[...el,"matchUserRole"];break;case"OrganizationRBAC":t=[...el,"matchOrganizationRole"];break;case"EnterpriseRBAC":t=[...el,"matchUserRole","matchOrganizationRole"];break;default:t=[];break}return e?t.filter(i=>Xm[i]?.includes(e)):t}function tl(c,e){if(e){let t=c.findEntity(e.key,e.domain);return t&&t.hasSemantic(g.User)?t:void 0}for(let t of c.listEntities({includeForeign:!0}))if(t.hasSemantic(g.User))return t}function As(c,e){let t=e||tl(c),i={hasUser:!1,hasUsername:!1,hasPassword:!1,hasRole:!1};if(!t)return i;i.userEntity=t,i.hasUser=!0;for(let r of t.withInheritedProperties())r.hasSemantic(g.UserRole)?(i.roleProperty=r,i.hasRole=!0):r.hasSemantic(g.Username)?(i.usernameProperty=r,i.hasUsername=!0):r.hasSemantic(g.Password)&&(i.passwordProperty=r,i.hasPassword=!0);return i}function Es(c){let e,t;for(let a of c.listEntities())if(!e&&a.hasSemantic(g.Organization)&&(e=a),!t&&a.hasSemantic(g.User)&&(t=a),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=Zd(i,g.OrganizationMembers,g.OrganizationRole),o=s;return!o&&e&&(o=Array.from(e.withInheritedProperties()).find(a=>a.hasSemantic(g.OrganizationRole))),!o&&t&&(o=Array.from(t.withInheritedProperties()).find(a=>a.hasSemantic(g.OrganizationRole))),{hasOrganization:!!e,hasMembersAssociation:!!r,hasOrganizationRole:!!o,orgEntity:e,membersAssoc:r,roleProperty:o}}function il(c){let e,t;for(let a of c.listEntities())if(!e&&a.hasSemantic(g.Project)&&(e=a),!t&&a.hasSemantic(g.User)&&(t=a),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=Zd(i,g.ProjectMembers,g.ProjectRole),o=s;return!o&&e&&(o=Array.from(e.withInheritedProperties()).find(a=>a.hasSemantic(g.ProjectRole))),!o&&t&&(o=Array.from(t.withInheritedProperties()).find(a=>a.hasSemantic(g.ProjectRole))),{hasProject:!!e,hasMembersAssociation:!!r,hasProjectRole:!!o,projectEntity:e,membersAssoc:r,roleProperty:o}}function Zd(c,e,t){let i,r;for(let s of c){let o=[];for(let a of s.listAssociations())o.push(a);for(let a of s.listAllParents("up"))for(let n of a.listAssociations())o.some(l=>l.key===n.key)||o.push(n);for(let a of o)if(a.hasSemantic(e)){let n=a.getSemantic(e);if(!n?.link&&!i&&(i=a),!n?.link)for(let l of a.properties)!r&&l.hasSemantic(t)&&(r=l)}}return{membersAssoc:i,roleProperty:r}}function Zm(c){let e=c.type,i=c.readWebBinding()?.format,r=c.multiple,s;if(e==="string"){let o=c.schema?.maximum,a=typeof o=="number"?o:void 0;if(c.schema?.defaultValue?.type==="function"&&c.schema.defaultValue.value==="random"){let n=c.schema.defaultValue.config;if(n){let l=0,d=!1;n.isFixed?n.length&&(l=n.length,d=!0):a&&(l=a,d=!0),d&&(n.prefix&&(l+=n.prefix.length),n.suffix&&(l+=n.suffix.length),(!a||l>a)&&(a=l))}}s=a?`VARCHAR(${a})`:"TEXT"}else if(e==="number"){let o=c.schema?.defaultValue?.type==="function"&&c.schema.defaultValue.value==="incremental";i==="int32"?s="INTEGER":i==="int64"?s="BIGINT":i==="float"||i==="double"?s="DOUBLE PRECISION":o?s="BIGINT":s="NUMERIC"}else e==="boolean"?s="BOOLEAN":e==="date"?s="DATE":e==="datetime"?s="TIMESTAMPTZ":e==="time"?s="TIME":e==="binary"||e==="json"?s="JSONB":s="TEXT";return r?`${s}[]`:s}function Qd(c){let e=c.getExposedName();if(!e)throw new b("Property missing a name definition.",{code:"E_PROPERTY_NAME_MISSING",status:500});let t=null;if(c.schema?.defaultValue){let p=c.schema.defaultValue.type,m=String(c.schema.defaultValue.value);if(p==="function"){let h=c.type;if(h==="string"){if(m==="uuid-v4"&&c.primary)throw new b("Function 'uuid-v4' cannot be used as a default for a primary key string.",{code:"E_INVALID_DEFAULT_FUNCTION",status:400});if(m!=="random"&&m!=="uuid-v4")throw new b(`Function '${m}' is not supported for string properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else if(h==="number"){if(m!=="incremental")throw new b(`Function '${m}' is not supported for number properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else if(["date","time","datetime"].includes(h)){if(m!=="now")throw new b(`Function '${m}' is not supported for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else throw new b(`Functions are not supported as default values for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}t={type:p,value:m}}let i=!!c.primary,r=!c.required&&!i,s=!!c.unique;!t&&c.hasSemantic(g.DeletedFlag)&&(t={type:"literal",value:"false"});let o=c.getSemantic(g.Currency);if(o){let p=o.config??{},m=p.storageFormat||ka.storageFormat;if(m==="complex_object")return[{name:e,dataType:"JSONB",isNullable:r,isPrimary:i,isUnique:s,defaultRule:null}];if(m==="decimal"||m==="integer_cents"){let h=p.decimalPlaces??ka.decimalPlaces,f=m==="decimal"?`NUMERIC(19, ${h})`:"BIGINT";return[{name:`${e}_amount`,dataType:f,isNullable:r,isPrimary:i,isUnique:s,defaultRule:t},{name:`${e}_currency`,dataType:"CHAR(3)",isNullable:r,isPrimary:!1,isUnique:!1,defaultRule:{type:"literal",value:p.defaultCurrency||"USD"}}]}}let a=[{name:e,dataType:Zm(c),isNullable:r,isPrimary:i,isUnique:s,defaultRule:t}],n=!1,l=c.getSemantic(g.Email);l&&(n=(l.config??va).requireVerification??!0);let d=c.getSemantic(g.Phone);return d&&(n=(d.config??Yd).requireVerification===!0),n&&a.push({name:`_${e}_verified`,dataType:"BOOLEAN",isNullable:!1,isPrimary:!1,isUnique:!1,defaultRule:{type:"literal",value:"false"}}),a}function Qm(c){let e=c.toUpperCase().split("(")[0];return e==="CHARACTER VARYING"&&(e="VARCHAR"),e==="CHARACTER"&&(e="CHAR"),e}function eh(c,e){let t=e.toUpperCase(),i=Qm(c.dataType),r=t.split("(")[0];if(i===r){if(i==="VARCHAR"){let o=c.dataType.match(/\((\d+)\)/),a=o?Number.parseInt(o[1],10):null,n=t.match(/\((\d+)\)/),l=n?Number.parseInt(n[1],10):null;return!!(!l||a&&l>=a)}return!0}return{INTEGER:["BIGINT","NUMERIC","VARCHAR","TEXT"],BIGINT:["NUMERIC","VARCHAR","TEXT"],DATE:["TIMESTAMPTZ"],BOOLEAN:["VARCHAR","TEXT"]}[i]?.includes(r)||!1}function th(c,e,t,i,r){if(!e.actions)return;let s=e.entity.key,o=t.get(s),a=i.findEntity(s);if(!o)return;let n=Array.from(o.withInheritedProperties()),l=new Set(n.map(m=>m.key)),d=Array.from(o.withInheritedAssociations()),p=new Set(d.map(m=>m.key));for(let m of e.actions)if(!(!m.projection||!Array.isArray(m.projection.fields)))for(let h of m.projection.fields)if(h.type==="association"){let f=h.key.split("."),k=f[0];if(p.has(k)){let w=d.find(S=>S.key===k);f.length>1&&(!w||w.schema?.embedded!==!0)&&r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:`Projected association '${h.key}' is invalid because association '${k}' is not embedded.`})}else{let w=!1,S=`Projected association '${h.key}' no longer exists on entity '${o.info.getLabel()}'.`;if(a){let E=Array.from(a.withInheritedAssociations()).find(A=>A.key===k);if(E){let A;try{A=E.getExposedName()}catch{}if(A){let _=d.find(O=>{try{return O.getExposedName()===A}catch{return!1}});_&&(f.length>1&&_.schema?.embedded!==!0?S=`Projected association '${h.key}' is invalid because remapped association '${_.key}' is not embedded.`:w=!0)}}}w||r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:S})}}else{let f=h.key.split("."),k=f[0];if(l.has(k)){let w=n.find(S=>S.key===k);f.length>1&&(!w||w.type!=="json"?r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid because root property '${k}' is not of type 'json'.`}):w.jsonSchema&&(St(w.jsonSchema,f.slice(1))||r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid according to the JSON Schema of '${k}'.`})))}else{let w=!1;if(a){let S=Array.from(a.withInheritedProperties()).find(E=>E.key===k);if(S){let E;try{E=S.getExposedName()}catch{}if(E){let A=n.find(_=>{try{return _.getExposedName()===E}catch{return!1}});A&&(f.length===1||A.type==="json")&&(w=!0,f.length>1&&A.jsonSchema&&(St(A.jsonSchema,f.slice(1))||(w=!1)))}}}w||r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' no longer exists on entity '${o.info.getLabel()}'.`})}}}function ih(c,e,t,i,r){if(!e.paginationContract)return;let s=e.paginationContract,o=e.entity.key,a=t.get(o);if(!a)return;let n=Array.from(a.withInheritedProperties()),l=new Set(n.map(m=>m.key)),d=i.findEntity(o),p=(m,h)=>{if(!(!m||!Array.isArray(m)))for(let f of m){let k=f.split("."),w=k[0];if(l.has(w)){let S=n.find(E=>E.key===w);k.length>1&&(!S||S.type!=="json"?r.paginationFieldsWithMismatches.push({exposureKey:c,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid because root property '${w}' is not of type 'json'.`}):S.jsonSchema&&(St(S.jsonSchema,k.slice(1))||r.paginationFieldsWithMismatches.push({exposureKey:c,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid according to the JSON Schema of '${w}'.`})))}else{let S=!1;if(d){let E=Array.from(d.withInheritedProperties()).find(A=>A.key===w);if(E){let A;try{A=E.getExposedName()}catch{}if(A){let _=n.find(O=>{try{return O.getExposedName()===A}catch{return!1}});_&&(k.length===1||_.type==="json")&&(S=!0,k.length>1&&_.jsonSchema&&(St(_.jsonSchema,k.slice(1))||(S=!1)))}}}S||r.paginationFieldsWithMismatches.push({exposureKey:c,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' no longer exists on entity '${a.info.getLabel()}'.`})}}};p(s.filterableFields,"filterable"),p(s.sortableFields,"sortable"),p(s.searchableFields,"searchable")}function ep(c,e){let t=c.domain,i={hasUpdate:!1,canProceed:!0,breakingChanges:[],exposedEntitiesToRemove:[],subEndpointsToRemove:[],userModelRemapping:[],sessionPropertiesToRemove:[],accessRulesWithMismatches:[],paginationFieldsWithMismatches:[],actionProjectionsWithMismatches:[]};if(!t)return i.hasUpdate=!0,i;if(t.key===e.key&&t.info.version===e.info.version)return i;i.hasUpdate=!0;let r=new Map;for(let P of t.listEntities())r.set(P.key,P);let s=new Map;for(let P of e.listEntities())s.set(P.key,P);let o=new Set;for(let[P,R]of c.exposes.entries()){let x=r.has(R.entity.key),D=s.get(R.entity.key);if(!D){let M=r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.exposedEntitiesToRemove.push({key:P,entityKey:R.entity.key,name:R.entity.key,reason:`Entity ${M} no longer exists in the domain.`}),o.add(P);continue}if(x){let M=r.get(R.entity.key),Y=new Map;for(let ee of M.withInheritedProperties())try{let te=ee.getExposedName();te&&Y.set(te,ee)}catch{}let Q=new Map;for(let ee of D.withInheritedProperties())try{let te=ee.getExposedName();te&&Q.set(te,ee)}catch{}for(let[ee,te]of Y.entries()){let _e=Q.get(ee);if(!_e)continue;let de=Qd(te),ye=Qd(_e);for(let Se of de){let le=ye.find(yt=>yt.name===Se.name);if(!le)continue;if(Se.isPrimary&&!le.isPrimary){i.canProceed=!1;let yt=M.info.getLabel(),bt=`Cannot remove Primary Key constraint from column '${Se.name}' in entity '${yt}'.`;i.breakingChanges.push({type:"primary_key_removed",entityKey:M.key,propertyKey:te.key,reason:bt})}if(!eh(Se,le.dataType)){i.canProceed=!1;let yt=M.info.getLabel(),bt=`Cannot safely cast column '${Se.name}' in entity '${yt}' from ${Se.dataType} to ${le.dataType}.`;i.breakingChanges.push({type:"type_change_unsafe",entityKey:M.key,propertyKey:te.key,reason:bt})}let $e=Se.isNullable&&!le.isNullable,De=!!le.defaultRule;if($e&&!De){i.canProceed=!1;let yt=M.info.getLabel(),bt=`Cannot make column '${Se.name}' in entity '${yt}' required without providing a default value to backfill existing records.`;i.breakingChanges.push({type:"column_not_null_missing_default",entityKey:M.key,propertyKey:te.key,reason:bt})}}}}}let a=!0;for(;a;){a=!1;for(let[P,R]of c.exposes.entries())if(!o.has(P)){if(R.isRoot===!1&&!R.parent){let x=r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:"",associationKey:"",name:R.entity.key,reason:`Sub-endpoint for entity ${x} is missing a parent reference.`}),o.add(P),a=!0;continue}if(R.parent){let x=c.exposes.get(R.parent.key);if(!x){i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:R.parent.selfRoute?"":R.parent.association?.key??"unknown",name:R.entity.key,reason:`Parent exposure "${R.parent.key}" does not exist in the API model.`}),o.add(P),a=!0;continue}let D=r.get(x.entity.key),M=D?.info.getLabel()||x.entity.key;if(o.has(R.parent.key)){i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:R.parent.selfRoute?"":R.parent.association?.key??"unknown",name:R.entity.key,reason:`Parent exposure for entity ${M} is scheduled for removal.`}),o.add(P),a=!0;continue}let Y=s.get(x.entity.key);if(!Y){i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:R.parent.selfRoute?"":R.parent.association?.key??"unknown",name:R.entity.key,reason:`Parent entity ${M} is scheduled for removal.`}),o.add(P),a=!0;continue}if(R.parent.selfRoute){if(!x.hasCollection||!x.collectionPath){i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:"",name:R.entity.key,reason:`Parent exposure for entity ${M} does not have a collection endpoint required for selfRoute.`}),o.add(P),a=!0;continue}let je=s.get(R.entity.key);if(!je||!je.hasSemantic(g.User)){let Ii=je?.info.getLabel()||r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:"",name:R.entity.key,reason:`Entity ${Ii} no longer carries the User semantic required for selfRoute.`}),o.add(P),a=!0;continue}continue}if(!R.parent.association||!R.parent.association.key){let je=r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:"unknown",name:R.entity.key,reason:`Sub-endpoint for entity ${je} does not define a parent association.`}),o.add(P),a=!0;continue}let Q=R.parent.association.key,ee=R.parent.association.domain,te=e.findAssociation(Q,ee)??Array.from(Y.withInheritedAssociations()).find(je=>je.key===Q),_e=t.findAssociation(Q,ee)??(D?Array.from(D.withInheritedAssociations()).find(je=>je.key===Q):void 0),de=te?.info.getLabel()||_e?.info.getLabel()||Q;if(!te){i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:Q,name:R.entity.key,reason:`Parent association ${de} is missing in the new domain.`}),o.add(P),a=!0;continue}let ye=s.get(R.entity.key),Se=Y.key,le=R.entity.key,$e=te.getParentInstance()?.key,De=$e===Se||Y.listAllParents("up").some(je=>je.key===$e),yt=$e===le||ye&&ye.listAllParents("up").some(je=>je.key===$e),bt=te.targets.some(je=>je.key===le||ye&&ye.listAllParents("up").some(Ii=>Ii.key===je.key)),mp=te.targets.some(je=>je.key===Se||Y.listAllParents("up").some(Ii=>Ii.key===je.key));if(!(De&&bt||yt&&mp)){let Ii=(r.get(R.entity.key)||ye)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:R.parent.key,associationKey:Q,name:R.entity.key,reason:`Target entity ${Ii} is no longer a valid target for the parent association ${de}.`}),o.add(P),a=!0;continue}}}}let n,l;if(c.user&&(n=r.get(c.user.key),l=s.get(c.user.key),!l)){i.canProceed=!1;let R=`User entity '${n?.info.getLabel()||c.user.key}' no longer exists in the new domain version.`;i.breakingChanges.push({type:"user_entity_missing",entityKey:c.user.key,propertyKey:"",reason:R})}if(c.user&&l&&n){let P=Array.from(n.withInheritedProperties()),R=Array.from(l.withInheritedProperties());if(c.session?.properties)for(let x of c.session.properties){let D=P.find(Q=>Q.key===x.key);if(!D){i.sessionPropertiesToRemove.push(x.key);continue}let M;try{M=D.getExposedName()}catch{}if(!M){i.sessionPropertiesToRemove.push(x.key);continue}let Y=R.find(Q=>{try{return Q.getExposedName()===M}catch{return!1}});Y?Y.key!==D.key&&i.userModelRemapping.push({oldPropertyKey:D.key,newPropertyKey:Y.key,exposedName:M,reason:`Property ${D.info.getLabel(D.key)} has been renamed to ${Y.info.getLabel(Y.key)}.`}):i.sessionPropertiesToRemove.push(x.key)}}let d=As(e,l),p=Es(e),m=il(e),h=d.roleProperty??(l?Array.from(l.withInheritedProperties()).find(P=>P.hasSemantic(g.UserRole)):void 0),f=p.roleProperty,k=m.roleProperty,w=h?.schema?.enum,S=f?.schema?.enum,E=k?.schema?.enum,A=(P,R)=>{if(P.type==="matchOrganizationRole"){let x=P;if(!f)i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:R,reason:"No organization role property configured in the new domain model."});else if(S&&Array.isArray(S)&&x.roles)for(let D of x.roles)S.includes(D)||i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:R,reason:`Organization role '${D}' is no longer a valid role in the new domain model.`})}else if(P.type==="matchProjectRole"){let x=P;if(!k)i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:R,reason:"No project role property configured in the new domain model."});else if(E&&Array.isArray(E)&&x.roles)for(let D of x.roles)E.includes(D)||i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:R,reason:`Project role '${D}' is no longer a valid role in the new domain model.`})}},_=(P,R)=>{if(P.type==="matchUserRole"){let x=P;if(!h){i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:"No role field configured on the new user model."});return}if(!w||!Array.isArray(w))return;let D=x.mode;if(D==="allowlist")for(let M of x.allowed??[])w.includes(M)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`Role '${M}' in the allowed list is no longer a valid role in the new user model.`});else if(D==="denylist")for(let M of x.denied??[])w.includes(M)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`Role '${M}' in the denied list is no longer a valid role in the new user model.`});else D==="minRole"?x.minimumRole&&!w.includes(x.minimumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`minimumRole '${x.minimumRole}' is no longer a valid role in the new user model.`}):D==="maxRole"&&x.maximumRole&&!w.includes(x.maximumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`maximumRole '${x.maximumRole}' is no longer a valid role in the new user model.`})}},O=(P,R,x)=>{if(P.type==="matchResourceAttribute"){let D=P;if(!x)return;let M=s.get(x);if(!M)return;let Y=Array.from(M.withInheritedProperties());if(!Y.some(ee=>ee.key===D.attribute)){let ee=r.get(x),te=D.attribute,_e=!1;if(ee){let de=Array.from(ee.withInheritedProperties()).find(ye=>ye.key===D.attribute);if(de){te=de.info.getLabel(de.key);let ye;try{ye=de.getExposedName()}catch{}ye&&Y.find(le=>{try{return le.getExposedName()===ye}catch{return!1}})&&(_e=!0)}}if(!_e){let de=M.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceAttribute",location:R,reason:`Property attribute '${te}' no longer exists on entity '${de}'.`})}}}},I=(P,R,x)=>{if(P.type==="matchResourceOwner"){let D=P;if(D.target==="user-entity"){c.user&&!l&&i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:"User entity is missing in the new domain."});return}if(!x)return;let M=s.get(x);if(!M)return;if(D.association&&D.association.key){let Y=D.association.key,Q=D.association.domain,ee=e.findAssociation(Y,Q),te=Array.from(M.withInheritedAssociations());if(!(ee?te.some(de=>de.key===ee.key):te.some(de=>de.key===Y))){let de=r.get(x),ye=Y,Se=!1;if(de){let $e=Array.from(de.withInheritedAssociations()).find(De=>De.key===Y);if($e){ye=$e.info.getLabel($e.key);let De;try{De=$e.getExposedName()}catch{}De&&te.find(bt=>{try{return bt.getExposedName()===De}catch{return!1}})&&(Se=!0)}}if(!Se){let le=M.info.getLabel();e.resolveOwnershipPath(x)!==null?i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:`Direct ownership association '${ye}' no longer exists on entity '${le}'. The resolved ownership path will be used instead.`}):i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:`Ownership association '${ye}' no longer exists on entity '${le}' and no transitively resolved ownership path is available.`})}}}else if(!(e.resolveOwnershipPath(x)!==null)){let Q=M.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:`No ownership association specified and no transitively resolved ownership path exists for entity '${Q}'.`})}}},j=(P,R)=>{if(P.type==="matchUserProperty"){let x=P;if(c.user&&!l){i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:R,reason:"User entity is missing in the new domain."});return}l&&x.property&&(Array.from(l.withInheritedProperties()).some(Y=>Y.key===x.property)||i.userModelRemapping.some(Q=>Q.oldPropertyKey===x.property)||i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:R,reason:`User property '${x.property}' no longer exists on the User entity.`}))}},L=(P,R,x)=>{if(P.type==="matchAssociation"){let M=P.association;if(!M||!M.key){i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:R,reason:"No target association specified for match association access rule."});return}let Y=M.key,Q=M.domain;if(!e.findAssociation(Y,Q)){let te=x?s.get(x):void 0,_e=te?Array.from(te.withInheritedAssociations()):[];if(!_e.some(ye=>ye.key===Y)){let ye=x?r.get(x):void 0,Se=!1;if(ye){let $e=Array.from(ye.withInheritedAssociations()).find(De=>De.key===Y);if($e){let De;try{De=$e.getExposedName()}catch{}De&&_e.find(bt=>{try{return bt.getExposedName()===De}catch{return!1}})&&(Se=!0)}}if(!Se){let le=te?.info.getLabel()||ye?.info.getLabel()||x||"Entity";i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:R,reason:`Target association '${Y}' no longer exists in domain or on entity '${le}'.`})}}}}};if(c.accessScenarios)for(let P of c.accessScenarios)for(let R of P.predicate.getLeafRules())_(R,{type:"api",key:c.key}),A(R,{type:"api",key:c.key}),j(R,{type:"api",key:c.key});for(let[P,R]of c.exposes.entries())if(!o.has(P)){if(R.accessScenarios)for(let x of R.accessScenarios)for(let D of x.predicate.getLeafRules())_(D,{type:"exposure",key:P}),A(D,{type:"exposure",key:P}),O(D,{type:"exposure",key:P},R.entity.key),I(D,{type:"exposure",key:P},R.entity.key),j(D,{type:"exposure",key:P}),L(D,{type:"exposure",key:P},R.entity.key);if(R.actions){for(let x of R.actions)if(x.accessScenarios)for(let D of x.accessScenarios)for(let M of D.predicate.getLeafRules())_(M,{type:"action",key:`${P}:${x.kind}`}),A(M,{type:"action",key:`${P}:${x.kind}`}),O(M,{type:"action",key:`${P}:${x.kind}`},R.entity.key),I(M,{type:"action",key:`${P}:${x.kind}`},R.entity.key),j(M,{type:"action",key:`${P}:${x.kind}`}),L(M,{type:"action",key:`${P}:${x.kind}`},R.entity.key)}th(P,R,s,t,i),ih(P,R,s,t,i)}return i}function tp(c,e,t){if(!t.canProceed)throw new b("Cannot apply domain update because it contains breaking changes. Details in the report.",{code:"E_CANNOT_PROCEED_WITH_UPGRADE",status:400});let i=c.domain;c.dependencies.clear(),c.dependencies.set(e.key,e),c.dependencyList=[{key:e.key,version:e.info.version}];let r=[...t.exposedEntitiesToRemove,...t.subEndpointsToRemove];for(let A of r)c.exposes.delete(A.key);if(c.user&&c.session){let A=new Set(t.sessionPropertiesToRemove),_=new Map;for(let O of t.userModelRemapping)_.set(O.oldPropertyKey,O.newPropertyKey);if(c.session.properties){let O=[];for(let I of c.session.properties){if(A.has(I.key))continue;let j=_.get(I.key);j?O.push({...I,key:j}):O.push(I)}c.session.properties=O}}let s=new Map;for(let A of e.listEntities())s.set(A.key,A);let o=c.user?s.get(c.user.key):void 0,a=As(e,o),n=Es(e),l=il(e),d=a.roleProperty??(o?Array.from(o.withInheritedProperties()).find(A=>A.hasSemantic(g.UserRole)):void 0),p=n.roleProperty,m=l.roleProperty,h=d?.schema?.enum,f=p?.schema?.enum,k=m?.schema?.enum,w=(A,_,O,I,j)=>{if(A.type===_){let L=A;if(!O)return!0;if(I&&Array.isArray(I)&&L.roles&&L.roles.length>0){let P=L.roles.filter(R=>I.includes(R));if(P.length===0)return!0;L.roles=P}return j.push(A),!0}return!1},S=(A,_)=>{let O=[];for(let I of A)if(I.type==="matchUserRole"){let j=I;if(!d)continue;if(h&&Array.isArray(h)){let L=j.mode;if(L==="allowlist"){let P=j.allowed??[];if(P.length>0){let R=P.filter(x=>h.includes(x));if(R.length===0)continue;j.allowed=R}}else if(L==="denylist"){let P=j.denied??[];P.length>0&&(j.denied=P.filter(R=>h.includes(R)))}else if(L==="minRole"){if(j.minimumRole&&!h.includes(j.minimumRole))continue}else if(L==="maxRole"&&j.maximumRole&&!h.includes(j.maximumRole))continue}O.push(I)}else{if(w(I,"matchOrganizationRole",p,f,O))continue;if(w(I,"matchProjectRole",m,k,O))continue;if(I.type==="matchResourceAttribute"&&_){let j=I,L=s.get(_);if(!L)continue;let P=Array.from(L.withInheritedProperties());if(P.some(x=>x.key===j.attribute))O.push(I);else{let x,D=i?.findEntity(_);if(D){let Y=Array.from(D.withInheritedProperties()).find(Q=>Q.key===j.attribute);if(Y){let Q;try{Q=Y.getExposedName()}catch{}Q&&(x=P.find(ee=>{try{return ee.getExposedName()===Q}catch{return!1}}))}}if(x)j.attribute=x.key,O.push(I);else continue}}else if(I.type==="matchResourceOwner"&&_){let j=I;if(j.target==="user-entity")O.push(I);else if(j.association&&j.association.key){let L=s.get(_);if(!L)continue;let P=Array.from(L.withInheritedAssociations()),R=j.association.key;if(P.some(D=>D.key===R))O.push(I);else{let D,M=i?.findEntity(_);if(M){let Q=Array.from(M.withInheritedAssociations()).find(ee=>ee.key===R);if(Q){let ee;try{ee=Q.getExposedName()}catch{}if(ee){let te=P.find(_e=>{try{return _e.getExposedName()===ee}catch{return!1}});te&&(D=te.key)}}}D?(j.association.key=D,O.push(I)):(j.association=void 0,O.push(I))}}else O.push(I)}else if(I.type==="matchUserProperty"){let j=I;if(c.user){let L=s.get(c.user.key);if(L&&j.property)if(Array.from(L.withInheritedProperties()).some(x=>x.key===j.property))O.push(I);else{let x=t.userModelRemapping.find(D=>D.oldPropertyKey===j.property);x?(j.property=x.newPropertyKey,O.push(I)):(j.property="",O.push(I))}else O.push(I)}else O.push(I)}else if(I.type==="matchAssociation"){let j=I;if(j.association&&j.association.key){let L=_?s.get(_):void 0;if(L&&_){let P=Array.from(L.withInheritedAssociations());if(!P.some(x=>x.key===j.association.key)){let x=i?.findEntity(_);if(x){let M=Array.from(x.withInheritedAssociations()).find(Y=>Y.key===j.association.key);if(M){let Y;try{Y=M.getExposedName()}catch{}if(Y){let Q=P.find(ee=>{try{return ee.getExposedName()===Y}catch{return!1}});Q&&(j.association.key=Q.key)}}}}}}O.push(I)}else O.push(I)}return O},E=(A,_)=>{let O=[];for(let I of A.children)if(I instanceof qe)E(I,_),O.push(I);else{let j=S([I],_);O.push(...j)}A.children=O};if(c.accessScenarios)for(let A of c.accessScenarios)E(A.predicate);for(let A of c.exposes.values()){let _=A.entity.key,O=s.get(_),I=i?.findEntity(_),j=x=>x,L=x=>x,P=!1,R=!1;if(O){let x=Array.from(O.withInheritedProperties()),D=new Set(x.map(Q=>Q.key)),M=Array.from(O.withInheritedAssociations()),Y=new Set(M.map(Q=>Q.key));j=Q=>{let ee=Q.split("."),te=ee[0],_e=te,de=!1;if(D.has(te))de=!0;else if(I){let Se=Array.from(I.withInheritedProperties()).find(le=>le.key===te);if(Se){let le;try{le=Se.getExposedName()}catch{}if(le){let $e=x.find(De=>{try{return De.getExposedName()===le}catch{return!1}});$e&&(_e=$e.key,de=!0)}}}ee[0]=_e;let ye=ee.join(".");return de||(P=!0),ye},L=Q=>{let ee=Q.split("."),te=ee[0],_e=te,de=!1;if(Y.has(te))de=!0;else if(I){let Se=Array.from(I.withInheritedAssociations()).find(le=>le.key===te);if(Se){let le;try{le=Se.getExposedName()}catch{}if(le){let $e=M.find(De=>{try{return De.getExposedName()===le}catch{return!1}});$e&&(_e=$e.key,de=!0)}}}ee[0]=_e;let ye=ee.join(".");return de||(R=!0),ye}}if(A.accessScenarios)for(let x of A.accessScenarios)E(x.predicate,_);if(A.actions)for(let x of A.actions){if(x.accessScenarios)for(let D of x.accessScenarios)E(D.predicate,_);x.projection&&Array.isArray(x.projection.fields)&&(x.projection.fields=x.projection.fields.map(D=>{if(D.type==="association"){R=!1;let M=L(D.key),Q=t.actionProjectionsWithMismatches.some(ee=>ee.exposureKey===A.key&&ee.actionKind===x.kind&&ee.fieldType==="association"&&ee.fieldKey===D.key)||R?!0:D.invalid;return{...D,key:M,invalid:Q}}else{P=!1;let M=j(D.key),Q=t.actionProjectionsWithMismatches.some(ee=>ee.exposureKey===A.key&&ee.actionKind===x.kind&&ee.fieldType==="property"&&ee.fieldKey===D.key)||P?!0:D.invalid;return{...D,key:M,invalid:Q}}}))}if(A.paginationContract&&O){let x=A.paginationContract;x.filterableFields&&(x.filterableFields=x.filterableFields.map(j)),x.sortableFields&&(x.sortableFields=x.sortableFields.map(j)),x.searchableFields&&(x.searchableFields=x.searchableFields.map(j))}}c.notifyChange()}var Ei=class c extends cr{kind;key;info;user;authentication;authorization;session;exposes;accessScenarios;rateLimiting;termsOfService;contact;license;pagination;#e=!0;#t=!1;get domain(){if(this.dependencyList.length===0)return;let e=this.dependencyList[0];return this.dependencies.get(e.key)}static createSchema(e={}){let{key:t=W(),exposes:i=[],pagination:r}=e,s=he.fromJSON(e.info,{name:"Unnamed API"}).toJSON(),o={kind:ke,key:t,info:s,exposes:i,pagination:r?structuredClone(r):{kind:"cursor"}};return e.user&&(o.user=structuredClone(e.user)),e.dependencyList&&(o.dependencyList=structuredClone(e.dependencyList)),e.authentication&&(o.authentication=structuredClone(e.authentication)),e.authorization&&(o.authorization=structuredClone(e.authorization)),e.session&&(o.session=structuredClone(e.session)),Array.isArray(e.accessScenarios)&&(o.accessScenarios=structuredClone(e.accessScenarios)),e.rateLimiting&&(o.rateLimiting=structuredClone(e.rateLimiting)),e.termsOfService&&(o.termsOfService=e.termsOfService),e.contact&&(o.contact=structuredClone(e.contact)),e.license&&(o.license=structuredClone(e.license)),o}constructor(e,t){let i=c.createSchema(e),r=[];if(t instanceof Me)t.readOnly?r.push(t):(console.warn(`Domain ${t.key} is not read only, cloning it. This may have performance implications.`),r.push(t.clone({readOnly:!0})));else if(typeof t=="object"&&t.kind===Ee)r.push(new Me(t,void 0,{readOnly:!0}));else if(t)throw new b("Invalid domain provided. Expected a DataDomain instance or schema.",{code:"E_DOMAIN_INVALID",help:"It looks like the provided data domain is not a valid instance or domain schema."});if(t){if(!t.info.version)throw new b(`Domain ${t.key} must have a version.`,{code:"E_DOMAIN_NO_VERSION",help:"Before attaching the data domain, give it a version name. Only versioned domains can be attached to an API model."});i.dependencyList=[{key:t.key,version:t.info.version}]}super(i.dependencyList,r),this.kind=i.kind,this.key=i.key,this.info=new he(i.info),this.user=i.user,this.pagination=i.pagination?structuredClone(i.pagination):{kind:"cursor"},i.authentication&&(this.authentication=structuredClone(i.authentication)),i.authorization&&(this.authorization=structuredClone(i.authorization)),i.session&&(this.session=structuredClone(i.session)),Array.isArray(i.exposes)?this.exposes=new Map(i.exposes.map(s=>[s.key,new hr(this,s)])):this.exposes=new Map,Array.isArray(i.accessScenarios)?this.accessScenarios=i.accessScenarios.map(s=>new It(this,s)):this.accessScenarios=[],i.rateLimiting&&(this.rateLimiting=new ii(i.rateLimiting)),i.termsOfService&&(this.termsOfService=i.termsOfService),i.contact&&(this.contact=i.contact),i.license&&(this.license=i.license),this.#e=!1}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON(),exposes:Array.from(this.exposes.values()).map(t=>t.toJSON()),pagination:structuredClone(this.pagination)};return this.user&&(e.user={...this.user}),this.dependencyList.length>0&&(e.dependencyList=structuredClone(this.dependencyList)),this.authentication&&(e.authentication=structuredClone(this.authentication)),this.authorization&&(e.authorization=structuredClone(this.authorization)),this.session&&(e.session=structuredClone(this.session)),Array.isArray(this.accessScenarios)&&this.accessScenarios.length>0&&(e.accessScenarios=this.accessScenarios.map(t=>t.toJSON())),this.rateLimiting&&(e.rateLimiting=this.rateLimiting.toJSON()),this.termsOfService&&(e.termsOfService=this.termsOfService),this.contact&&(e.contact=structuredClone(this.contact)),this.license&&(e.license=structuredClone(this.license)),e}notifyChange(){this.#t||this.#e||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;let e=new Event("change");this.dispatchEvent(e)}))}exposeEntity(e,t={}){let i=this.domain;if(!i)throw new b("No domain attached to API model",{code:"E_NO_DOMAIN",help:"Attach a data domain to the API model before exposing entities."});let r=Kt(e,this.domain?.key);if(t.selfRoute){if(!t.parentId)throw new b("Parent ID must be specified for selfRoute exposure",{code:"E_NO_PARENT",help:"Provide a parent when exposing a selfRoute."});if(t.association)throw new b("Association must not be specified for selfRoute exposure",{code:"E_UNEXPECTED_ASSOCIATION",help:"selfRoute does not use associations."});let m=this.exposes.get(t.parentId);if(!m)throw new b(`Parent exposure not found: ${t.parentId}`,{code:"E_PARENT_NOT_FOUND",help:"Make sure the parent exposure key you provided is correct."});if(!m.hasCollection||!m.collectionPath)throw new b("Parent exposure must have a collection endpoint for selfRoute",{code:"E_NO_COLLECTION",help:"selfRoute requires the parent exposure to have a collection path."});let h=i.findEntity(e.key,e.domain);if(!h)throw new b(`Entity not found in domain: ${e.key}`,{code:"E_NO_ENTITY",help:"Make sure the entity you are trying to expose exists in the data domain."});if(!h.hasSemantic(g.User))throw new b("selfRoute exposure can only be created for an entity carrying the User semantic",{code:"E_NOT_USER_ENTITY",help:"Annotate the entity with the User semantic before exposing it as a selfRoute."});for(let w of this.exposes.values())if(w.parent?.selfRoute&&w.parent.key===t.parentId)throw new b(`A selfRoute exposure is already registered for parent ${t.parentId}`,{code:"E_ENTITY_ALREADY_EXPOSED",help:"Only one selfRoute exposure can be created per parent exposure."});let f={kind:Ht,key:W(),entity:e,actions:[],isRoot:!1,hasCollection:!1,resourcePath:"/me",parent:{key:m.key,selfRoute:!0}},k=new hr(this,f);return this.exposes.set(k.key,k),this.notifyChange(),k}let{parentId:s,association:o}=t;if(s&&!o)throw new b("Association not specified for nested entity",{code:"E_NO_ASSOCIATION",help:"Provide an association when exposing a nested entity."});if(!s&&o)throw new b("Association specified for non nested entity",{code:"E_NO_PARENT",help:"Provide a parent when exposing a nested entity."});if(s&&o){let m=this.exposes.get(s);if(!m)throw new b(`Parent exposure not found: ${s}`,{code:"E_PARENT_NOT_FOUND",help:"Make sure the parent exposure key you provided is correct."});return m.exposeEntity(e,o)}for(let m of this.exposes.values())if(m.isRoot&&Kt(m.entity,this.domain?.key)===r)throw new b(`Entity ${e.key} is already exposed as a root entity.`,{code:"E_ENTITY_ALREADY_EXPOSED",help:"Do not try to expose already exposed entity."});let a=i.findEntity(e.key,e.domain);if(!a)throw new b(`Entity not found in domain: ${e.key}`,{code:"E_NO_ENTITY",help:"Make sure the entity you are trying to expose exists in the data domain."});let{collectionPath:n,resourcePath:l}=this.generateUniqueRootPaths(a.info.name||""),d={kind:Ht,key:W(),entity:{...e},actions:[],isRoot:!0,collectionPath:n,resourcePath:l,hasCollection:!0},p=new hr(this,d);return this.exposes.set(p.key,p),this.notifyChange(),p}generateUniqueRootPaths(e){let t=Et(e.toLocaleLowerCase()),i=ys(e),r=`/${t}`,s=`/${t}/{${i}}`,o=1,a=r;for(;this.findCollectionPathCollision(r);)r=`${a}-${o}`,s=`${r}/{${i}}`,o++;return{collectionPath:r,resourcePath:s}}removeExposedEntity(e){if(!this.exposes.has(e))throw new b(`Exposed entity with key "${e}" not found.`,{code:"E_NO_EXPOSURE",help:"The exposed entity you are trying to remove does not exist."});this.removeWithChildren(e),this.notifyChange()}removeWithChildren(e){if(!this.exposes.has(e))return;let t=new Set([e]),i=r=>{for(let s of this.exposes.values())s.parent?.key===r&&!t.has(s.key)&&(t.add(s.key),i(s.key))};i(e);for(let r of t)this.exposes.delete(r)}cleanForDomainChange(){this.dependencies.clear(),this.dependencyList=[],this.exposes=new Map,this.user=void 0,this.session&&(this.session.properties=[]),this.notifyChange()}attachDataDomain(e){if(!e.info.version)throw new b("Cannot attach DataDomain without a version. Please set the version in the domain info.",{code:"E_DOMAIN_NO_VERSION",help:"Before attaching the data domain, give it a version name. Only versioned domains can be attached to an API model."});this.cleanForDomainChange(),this.dependencies.set(e.key,e),this.dependencyList=[{key:e.key,version:e.info.version}];for(let t of e.listEntities())if(t.hasSemantic(g.User)){this.user={key:t.key};break}this.notifyChange()}findExposedByEntity(e){let t=Kt(e,this.domain?.key);for(let i of this.exposes.values())if(Kt(i.entity,this.domain?.key)===t)return i}findResourcePathCollision(e,t){for(let i of this.exposes.values())if(!(t&&i.key===t)&&i.isRoot&&i.resourcePath===e)return i}findCollectionPathCollision(e,t){for(let i of this.exposes.values())if(!(t&&i.key===t)&&i.isRoot&&i.hasCollection&&i.collectionPath===e)return i}hasDomainUpdate(e){let t=this.domain;return t?t.key!==e.key||t.info.version!==e.info.version:!0}analyzeDomainUpdate(e){return ep(this,e)}applyDomainUpdate(e,t){tp(this,e,t),this.notifyChange()}};function fr(c){return c.replace(/([A-Z]+)([A-Z][a-z\d])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").toLowerCase()}var _s=class{used=new Set;register(e){let t=fr(e);if(!this.used.has(t))return this.used.add(t),t;let i=1,r=`${t}_${i}`;for(;this.used.has(r);)i++,r=`${t}_${i}`;return this.used.add(r),r}has(e){return this.used.has(fr(e))}clear(){this.used.clear()}};var rl;(function(c){c.LatLon="lat,lon",c.LonLat="lon,lat",c.PostGIS="postgis",c.Degree="degree",c.WKT="wkt",c.GeoJSON="geojson"})(rl||(rl={}));var sl;(function(c){c.Meters="meters",c.Kilometers="kilometers",c.Miles="miles",c.Feet="feet",c.Yards="yards",c.NauticalMiles="nautical_miles"})(sl||(sl={}));var ol;(function(c){c.WGS84="EPSG:4326",c.WebMercator="EPSG:3857",c.NAD83="EPSG:4269",c.NAD27="EPSG:4267"})(ol||(ol={}));var gr={format:rl.LatLon,spatialReferenceSystem:ol.WGS84,defaultDistanceUnit:sl.Meters,enableSpatialIndexing:!0,enableValidation:!0,enablePostGISIntegration:!0,postGISGeometryType:"POINT",enableDistanceQueries:!0,maxQueryDistance:1e5,enableBoundingBoxQueries:!0,enablePolygonQueries:!1,enableGeoClustering:!1,apiEndpointPrefix:"/nearby",includeElevation:!1,coordinatePrecision:6,enableReverseGeocoding:!1};function al(c){return c.split("#")[1]}function wa(c){return c?c.charAt(0).toUpperCase()+c.slice(1):""}var Bt=class{memorySchemas={};memoryNames={};differentiatedInputFieldsCache=new Map;#e=!1;get hasFileUpload(){return this.#e}getSchemas(){let e={};for(let[t,i]of Object.entries(this.memorySchemas))e[this.memoryNames[t]]=i;return e}generateRootRef(e){return this.generateEntity(e,!1),{$ref:`#/components/schemas/${this.generateSchemaKey(e,!1)}`}}generateCreateInputRef(e){return this.generateEntity(e,"create"),{$ref:`#/components/schemas/${this.generateSchemaKey(e,"create")}`}}generateUpdateInputRef(e){return this.generateEntity(e,"update"),{$ref:`#/components/schemas/${this.generateSchemaKey(e,"update")}`}}generatePatchInputRef(e){return this.generateEntity(e,"patch"),{$ref:`#/components/schemas/${this.generateSchemaKey(e,"patch")}`}}generateInputRef(e,t="create"){return t==="patch"?this.generatePatchInputRef(e):t==="update"?this.generateUpdateInputRef(e):this.generateCreateInputRef(e)}generateProjectedRef(e,t,i){let r,s=i||"read";if("projection"in t&&t.projection?(r=t.projection,"kind"in t&&t.kind&&(s=t.kind)):"type"in t&&"fields"in t&&(r=t),!r||!Array.isArray(r.fields)||r.fields.length===0)return this.generateRootRef(e);let o=this.getProjectionFingerprint(r),a=`${e.key}:projected:${s.toLowerCase()}:${o}`;return this.memorySchemas[a]||this.generateProjectedEntity(e,s,r,a),{$ref:`#/components/schemas/${this.memoryNames[a]}`}}generateLinkInputRef(e,t,i){let r=e.info.name||e.key,s=`${this.generateSchemaKey(e,!1)}LinkInput`;if(this.memorySchemas[s])return{$ref:`#/components/schemas/${s}`};let o={type:"object",properties:{},required:[]};this.memorySchemas[s]=o,this.memoryNames[s]=s,e.info.displayName&&(o.title=`Link ${e.info.displayName} Input`);let a=[],n=r.toLowerCase();for(let p of e.properties)if(p.primary){let m=(p.info.name||p.key).toLowerCase(),h=`${n}_${m}`;o.properties||(o.properties={});let f=this.mapPropertyBase(p,void 0,!0);f.description=`The identifier of the ${r} to link.`,o.properties[h]=f,a.push(h)}let l=t,d=t.semantics.find(p=>p.link);if(d?.link){let p=d.link,m=i.findAssociation(p.key,p.domain);m&&(l=m)}for(let p of l.listProperties()){if(this.isSystemProperty(p))continue;let m=p.info.name||p.key;o.properties||(o.properties={}),o.properties[m]=this.mapPropertyBase(p,void 0,!0);let h=p.schema?.defaultValue?.value!==void 0;p.required&&!h&&a.push(m)}return a.length>0?o.required=a:delete o.required,{$ref:`#/components/schemas/${s}`}}generateSchemaKey(e,t){let i=e.info.name||"entity "+e.key;return t?t==="patch"?`${i}PatchInput`:this.hasDifferentiatedInputFields(e)?`${i}${t==="update"?"Update":"Create"}Input`:`${i}Input`:i}getCacheKey(e,t){if(!t)return e.key;if(t==="patch")return`${e.key}:input:patch`;if(this.hasDifferentiatedInputFields(e)){let i=t==="update"?"update":"create";return`${e.key}:input:${i}`}return`${e.key}:input`}isSystemProperty(e){let t=[g.CreatedTimestamp,g.UpdatedTimestamp,g.DeletedTimestamp,g.DeletedFlag,g.Version,g.ClientIPAddress,g.Calculated,g.Derived];return e.semantics.some(i=>t.includes(i.id))}isSystemAssociation(e){let t=[g.ResourceOwnerIdentifier,g.CreatedBy,g.UpdatedBy,g.DeletedBy];return e.semantics.some(i=>t.includes(i.id))}isReadOnlyOrSystemProperty(e){return!!e.readOnly||this.isSystemProperty(e)}isReadOnlyOrSystemAssociation(e){return!!e.readOnly||this.isSystemAssociation(e)}isWriteOnlyProperty(e){return!!e.writeOnly||e.hasSemantic(g.Password)}hasDifferentiatedInputFields(e,t=new Set){let i=t.size===0;if(i&&this.differentiatedInputFieldsCache.has(e.key))return!!this.differentiatedInputFieldsCache.get(e.key);if(t.has(e))return!1;t.add(e);let r=!1;for(let s of e.properties){if(s.readBinding("web")?.hidden)continue;if((s.readOnly||s.immutable)&&!this.isSystemProperty(s)){r=!0;break}let a=s.schema?.defaultValue?.value!==void 0;if(s.required&&a&&!s.readOnly&&!this.isSystemProperty(s)){r=!0;break}}if(!r){for(let s of e.associations)if(!s.readBinding("web")?.hidden){if(s.readOnly&&!this.isSystemAssociation(s)){r=!0;break}if(s.schema?.embedded===!0){for(let a of s.listTargets())if(this.hasDifferentiatedInputFields(a,t)){r=!0;break}if(r)break}}}return i&&this.differentiatedInputFieldsCache.set(e.key,r),r}stripInputExample(e,t,i){if(!t||typeof t!="object"||Array.isArray(t))return t;let r=i==="update"||i==="patch",s=new Set;for(let d of e.properties)(this.isSystemProperty(d)||d.readOnly||r&&d.immutable)&&s.add(d.getExposedName());let o=new Set,a=new Map,n=new Set;for(let d of e.associations){let p=d.getExposedName();if(this.isSystemAssociation(d)||d.readOnly)o.add(p);else if(d.schema?.embedded===!0){let m=Array.from(d.listTargets());m.length===1&&(a.set(p,m[0]),d.multiple&&n.add(p))}}let l={};for(let[d,p]of Object.entries(t)){if(s.has(d)||o.has(d))continue;let m=a.get(d);m?n.has(d)?Array.isArray(p)?l[d]=p.map(h=>this.stripInputExample(m,h,i)):l[d]=p:p&&typeof p=="object"?l[d]=this.stripInputExample(m,p,i):l[d]=p:l[d]=p}return l}stripOutputExample(e,t){if(!t||typeof t!="object"||Array.isArray(t))return t;let i=new Set;for(let a of e.properties)this.isWriteOnlyProperty(a)&&i.add(a.getExposedName());let r=new Map,s=new Set;for(let a of e.associations){let n=a.getExposedName();if(a.schema?.embedded===!0){let l=Array.from(a.listTargets());l.length===1&&(r.set(n,l[0]),a.multiple&&s.add(n))}}let o={};for(let[a,n]of Object.entries(t)){if(i.has(a))continue;let l=r.get(a);l?s.has(a)?Array.isArray(n)?o[a]=n.map(d=>this.stripOutputExample(l,d)):o[a]=n:n&&typeof n=="object"?o[a]=this.stripOutputExample(l,n):o[a]=n:o[a]=n}return o}generateEntity(e,t){let i=this.getCacheKey(e,t);if(this.memorySchemas[i])return;let r={type:"object",properties:{},required:[]};this.memorySchemas[i]=r;let s=this.generateSchemaKey(e,t);if(this.memoryNames[i]=s,e.info.displayName)if(!t)r.title=e.info.displayName;else if(t==="patch")r.title=`${e.info.displayName} Patch Input`;else if(this.hasDifferentiatedInputFields(e)){let m=t==="update"?"Update":"Create";r.title=`${e.info.displayName} ${m} Input`}else r.title=`${e.info.displayName} Input`;if(e.info.description&&(r.description=e.info.description),e.semantics.length>0){r["x-api-now-semantics"]={};for(let m of e.semantics)r["x-api-now-semantics"][al(m.id)]=m.config?m.config:{}}let o=[],a=!!t,n=t==="create"||t===!0,l=t==="update"||t==="patch",d=t==="patch";for(let m of e.properties){if(a){if(this.isSystemProperty(m)||m.readOnly||l&&m.immutable)continue}else if(this.isWriteOnlyProperty(m))continue;let h=m.readBinding("web");if(h?.hidden)continue;let f=m.hasSemantic(g.PublicUniqueName),k=m.schema?.defaultValue?.value!==void 0,w=n&&k;!d&&m.required&&(!a||!m.readOnly)&&!w&&!(a&&f)&&o.push(m.info.name||m.key),r.properties||(r.properties={}),r.properties[m.info.name||m.key]=this.mapPropertyBase(m,h,a,d)}for(let m of e.associations){if(a&&(this.isSystemAssociation(m)||m.readOnly)||m.readBinding("web")?.hidden)continue;let f=Array.from(m.listTargets());if(f.length===0)continue;let k=!m.schema?.embedded,w=[];for(let _ of f)if(k){let O=_.info.displayName||_.info.name||_.key;w.push({type:"string",description:`The ID of the linked ${O}.`})}else _!==e&&this.generateEntity(_,t),w.push({$ref:`#/components/schemas/${this.generateSchemaKey(_,t)}`});let S;if(w.length>1){let _=m.schema?.unionType||"anyOf";_==="oneOf"?S={oneOf:w}:_==="allOf"?S={allOf:w}:S={anyOf:w}}else S=w[0];let E=m.info.name||m.key;r.properties||(r.properties={}),m.multiple?r.properties[E]={type:d?["array","null"]:"array",items:S}:d?k&&w.length===1?r.properties[E]=typeof S=="object"&&S!==null?{...S,type:["string","null"]}:S:r.properties[E]={oneOf:[S,{type:"null"}]}:r.properties[E]=typeof S=="object"&&S!==null?{...S}:S;let A=r.properties[E];if(typeof A=="object"&&A!==null){let _=A;m.info.displayName&&(_.title=m.info.displayName),m.info.description&&(_.description=m.info.description)}}o.length>0?r.required=o:delete r.required;let p=e.toExample("application/json",{renderMocked:!1,renderOptional:!0});if(p){let m;if(typeof p=="string")try{m=JSON.parse(p)}catch{m=p}else m=p;m&&typeof m=="object"&&!Array.isArray(m)&&(a?m=this.stripInputExample(e,m,t):m=this.stripOutputExample(e,m)),r.example=m}}getProjectionFingerprint(e){let t=[...e.fields].sort((i,r)=>{let s=(i.type||"").localeCompare(r.type||"");return s!==0?s:i.key.localeCompare(r.key)});return`${e.type}:${t.map(i=>`${i.type||"property"}:${i.key}`).join(";")}`}resolveProjectedSchemaKey(e,t,i,r){if(this.memoryNames[i])return this.memoryNames[i];let s=e.info.name||`entity_${e.key}`,o=wa(t)||"Response",a=r||`${s}${o}Response`,n=new Set(Object.values(this.memoryNames));if(!n.has(a))return a;let l=2;for(;n.has(`${a}${l}`);)l++;return`${a}${l}`}generateProjectedEntity(e,t,i,r,s){if(this.memorySchemas[r])return;let o={type:"object",properties:{},required:[]};this.memorySchemas[r]=o;let a=this.resolveProjectedSchemaKey(e,t,r,s);this.memoryNames[r]=a;let n=e.info.name||"entity "+e.key,l=wa(t)||"Response";if(e.info.displayName?o.title=`${e.info.displayName} ${l} Response`:o.title=`${wa(n)} ${l} Response`,e.info.description&&(o.description=e.info.description),e.semantics.length>0){o["x-api-now-semantics"]={};for(let h of e.semantics)o["x-api-now-semantics"][al(h.id)]=h.config?h.config:{}}let d=i.type==="include",p=[];for(let h of e.properties){if(this.isWriteOnlyProperty(h))continue;let f=h.readBinding("web");if(f?.hidden)continue;let k=h.info.name||h.key,w=i.fields.filter(I=>{if(I.type&&I.type!=="property")return!1;let[j]=I.key.split(".");return j===h.key||h.info.name&&j===h.info.name}),S=w.some(I=>!I.key.includes(".")),E=w.filter(I=>I.key.includes(".")),A=!1,_;if(d?S?A=!0:E.length>0&&h.type==="json"&&(A=!0,_=E.map(I=>I.key.split(".").slice(1))):S?A=!1:E.length>0&&h.type==="json"?(A=!0,_=E.map(I=>I.key.split(".").slice(1))):A=!0,!A)continue;let O=this.mapPropertyBase(h,f,!1);_&&_.length>0&&(O=this.projectJsonSchema(O,_,i.type)),o.properties||(o.properties={}),o.properties[k]=O,h.required&&!h.readOnly&&p.push(k)}for(let h of e.associations){if(h.readBinding("web")?.hidden)continue;let k=Array.from(h.listTargets());if(k.length===0)continue;let w=h.info.name||h.key,S=i.fields.filter(x=>{if(x.type&&x.type!=="association")return!1;let[D]=x.key.split(".");return D===h.key||h.info.name&&D===h.info.name}),E=S.some(x=>!x.key.includes(".")),A=S.filter(x=>x.key.includes(".")),_=h.schema?.embedded===!0,O=A.length>0&&_,I=!1;if(d?(E||O)&&(I=!0):E?I=!1:I=!0,!I)continue;let j=!h.schema?.embedded,L=[];for(let x of k)if(j){let D=x.info.displayName||x.info.name||x.key;L.push({type:"string",description:`The ID of the linked ${D}.`})}else if(O){let D=new Set(Array.from(x.withInheritedAssociations()).flatMap(te=>[te.key,te.info.name||""])),M={type:d?"include":"exclude",fields:A.map(te=>{let _e=te.key.split(".").slice(1).join("."),[de]=_e.split(".");return{type:D.has(de)?"association":"property",key:_e,...te.domain?{domain:te.domain}:{}}})},Y=this.getProjectionFingerprint(M),Q=`${x.key}:projected:${t.toLowerCase()}:${Y}`,ee=`${a}_${wa(w)}`;this.generateProjectedEntity(x,t,M,Q,ee),L.push({$ref:`#/components/schemas/${this.memoryNames[Q]}`})}else x!==e&&this.generateEntity(x,!1),L.push({$ref:`#/components/schemas/${this.generateSchemaKey(x,!1)}`});let P;if(L.length>1){let x=h.schema?.unionType||"anyOf";x==="oneOf"?P={oneOf:L}:x==="allOf"?P={allOf:L}:P={anyOf:L}}else P=L[0];o.properties||(o.properties={}),h.multiple?o.properties[w]={type:"array",items:P}:o.properties[w]=typeof P=="object"&&P!==null?{...P}:P;let R=o.properties[w];if(typeof R=="object"&&R!==null){let x=R;h.info.displayName&&(x.title=h.info.displayName),h.info.description&&(x.description=h.info.description)}}if(p.length>0&&o.properties){let h=p.filter(f=>Object.prototype.hasOwnProperty.call(o.properties,f));h.length>0?o.required=h:delete o.required}else delete o.required;let m=e.toExample("application/json",{renderMocked:!1,renderOptional:!0});if(m){let h;if(typeof m=="string")try{h=JSON.parse(m)}catch{h=m}else h=m;h&&typeof h=="object"&&!Array.isArray(h)&&(h=this.filterProjectedExample(h,o.properties)),o.example=h}}projectJsonSchema(e,t,i){if(!e||typeof e!="object")return e;let r=structuredClone(e);if(!r.properties||typeof r.properties!="object")return r;let s=new Set,o=new Map;for(let a of t){if(!a||a.length===0)continue;let[n,...l]=a;if(l.length===0)s.add(n);else{let d=o.get(n);d||(d=[],o.set(n,d)),d.push(l)}}if(i==="include"){let a={};for(let[n,l]of Object.entries(r.properties))if(s.has(n))a[n]=l;else if(o.has(n)){let d=o.get(n);d&&(a[n]=this.projectJsonSchema(l,d,"include"))}r.properties=a}else{let a={};for(let[n,l]of Object.entries(r.properties))if(!s.has(n))if(o.has(n)){let d=o.get(n);d&&(a[n]=this.projectJsonSchema(l,d,"exclude"))}else a[n]=l;r.properties=a}if(r.required&&Array.isArray(r.required)){let a=r.required.filter(n=>r.properties&&Object.prototype.hasOwnProperty.call(r.properties,n));a.length>0?r.required=a:delete r.required}return r}filterProjectedExample(e,t){if(!e||typeof e!="object"||!t)return e;let i={};for(let[r,s]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let o=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&"properties"in o&&o.properties?i[r]=this.filterProjectedExample(s,o.properties):i[r]=s}return i}mapPropertyBase(e,t,i=!1,r=!1){let s={};(e.readOnly||this.isSystemProperty(e))&&!i&&(s.readOnly=!0),this.isWriteOnlyProperty(e)&&(s.writeOnly=!0),e.deprecated&&(s.deprecated=!0);let o=r&&!e.multiple;if(e.schema){if(typeof e.schema.minimum=="number"&&(e.type==="string"?s.minLength=e.schema.minimum:e.schema.exclusiveMinimum?s.exclusiveMinimum=e.schema.minimum:s.minimum=e.schema.minimum),typeof e.schema.maximum=="number"&&(e.type==="string"?s.maxLength=e.schema.maximum:e.schema.exclusiveMaximum?s.exclusiveMaximum=e.schema.maximum:s.maximum=e.schema.maximum),e.schema.pattern&&(s.pattern=e.schema.pattern),e.schema.enum&&(s.enum=o&&!e.schema.enum.includes(null)?[...e.schema.enum,null]:[...e.schema.enum]),e.schema.defaultValue?.value!==void 0)if(e.schema.defaultValue.type==="literal"||!e.schema.defaultValue.type){let m=Fc(e);m!==void 0&&(s.default=m)}else e.schema.defaultValue.type==="function"&&(s["x-default-generator"]=e.schema.defaultValue.value,e.schema.defaultValue.config&&(s["x-default-generator-config"]=e.schema.defaultValue.config));if(e.schema.examples&&e.schema.examples.length>0)s.example=e.schema.examples[0];else if(e.schema.defaultValue?.type==="function"){let m=e.toExample("application/json");m!==void 0&&(s.example=m)}}e.info.displayName&&(s.title=e.info.displayName);let a=this.formatFunctionGeneratorTag(e.schema?.defaultValue);if(a?e.info.description?s.description=e.info.description.includes(a)?e.info.description:`${a} ${e.info.description}`:s.description=a:e.info.description&&(s.description=e.info.description),e.hasSemantic(g.Password)&&(s.format="password"),t?.xml&&(s.xml={...t.xml}),e.semantics.length>0){s["x-api-now-semantics"]={};for(let m of e.semantics)!this.#e&&(m.id===g.FileURL||m.id===g.ImageURL)&&(this.#e=!0),s["x-api-now-semantics"][al(m.id)]=m.config?m.config:{}}switch(e.type){case"json":if(e.jsonSchema&&typeof e.jsonSchema=="object"){let m=structuredClone(e.jsonSchema);o?m.allOf?s.oneOf=[m,{type:"null"}]:m.oneOf?(Object.assign(s,m),s.oneOf=[...m.oneOf,{type:"null"}]):m.anyOf?(Object.assign(s,m),s.anyOf=[...m.anyOf,{type:"null"}]):m.type?(Object.assign(s,m),Array.isArray(s.type)?s.type.includes("null")||(s.type=[...s.type,"null"]):typeof s.type=="string"&&(s.type=[s.type,"null"])):(Object.assign(s,m),s.type=["object","null"]):Object.assign(s,m)}else s.type=o?["object","null"]:"object",s.additionalProperties=!0;break;case"string":s.type=o?["string","null"]:"string";break;case"number":{let m=t?.format==="int32"||t?.format==="int64"?"integer":"number";s.type=o?[m,"null"]:m,e.schema?.multipleOf!==void 0&&(s.multipleOf=e.schema.multipleOf);break}case"boolean":s.type=o?["boolean","null"]:"boolean";break;case"date":s.type=o?["string","null"]:"string",s.format="date";break;case"datetime":s.type=o?["string","null"]:"string",s.format="date-time";break;case"time":s.type=o?["string","null"]:"string",s.format="time";break;case"binary":if(s.type=o?["string","null"]:"string",s.format="binary",t?.fileTypes&&t.fileTypes.length>0){let m=t.fileTypes.join(", ");s.contentMediaType=t.fileTypes.length===1?t.fileTypes[0]:m;let h=`**Allowed file types:** ${m}`;s.description=s.description?`${s.description}
|
|
53
|
+
`))}function Ld(c,e){return Vm(c,e),{options:{directed:c.isDirected(),multigraph:c.isMultigraph(),compound:c.isCompound()},nodes:Um(c,e),edges:zm(c,e)}}function Md(c,e){for(let t of c.nodes()){let i=c.node(t);i&&i.domain.key===e&&c.removeNode(t)}}function Gc(c,e,t){let i=new Set,r=new Set;for(let o of e.nodes()){let a=e.node(o);if(!a)continue;let n=`${t}:${o}`;c.setNode(n,a),i.add(n)}for(let o of e.edges()){let a=e.edge(o);if(!a)continue;let n=`${t}:${o.v}`,l=`${t}:${o.w}`;c.setEdge(n,l,{foreign:!0,domain:t,...a}),r.add(`${n}|${l}`)}let s=new Set;for(let o of e.nodes()){let a=`${t}:${o}`;for(let n of e.parents(o)){let l=`${t}:${n}`,d=c.node(a),p=c.node(l);d.kind===O&&p.kind===O?s.has(a)?c.addParent(a,l):(s.add(a),c.setParent(a,l)):c.setParent(a,l)}}return{nodes:i,edges:r}}function Dd(c,e){for(let t of e)if(t.w===c)return t.v}function Fm(c,e,t,i,r){if(!e){let o={type:"malformed_entry",severity:"error",message:"Unable to restore data domain graph. Malformed node entry"};if(r.push(o),i==="strict")throw new Error(o.message);return}let s=e;if(!s.kind){let o={type:"malformed_entry",severity:"error",message:"Unable to restore data domain graph. Node entry missing kind property",affectedKey:s.key};if(r.push(o),i==="strict")throw new Error(o.message);return}try{if(s.kind===Le)return new ar(c,s);if(s.kind===Oe)return new wi(c,s);if(s.kind===O)return new sr(c,s);if(s.kind===be){let a=s,n=Dd(a.key,t);if(!n){let l={type:"missing_edge",severity:"error",message:`Property "${a.info?.name||a.key}" has no parent entity edge`,affectedKey:a.key,resolution:i==="lenient"?"Property will be skipped":void 0};if(r.push(l),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new ki(c,n,a)}if(s.kind===se){let a=s,n=Dd(a.key,t);if(!n){let l={type:"missing_edge",severity:"error",message:`Association "${a.info?.name||a.key}" has no parent entity edge`,affectedKey:a.key,resolution:i==="lenient"?"Association will be skipped":void 0};if(r.push(l),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new rr(c,n,a)}let o={type:"unknown_kind",severity:"error",message:`Unknown node kind: ${s.kind}`,affectedKey:s.key};if(r.push(o),i==="strict")throw new Error(`Unable to restore data domain graph. Unknown node kind ${s.kind}`);return}catch(o){let a={type:"malformed_entry",severity:"error",message:`Failed to create node: ${o instanceof Error?o.message:String(o)}`,affectedKey:s.key};if(r.push(a),i==="strict")throw o;return}}function Ud(c,e={}){let{json:t,dependencies:i,mode:r="strict"}=e,s=new Bo({compound:!0,multigraph:!0,directed:!0}),o=[],a=new Set,n=new Set;if(i)for(let d of i)try{let p=Gc(s,d.graph,d.key);p.edges.size&&(n=new Set([...n,...p.edges])),p.nodes.size&&(a=new Set([...a,...p.nodes])),c.dependencies.set(d.key,d)}catch(p){let m=`Failed to merge dependency "${d.key}": ${p instanceof Error?p.message:String(p)}`;if(r==="strict")throw new Error(m,{cause:p});let h={type:"missing_dependency",severity:"error",message:m,affectedKey:d.key,resolution:"Dependency will be skipped"};o.push(h)}if(!t)return{graph:s,issues:o,success:!0};if(Array.isArray(t.nodes)){let d=new Map;for(let p of t.nodes){let m=Fm(c,p.value,t.edges,r,o);m&&(s.setNode(p.v,m),p.parents&&d.set(p.v,p.parents))}for(let[p,m]of d){if(!s.hasNode(p)){let h={type:"missing_node",severity:"warning",message:`Cannot set parents for missing node: ${p}`,affectedKey:p,resolution:"Parent relationship will be skipped"};o.push(h);continue}for(let h of m){if(!s.hasNode(h)){let f={type:"missing_node",severity:"warning",message:`Parent node "${h}" not found for child "${p}"`,affectedKey:p,context:{parentKey:h},resolution:"Parent relationship will be skipped"};o.push(f);continue}try{s.setParent(p,h)}catch(f){let w={type:"invalid_parent",severity:"warning",message:`Failed to set parent "${h}" for child "${p}": ${f instanceof Error?f.message:String(f)}`,affectedKey:p,context:{parentKey:h},resolution:"Parent relationship will be skipped"};o.push(w)}}}}if(Array.isArray(t.edges))for(let d of t.edges){if(!d.value){let p="Edge entry missing value";if(r==="strict")throw new Error(p);let m={type:"malformed_entry",severity:"error",message:p,context:{edge:d}};o.push(m);continue}if(d.value.foreign&&!a.has(d.w)){let p={type:"missing_node",severity:"warning",message:`Missing foreign node: ${d.w}`,affectedKey:d.w,resolution:"Edge will be skipped"};o.push(p);continue}if(a.has(d.v)||a.has(d.w)){if(!s.hasNode(d.v)||!s.hasNode(d.w)){let p={type:"missing_node",severity:"warning",message:`Missing foreign node for edge: ${d.v} -> ${d.w}`,context:{sourceNode:d.v,targetNode:d.w},resolution:"Edge will be skipped"};o.push(p);continue}}else{if(!s.hasNode(d.v)){let p={type:"missing_node",severity:"warning",message:`Source node not found for edge: ${d.v}`,affectedKey:d.v,resolution:"Edge will be skipped"};o.push(p);continue}if(!s.hasNode(d.w)){let p={type:"missing_node",severity:"warning",message:`Target node not found for edge: ${d.w}`,affectedKey:d.w,resolution:"Edge will be skipped"};o.push(p);continue}}try{s.setEdge({v:d.v,w:d.w,name:d.name},d.value)}catch(p){let h={type:"malformed_entry",severity:"warning",message:`Failed to create edge ${d.v} -> ${d.w}: ${p instanceof Error?p.message:String(p)}`,context:{sourceNode:d.v,targetNode:d.w},resolution:"Edge will be skipped"};o.push(h)}}for(let d of s.nodes()){let p=s.node(d);if(p){if(p.kind===be){let m=p,h=m.parent?s.node(m.parent):void 0;h&&Array.isArray(h.fields)&&(h.fields.some(k=>k.key===m.key&&k.type==="property")||h.fields.push({type:"property",key:m.key}))}else if(p.kind===se){let m=p,h=m.parent?s.node(m.parent):void 0;h&&Array.isArray(h.fields)&&(h.fields.some(k=>k.key===m.key&&k.type==="association")||h.fields.push({type:"association",key:m.key}))}}}let l=o.some(d=>d.severity==="error");return{graph:s,issues:o,success:!l}}var cr=class extends EventTarget{dependencies=new Map;dependencyList=[];constructor(e=[],t=[]){super(),this.dependencyList=[...e];for(let i of t)this.dependencies.set(i.key,i)}};var Me=class c extends cr{kind;key;graph;info;lifecycle;previousVersion;#e=!0;#t=!1;readOnly;get domain(){return this}#i;get fields(){return this.#i}set fields(e){this.#i=e}issues=[];static createSchema(e={}){let{key:t=W(),fields:i,lifecycle:r="draft",previousVersion:s}=e,o=he.fromJSON(e.info,{name:"Unnamed domain"}).toJSON(),a={kind:Ee,key:t,info:o,lifecycle:r};return s&&(a.previousVersion=s),e.dependencyList&&(a.dependencyList=structuredClone(e.dependencyList)),e.graph&&(a.graph=e.graph),Array.isArray(i)&&(a.fields=[...i]),a}constructor(e,t=[],i){let r=c.createSchema(e),s=[];for(let n of t)if(n instanceof c)n.readOnly?s.push(n):(console.warn(`Domain ${n.key} is not read only, cloning it. This may have performance implications.`),s.push(n.clone({readOnly:!0})));else if(typeof n=="object"&&n.kind===Ee&&n.key){let l=new c(n,void 0,{readOnly:!0});s.push(l)}else throw new Error(`Invalid foreign domain dependency: ${n}`);super(r.dependencyList,s),this.kind=r.kind,this.key=r.key,this.info=new he(r.info),this.readOnly=i?.readOnly||!1,this.lifecycle=r.lifecycle||"draft",this.previousVersion=r.previousVersion;let o=i?.mode||"strict",a=Ud(this,{json:r.graph,dependencies:s,mode:o});this.graph=a.graph,a.issues.length>0&&o==="lenient"&&(this.issues=a.issues),Array.isArray(r.fields)?this.fields=[...r.fields]:this.fields=[],Array.isArray(r.dependencyList)?this.dependencyList=[...r.dependencyList]:this.dependencyList=[],this.#e=!1}clone(e){let t=this.toJSON(),i=Array.from(this.dependencies.values()).map(s=>s.clone()),r={readOnly:this.readOnly,...e};return new c(t,i,r)}toJSON(){let e={info:this.info.toJSON(),kind:this.kind,key:this.key,graph:Ld(this.graph,this.key),lifecycle:this.lifecycle};return this.previousVersion&&(e.previousVersion=this.previousVersion),this.dependencyList.length>0&&(e.dependencyList=structuredClone(this.dependencyList)),Array.isArray(this.fields)&&this.fields.length&&(e.fields=[...this.fields]),e}notifyChange(){this.#t||this.#e||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;let e=new Event("change");this.dispatchEvent(e)}))}changeLifecycle(e,t){if(e!==this.lifecycle){if(this.lifecycle==="published"){if(e!=="draft")throw new Error(`Cannot transition from published to ${e}`);if(!t)throw new Error("A new version must be specified when creating a draft from a published domain");if(t===this.info.version)throw new Error("The new version must be different from the current published version");this.previousVersion=this.info.version,this.info.version=t,this.lifecycle="draft",this.notifyChange();return}if(e==="draft"){if(this.lifecycle!=="committed")throw new Error(`Cannot transition from ${this.lifecycle} to draft`);this.lifecycle="draft",this.notifyChange();return}if(e==="committed"){if(this.lifecycle!=="draft")throw new Error(`Cannot transition from ${this.lifecycle} to committed`);this.lifecycle="committed",this.notifyChange();return}if(e==="published"){this.lifecycle="published",this.notifyChange();return}throw new Error(`Unknown lifecycle state: ${e}`)}}ensureWritable(){if(this.lifecycle!=="draft")throw new Error(`Cannot modify the data domain when it is in "${this.lifecycle}" lifecycle state`)}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}hasFields(){return this.fields.length>0}*listFields(){for(let{key:e}of this.fields){let t=this.graph.node(e);t&&(t.kind===Le||t.kind===Oe)&&(yield t)}}addNamespace(e,t){if(this.ensureWritable(),t){if(!this.graph.hasNode(t))throw new Error(`Parent namespace ${t} does not exist`);let r=this.graph.node(t);if(!r||r.kind!==Le)throw new Error(`Parent namespace ${t} is not a valid namespace`);if(r.domain.key!==this.key)throw new Error("Cannot add a namespace to a foreign domain");return r.addNamespace(e)}let i=new ar(this,e);return this.graph.setNode(i.key,i),this.fields.push({type:"namespace",key:i.key}),i}removeNamespace(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Namespace ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==Le)throw new Error(`Namespace ${e} not found`);if(t.domain.key!==this.key)throw new Error("Cannot remove a namespace from a foreign domain");let i=t.getParentInstance();return i===this?(Ve(this.graph,e),this.removeField(e)):i.removeNamespace(e),this}*listNamespaces(){for(let{key:e,type:t}of this.fields){if(t!=="namespace")continue;let i=this.graph.node(e);!i||i.kind!==Le||(yield i)}}*listForeignNamespaces(e){let t=this.dependencies.get(e);if(!t)throw new Error(`Foreign domain ${e} not found`);for(let i of t.listNamespaces()){let r=`${e}:${i.key}`;this.graph.node(r)&&(yield i)}}hasNamespaces(){return this.fields.some(e=>e.type==="namespace")}*listGraphNamespaces(e){for(let t of this.graph.children(e)){let i=this.graph.node(t);i.kind===Le&&i.domain.key===this.key&&(yield i)}}buildReferenceKey(e,t){if(t&&t!==this.key){if(typeof t!="string"||t.length===0)throw new Error(`Invalid namespace key. Expected a string, got ${typeof t}`);if(!this.dependencies.get(t))throw new Error(`Foreign domain ${t} not found`);return`${t}:${e}`}return e}findNamespace(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===Le)return i}moveNamespace(e,t){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Namespace ${e} does not exist`);let i=this.findNamespace(e);if(!i)throw new Error(`Namespace ${e} not found in the graph`);if(t){let o=this.findNamespace(t);if(o&&o.domain.key!==this.key)throw new Error("Cannot move a namespace to a foreign domain");if(!o)throw new Error(`Parent namespace ${t} does not exist`)}if(e===t)throw new Error("Cannot move a namespace to itself");if(i.domain.key!==this.key)throw new Error("Cannot move a namespace from a foreign domain");let r;if(t){if(r=this.findNamespace(t),!r)throw new Error(`Parent namespace ${t} not found`);if(this.isChildOf(t,e))throw new Error("Cannot move a namespace to its own child")}let s=this.graph.parent(e);return s&&!t?this.graph.node(s).detachNamespace(e):s||this.removeField(e),t&&r?r.attachNamespace(e):this.fields.push({type:"namespace",key:e}),this}isChildOf(e,t){let i=this.graph.children(t);for(let r of i)if(r===e||this.isChildOf(e,r))return!0;return!1}addModel(e,t){if(this.ensureWritable(),t){if(!this.graph.hasNode(t))throw new Error(`Parent ${t} does not exist`);let r=this.findNamespace(t);if(!r)throw new Error(`Parent namespace ${t} is not a valid namespace`);if(r.domain.key!==this.key)throw new Error("Cannot add a model to a foreign domain");return r.addModel(e)}let i=new wi(this,e);return this.graph.setNode(i.key,i),this.fields.push({type:"model",key:i.key}),i}removeModel(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Data model ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==Oe)throw new Error(`Data model ${e} not found`);if(t.domain.key!==this.key)throw new Error("Cannot remove a model from a foreign domain");let i=t.getParentInstance();return i===this?(Ve(this.graph,e),this.removeField(e)):i.removeModel(e),this}*listModels(e){let t=e?.domain,i=e?.includeForeign??!1,r=e?.foreignOnly??!1;if(t){let s=t===this.key?this:this.dependencies.get(t);if(!s)throw new Error(`Foreign domain ${t} not found`);for(let o of s.listModels()){let a=t===this.key?o.key:`${t}:${o.key}`,n=this.graph.node(a);n&&(yield n)}return}if(!r)for(let{key:s,type:o}of this.fields){if(o!=="model")continue;let a=this.graph.node(s);a&&a.kind===Oe&&(yield a)}if(i||r)for(let[s,o]of this.dependencies)for(let a of o.listModels()){let n=`${s}:${a.key}`,l=this.graph.node(n);l&&(yield l)}}*listForeignModels(e){yield*this.listModels({domain:e})}hasModels(){return this.fields.some(e=>e.type==="model")}*listGraphModels(e){for(let t of this.graph.children(e)){let i=this.graph.node(t);i.kind===Oe&&i.domain.key===this.key&&(yield i)}}findModel(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===Oe)return i}moveModel(e,t){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Data model ${e} does not exist`);let i=this.findModel(e);if(!i)throw new Error(`Data model ${e} not found in the graph`);if(t){let s=this.findNamespace(t);if(s&&s.domain.key!==this.key)throw new Error("Cannot move a model to a foreign domain");if(!s)throw new Error(`Parent namespace ${t} does not exist`)}if(i.domain.key!==this.key)throw new Error("Cannot move a data model to a foreign domain");let r=this.graph.parent(e);if(r&&!t){let s=this.findNamespace(r);if(!s)throw new Error(`The parent namespace ${r} not found`);s.detachModel(e)}else r||this.removeField(e);return t?this.findNamespace(t).attachModel(e):this.fields.push({type:"model",key:e}),this}addEntity(e,t){if(this.ensureWritable(),!e)throw new Error("An entity expects a DomainModel parent");if(!this.graph.hasNode(e))throw new Error(`The parent ${e} does not exist`);let i=this.findModel(e);if(!i)throw new Error(`Parent model ${e} is not a valid model`);if(i.domain.key!==this.key)throw new Error("Cannot add an entity to a foreign domain");return i.addEntity(t)}removeEntity(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Entity ${e} does not exist`);let t=this.graph.parent(e);if(!t)throw new Error(`Parent model not found for entity ${e}`);let i=this.findModel(t);if(!i)throw new Error(`Parent model ${t} not found`);if(i.domain.key!==this.key)throw new Error("Cannot remove an entity from a foreign domain");return i.removeEntity(e),this}*listEntities(e){let t,i,r=!1,s=!1;if(typeof e=="string"?t=e:e&&typeof e=="object"&&(t=e.parent,i=e.domain,r=e.includeForeign??!1,s=e.foreignOnly??!1),i&&i!==this.key&&!this.dependencies.get(i))throw new Error(`Foreign domain ${i} not found`);let o=t?this.graph.children(t):this.graph.nodes();for(let a of o){let n=this.graph.node(a);if(n&&n.kind===O){let l=n.domain.key===this.key;if(i){n.domain.key===i&&(yield n);continue}s?l||(yield n):r?yield n:l&&(yield n)}}}*listForeignEntities(e){yield*this.listEntities({domain:e})}*listAllForeignEntities(){yield*this.listEntities({foreignOnly:!0})}findEntity(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===O)return i}moveEntity(e,t,i){if(this.ensureWritable(),t===i)throw new Error("Cannot move an entity to the same model");if(!this.graph.hasNode(e))throw new Error(`Entity ${e} does not exist`);if(!this.graph.hasNode(t))throw new Error(`Source model ${t} does not exist`);if(!this.graph.hasNode(i))throw new Error(`Target model ${i} does not exist`);let r=this.findEntity(e),s=this.findModel(t),o=this.findModel(i);if(!r||!s||!o)throw new Error("Entity or models not found in the graph");if(r.domain.key!==this.key)throw new Error("Cannot move an entity from a foreign domain");if(o.domain.key!==this.key)throw new Error("Cannot move an entity to a foreign domain");o.attachEntity(e)}addAssociation(e,t){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Source entity ${e} not found`);let i=this.findEntity(e);if(!i)throw new Error(`Source entity ${e} not found`);if(i.domain.key!==this.key)throw new Error("Cannot add an association to a foreign domain");return i.addAssociation(t)}removeAssociation(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Association ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==se)throw new Error(`Association ${e} not found`);let i=t.getParentInstance();if(!i)throw new Error(`Parent entity not found for association ${e}`);if(i.domain.key!==this.key)throw new Error("Cannot remove an association from a foreign domain");return i.removeAssociation(e),this}findAssociation(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===se)return i}getIncomingAssociations(e){let t=[];for(let i of this.graph.inEdges(e)){let r=this.graph.node(i.v);r&&r.kind===se&&t.push(r)}return t}findAssociationBetween(e,t){let i=this.graph.node(e);if(!i||i.kind!==O)return;let r=i;for(let s of r.listAssociations())for(let o of s.targets)if(this.buildReferenceKey(o.key,o.domain)===t)return s}*associationsBetween(e,t){let i=this.findEntity(e.key,e.domain);if(!i||!this.findEntity(t.key,t.domain))return;let s=this.buildReferenceKey(t.key,t.domain);for(let o of i.withInheritedAssociations())for(let a of o.targets)if(this.buildReferenceKey(a.key,a.domain)===s){yield o;break}}resolveOwnershipPath(e){let t=this.findEntity(e);if(!t)return null;if(t.hasSemantic(g.User))return[];for(let s of t.listAssociations())if(s.hasSemantic(g.ResourceOwnerIdentifier))return[s];let i=[{key:e,path:[]}],r=new Set([e]);for(;i.length>0;){let s=i.shift();if(!s)continue;let o=this.findEntity(s.key);if(!o)continue;let a=[...o.listAssociations()].filter(p=>p.hasSemantic(g.CreatedBy)||p.hasSemantic(g.UpdatedBy)||p.hasSemantic(g.DeletedBy)?!1:p.hasSemantic(g.RelationalResourceOwner)||p.hasSemantic(g.ResourceOwnerIdentifier)?!0:p.listTargets().some(m=>m.hasSemantic(g.User))),l=this.getIncomingAssociations(s.key).filter(p=>{if(p.hasSemantic(g.CreatedBy)||p.hasSemantic(g.UpdatedBy)||p.hasSemantic(g.DeletedBy))return!1;let m=p.getParentInstance();return m?m.hasSemantic(g.User)||p.schema?.embedded===!0:!1}),d=[...a,...l];for(let p of d){let m=p.getParentInstance();if(!m)continue;let h=[...p.listTargets()];if(h.length!==0)for(let f of h){let k=s.key===m.key?f.key:m.key;if(r.has(k))continue;let w=this.findEntity(k);if(!w)continue;let S=[...s.path,p];if(w.hasSemantic(g.User)||p.hasSemantic(g.ResourceOwnerIdentifier))return S;r.add(k),i.push({key:k,path:S})}}}return null}addProperty(e,t){if(this.ensureWritable(),!e)throw new Error("A property expects a DomainEntity parent");if(!this.graph.hasNode(e))throw new Error(`Parent entity ${e} does not exist`);let i=this.findEntity(e);if(!i)throw new Error(`Parent entity ${e} not found`);if(i.domain.key!==this.key)throw new Error("Cannot add a property to a foreign domain");return i.addProperty(t)}removeProperty(e){if(this.ensureWritable(),!this.graph.hasNode(e))throw new Error(`Property ${e} does not exist`);let t=this.graph.node(e);if(!t||t.kind!==be)throw new Error(`Property ${e} not found`);let i=t.getParentInstance();if(!i)throw new Error(`Parent entity not found for property ${e}`);if(i.domain.key!==this.key)throw new Error("Cannot remove a property from a foreign domain");return i.removeProperty(e),this}findProperty(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===be)return i}registerForeignDomain(e){this.ensureWritable();let{info:t,key:i}=e;if(!t.version)throw new Error(`Foreign domain ${i} does not have a version set`);if(this.dependencies.has(i))throw new Error(`Foreign domain with key ${i} already registered`);this.dependencies.set(i,e),this.dependencyList.push({key:i,version:t.version}),Gc(this.graph,e.graph,e.key)}unregisterForeignDomain(e){this.ensureWritable();let t=this.dependencies.get(e);if(!t)throw new Error(`Foreign domain with key ${e} not found`);this.dependencies.delete(e),this.dependencyList=this.dependencyList.filter(i=>i.key!==e),Md(this.graph,t.key)}removeDomainElement(e,t){switch(t){case Le:this.removeNamespace(e);break;case Oe:this.removeModel(e);break;case O:this.removeEntity(e);break;case be:this.removeProperty(e);break;case se:this.removeAssociation(e);break;default:throw new Error(`Unknown kind ${t} for the object ${e}`)}}search(e={}){let{query:t,nodeTypes:i,includeForeignDomains:r=!1,caseSensitive:s=!1}=e,o=[],a=!t&&(!i||i.length===0),n=m=>!i||i.length===0?!0:i.includes(m),l=m=>{if(!m||!t)return!t;if(t instanceof RegExp)return t.test(m);let h=s?m:m.toLowerCase(),f=s?t:t.toLowerCase();return h.includes(f)},d=m=>{if(!t)return[];let h=[],{info:f}=m;return l(f.name)&&h.push("name"),l(f.displayName)&&h.push("displayName"),l(f.description)&&h.push("description"),h},p=m=>m.includes(":");for(let m of this.graph.nodes()){let h=this.graph.node(m);if(!h||!h.info)continue;let f=p(m);if(f&&!r||!n(h.kind))continue;if(a){o.push({node:h,matchedFields:[],key:m,isForeign:f});continue}let k=d(h);(!t||k.length>0)&&o.push({node:h,matchedFields:k,key:m,isForeign:f})}return o}};var zt=class{constructor(e=new Z,t=F()){this.fileManager=e;this.client=t}fileManager;client;async loadDomain(e,t){let i=await this.fileManager.read(e,t);if(i.kind!==ni)throw new Error(`File '${t}' is not a data domain. The file kind is '${i.kind}', but expected '${ni}'.`);let r=await this.fileManager.readMedia(e,t),s=r.media;if(s.kind!==Ee)throw new Error(`Invalid data domain schema format. The media kind is '${s.kind}', but expected '${Ee}'.`);let o=[];if(s.dependencyList&&s.dependencyList.length>0){y.debug(`[domain:load] Fetching dependencies: ${JSON.stringify(s.dependencyList)}`);try{o=(await this.client.dataCatalog.listDependencies(s.dependencyList,{token:this.client.token})).data||[]}catch(n){y.debug(`[domain:load] Failed to fetch dependencies: ${n}`)}}return{domain:new Me(s,o,{readOnly:!1}),fileMeta:i,metaVersion:r.meta.version,originalSchema:s}}};var Fe=class extends Ae{fileManager;domainLoader;constructor(e,t,i=new Z,r=new zt(i)){super(e,t),this.fileManager=i,this.domainLoader=r}async resolveFileId(e,t="Select a data domain file:"){let i=this.options.file||this.options.id;if(!i&&process.stdout.isTTY){y.debug("[domain] File ID not provided; listing data domain files for selection...");try{let r=await this.fileManager.list(e,{kind:"domain"});r.length>0&&(i=await Ce(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){y.debug(`[domain] Failed to list domain files for selection: ${r}`)}}return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1)),i}async loadDomain(e,t){try{return await this.domainLoader.loadDomain(e,t)}catch(i){i instanceof Error&&i.message.includes("is not a data domain")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1)),i instanceof Error&&i.message.includes("Invalid data domain schema format")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1));let r=U(i);this.formatter.error(r),process.exit(1)}}validateDomain(e,t={}){y.debug("[domain] Validating data domain structure...");let r=new Zi(e).validate();if(r&&r.length>0){let s=r.filter(a=>a.severity==="error"),o=r.filter(a=>a.severity==="warning");if(s.length>0&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:s.length===1&&!t.logWarnings?"Data domain validation failed.":`Data domain validation failed with ${s.length} error(s).`,detail:JSON.stringify(r,null,2)}),process.exit(1)),t.logWarnings&&o.length>0&&this.formatter.format!=="json"){console.log(ie.yellow(`\u26A0 Data domain validation reported ${o.length} warning(s):`));for(let a of o)console.log(ie.yellow(` - [${a.rule||"WARNING"}] ${a.message}`))}}}};var Go=class extends Fe{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[domain:list] Searching data domain files for org: ${e}, parent: ${this.options.parent||"all"}`);try{let t=await this.fileManager.search(e,{kind:"domain",parent:this.options.parent});y.debug(`[domain:list] Found ${t.length} domain files.`);let i=t.map(r=>({id:r.key,name:r.info?.name||"",parent:r.parents&&r.parents.length>0?r.parents[r.parents.length-1]:"root",isShortcut:r.isShortcut?"Yes":"No"}));this.formatter.list(i,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var Jo=class extends Fe{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[domain:create] Creating domain file: name=${this.options.name}, org=${e}, parent=${this.options.parent}, media=${this.options.media}, stdin=${this.options.stdin}`),this.options.media&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let t=this.options.name;!t&&process.stdout.isTTY&&(t=await pe("Enter data domain name:")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));try{let i=await this.fileManager.parseMediaInput({mediaPath:this.options.media,stdin:this.options.stdin});if(i!==void 0){let s=i.content;s.kind&&s.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${s.kind}', but expected '${Ee}'.`}),process.exit(1))}let r=await this.fileManager.create(e,{name:t,kind:"domain",parent:this.options.parent,mediaContent:i?.content,key:i?.key});this.formatter.success("Data domain created successfully!",r)}catch(i){i instanceof Error&&(i.message.startsWith("Media file not found")||i.message==="Cannot specify both media path and STDIN.")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1));let s=U(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var Wo=class extends Fe{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;y.debug(`[domain:read] Reading domain file: file=${t}, org=${e}, meta=${this.options.meta}, media=${this.options.media}`);let i=await this.resolveFileId(e,"Select a data domain file to read:");try{if(this.options.media){y.debug(`[domain:read] Fetching media schema for domain file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;y.debug("[domain:read] Media retrieved successfully."),this.formatter.format==="json"?console.log(JSON.stringify(s,null,2)):console.log(typeof s=="object"&&s!==null?JSON.stringify(s,null,2):s)}else{y.debug(`[domain:read] Fetching metadata for domain file ID '${i}'...`);let r=await this.fileManager.read(e,i);y.debug("[domain:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}};var Pe=class c extends Error{static E_VALIDATION_ERROR="E_VALIDATION_ERROR";code=c.E_VALIDATION_ERROR;issues;constructor(e,t){let i=e[0];super(t??`Validation failed: ${i?.path??""} - ${i?.message??""}`),this.name="OperationValidationException",this.issues=e,Error.captureStackTrace&&Error.captureStackTrace(this,c)}};function zd(c,e="/"){return c.replace(/~0/g,"~").replace(/~1/g,e)}function Jc(c,e="/"){let t="",i=c;typeof i=="number"&&(i=String(i));for(let r=0,s=i.length;r<s;r++){let o=i.charAt(r);o==="~"?t+="~0":o===e?t+="~1":t+=o}return t}function Re(c,e="/"){let t="";for(let i=0,r=c.length;i<r;i++)t+=e+Jc(c[i],e);return t}function _t(c,e="/"){if(Array.isArray(c))return c;if(c.length===0)return[];if(c.charAt(0)!==e)throw new Pe([{message:"Invalid pointer.",path:c}]);let t=[""],i=0;for(let r=1,s=c.length;r<s;r++){let o=c.charAt(r);if(o===e){let a=t[t.length-1];if(a==="constructor"||a==="__proto__")throw new Error("Prototype pollution attempt");t.push(""),i++}else o==="~"?c.charAt(r+1)==="1"?(t[i]+=e,r++):c.charAt(r+1)==="0"?(t[i]+="~",r++):t[i]+=o:t[i]+=o}return t}var Vt;(function(c){c.add="add",c.remove="remove",c.replace="replace",c.copy="copy",c.move="move",c.test="test"})(Vt||(Vt={}));function Ho(c,e){if(c==="-")return;let t=new Pe([{message:"Invalid pointer",path:`/${c}`}]),{length:i}=c;if(i>1&&c[0]==="0")throw t;let r=+c;if(Number.isNaN(r)||Math.abs(r).toString()!==c||r<0||r>e)throw t}function lr(c,e){let{length:t}=e,i=c,r;for(let s=0;s<t-1;s++){if(r=e[s],Array.isArray(i))Ho(r,i.length);else if(typeof i!="object"||i===null)throw new Error("Cannot be walked");i instanceof Map?i=i.get(r):i instanceof Set?i=Array.from(i)[+r]:i=i[r]}if(r=e[t-1],Array.isArray(i))Ho(r,i.length);else if(typeof i!="object"||i===null)throw new Error("Invalid target");return{token:r,parent:i}}function Yo(c,e,t){let i,r;return typeof c=="string"?i=_t(c,t):i=c,typeof e=="string"?r=[e]:r=e,Re(i.concat(r),t)}function qm(c,e){if(c instanceof Set){let t=0;for(let i of c)e(i,t+=1)}else if(Array.isArray(c)||c instanceof Map)c.forEach(e);else if(typeof c=="object"&&c!==null)Object.keys(c).forEach(t=>{e(c[t],t)});else throw new TypeError(`${c} is not a structure`)}function Vd(c,e,t,i){i(c,e,t),!(c===null||typeof c!="object")&&qm(c,(r,s)=>{Vd(r,s,c,i)})}function Xo(c,e){let t=Object.create(null);function i(s){for(let o in t)if(t[o]===s)return o}function r(s,o,a){let n=Yo(a&&i(a),o);t[n]=s}Vd(c,void 0,void 0,(s,o,a)=>{if(s!==null&&typeof s=="object"&&(a===void 0||o===void 0?r(s,[],""):r(s,o.toString(),a)),o===void 0||a===void 0)e(s,"");else{let n=i(a);e(s,Yo(n,o.toString()),a,n)}})}var ge=class c{_raw="";_tokens=[];_separator;_index;_parent;constructor(e,t="/"){if(e instanceof c&&e.separator===t)return e;this._separator=t,Array.isArray(e)?(this._tokens=e,this._raw=Re(e,this._separator)):typeof e=="string"?(this._raw=e,this._tokens=_t(e,this._separator)):(this._raw=e._raw,this._tokens=e._tokens)}get raw(){return this._raw}get tokens(){return[...this._tokens]}get separator(){return this._separator}getToken(e){return e<0||e>=this._tokens.length?null:this._tokens[e]}getParent(){return this._parent!==void 0?this._parent:(this._tokens.length===0||this._tokens.length===1&&this._tokens[0]===""?this._parent=null:this._parent=new c(this._tokens.slice(0,-1),this._separator),this._parent)}isRoot(){return this._tokens.length===0||this._tokens[0]===""}append(e){return new c([...this._tokens,String(e)],this._separator)}prefix(e){if(e<0||e>this._tokens.length)throw new Error("Levels out of bound.");return new c(this._tokens.slice(0,e),this._separator)}escape(e){return Jc(e,this._separator)}unescape(e){return zd(e,this._separator)}static encode(e,t="/"){return Re(e,t)}encode(e=this._separator){return Re(this._tokens,e)}static decode(e,t="/"){return _t(e,t)}find(e){let{tokens:t}=this;if(t.length===0)return e;let i;try{i=lr(e,t)}catch{return}let{token:r,parent:s}=i;return s[r]}findValue(e){return this.isRoot()?e:this.find(e)}findParentValue(e){return this.isRoot()?e:this.getParent().find(e)}static find(e,t){return new c(t).find(e)}findAndTest(e,t){let i=this.find(e);return{found:i!==void 0,value:i,equal:i===t}}static isValidArrayToken(e,t){if(e==="-")return;let i=new Pe([{message:"Invalid pointer.",path:`/${e}`}]),{length:r}=e;if(r>1&&e[0]==="0")throw i;let s=+e;if(Number.isNaN(s)||Math.abs(s).toString()!==e||s<0||s>t)throw i}getIndex(){if(this._index!==void 0)return this._index;let e=this._tokens;if(e.length===0)return null;let t=e[e.length-1];if(t==="-")return-1;let i=parseInt(t,10);return isNaN(i)?null:i}static getIndex(e){return new c(e).getIndex()}setIndex(e){let t=this._tokens,i=t[t.length-1];if(i===void 0)return new c(`/${e}`,this._separator);if(isNaN(+i))return new c([...t,e.toString()],this._separator);let r=Array.from(t);return r[r.length-1]=e.toString(),new c(r,this._separator)}static index(e){let t=Object.create(null);return Xo(e,(i,r)=>{t[r]=i}),t}static join(e,t,i){let r,s;if(typeof e=="string"?r=_t(e,i):r=e,typeof t=="string"){if(!t)return Re(r,i);let o=t,a=i||"/";o.startsWith(a)||(o=`${a}${o}`),s=_t(o,i)}else s=t;return Re(r.concat(s),i)}static unflatten(e){let t=Object.keys(e),i=e[""];for(let r of t){if(r==="")continue;let s=_t(r),o=lr(i,s),{parent:a,token:n}=o;a instanceof Map?a.set(n,e[r]):a instanceof Set?a.add(e[r]):Array.isArray(a)?a.push(e[r]):a[n]=e[r]}return i}static flatten(e){let t=Object.create(null);return Xo(e,(i,r)=>{let s;Array.isArray(i)?s=[]:i instanceof Map?s=new Map:i instanceof Set?s=new Set:typeof i=="object"&&i!==null?s={}:s=i,t[r]=s}),t}equals(e){return e?["","/"].includes(this._raw)&&["/",""].includes(e._raw)?!0:this.raw===e.raw:!1}isAfter(e){let t=e.getIndex(),i=this.getIndex();return t===null||i===null||t===-1||i===-1?!1:t<i}isAfterOrAt(e){let t=e.getIndex(),i=this.getIndex();return t===null||i===null||t===-1||i===-1?!1:t!==null&&i!==null&&t<=i}contains(e){if(this.isRoot())return!0;let t=e.tokens;if(t.length<=this._tokens.length)return!1;for(let i=0;i<this._tokens.length;i++)if(this._tokens[i]!==t[i])return!1;return!0}parentEquals(e){let t=this.getParent();return t&&e?t.equals(e):t===e}};function xt(c,e){let t=e.tokens,i=t.length;if(i===0||i===1&&t[0]==="")throw new Pe([{message:"Cannot walk empty path.",path:e.raw}]);try{let r=lr(c,t);return{token:r.token,parent:r.parent}}catch{throw new Pe([{message:"Path not found.",path:e.raw}])}}function Ft(c,e,t){let i=new ge(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:c};let{token:s,parent:o}=xt(c,i),a,n;if(Array.isArray(o))s==="-"?(o.push(r),n=o.length-1):o.splice(parseInt(s,10),0,r);else{a=o[s];let l=o;l[s]=r}return{doc:c,previous:a,idx:n}}function Di(c,e){let t=new ge(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return c;let{parent:i,token:r}=xt(c,t);if(Array.isArray(i))ge.isValidArrayToken(r,i.length);else if(typeof i=="object"&&i!==null&&!(r in i))throw new Pe([{path:`/${r}`,message:"The target does not exists."}]);return i[r]}function dr(c,e,t){let i=new ge(e),r=new ge(t),s=Di(c,i);return e===""||e==="/"?{doc:s,previous:c}:Ft(c,r,s)}function ei(c,e){let t=new ge(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return{doc:void 0,previous:c};let{parent:i,token:r}=xt(c,t),s=i[r];if(s===void 0)throw new Pe([{message:"Parent does not exists.",path:t.raw}]);return Array.isArray(i)?i.splice(parseInt(r,10),1):delete i[r],{doc:c,previous:s}}function fs(c,e,t){let i=new ge(e),r=new ge(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:ei(c,i).previous,previous:c};let s=ei(c,i);return Ft(s.doc,r,s.previous)}function pr(c,e,t){let i=new ge(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:c};let{parent:s,token:o}=xt(c,i),a=s[o];if(a===void 0)throw new Pe([{message:"Location not found.",path:i.raw}]);return s[o]=r,{doc:c,previous:a}}var Km=["boolean","string","number","null"];function Si(c){let e=typeof c;if(e==="boolean"||e==="string")return e;if(e==="number"&&Number.isFinite(c))return"number";if(e==="object"){if(Array.isArray(c)||c instanceof Set)return"array";if(c instanceof Map)return"object";if(c===null)return"null";if(e==="object")return"object"}}function Zo(c){return c===void 0?!0:Km.includes(c)}function Fd(c){let e=[];return c.forEach(t=>{e.push(t)}),e}function qd(c){let e=Object.create(null);return c.forEach((t,i)=>{e[i]=t}),e}function Wc(c,e,t,i){let r=Si(c),s=Si(e);if(r!==s)return!1;switch(r){case"number":return c===0&&1/c===-1/0?e===0&&1/e===-1/0:c===e;case"string":case"null":case"boolean":return c===e;default:}let o,a,n=t.indexOf(c);if(n!==-1)return i[n]===e;if(t.push(c),i.push(e),r==="array"){c instanceof Set&&(c=Fd(c)),e instanceof Set&&(e=Fd(e));let l=c,d=e;if(l.length!==d.length)return t.pop(),i.pop(),!1;for(o=0,a=l.length;o<a;o++)if(!Wc(l[o],d[o],t,i))return t.pop(),i.pop(),!1;return!0}if(r==="object"){c instanceof Map&&(c=qd(c)),e instanceof Map&&(e=qd(e));let l=c,d=e,p=Object.keys(l),m=Object.keys(d);if(p.length!==m.length)return t.pop(),i.pop(),!1;for(p.sort(),m.sort(),o=0,a=p.length;o<a;o++){let h=p[o],f=m[o];if(h!==f||!Object.prototype.hasOwnProperty.call(d,h)||!Wc(l[h],d[h],t,i))return t.pop(),i.pop(),!1}return t.pop(),i.pop(),!0}return t.pop(),i.pop(),!0}function qt(c,e){return Wc(c,e,[],[])}function Qo(c,e,t){let i=new ge(e),r=Di(c,i);if(!qt(r,t))throw new Pe([{path:i.raw,message:"Test operation failed. The values are not equal."}]);return{doc:c}}var fR=Object.freeze({add:Ft,copy:dr,move:fs,remove:ei,replace:pr,test:Qo});function Bd(c){return Array.isArray(c)?new Array(c.length).fill(0).map((e,t)=>`${t}`):Object.keys(c)}function gs(c){switch(typeof c){case"object":return JSON.parse(JSON.stringify(c));case"undefined":return null;default:return c}}function Bm(c,e,t={}){if(JSON.stringify(c)===JSON.stringify(e))return[];let i=[...c],r=[...e],s=[],o=0,a=0;for(;o<i.length||a<r.length;)if(o>=i.length){let n=t.fixedIndexes?a:-1;s.push({op:"add",index:n,value:r[a]}),a++}else if(a>=r.length)s.push({op:"remove",index:o}),o++;else if(qt(i[o],r[a]))o++,a++;else{let n=-1,l=-1;for(let d=o;d<i.length;d++)if(qt(i[d],r[a])){n=d;break}for(let d=a;d<r.length;d++)if(qt(r[d],i[o])){l=d;break}if(n===-1&&l===-1)s.push({op:"replace",index:a,value:r[a]}),o++,a++;else if(n===-1)s.push({op:"add",index:a,value:r[a]}),a++;else if(l===-1)s.push({op:"remove",index:o}),o++;else{s.push({op:"move",index:a,from:n});let d=i[n];i.splice(n,1),i.splice(o,0,d),o++,a++}}return s.sort((n,l)=>n.op==="remove"&&l.op==="remove"?l.index-n.index:0)}function Hc(c,e,t,i=[],r={}){if(c===e)return;if(c==null&&e!==null&&e!==void 0){t.push({op:"replace",path:"",value:e});return}if(e==null&&c!==null&&c!==void 0){t.push({op:"replace",path:"",value:null});return}typeof e.toJSON=="function"&&(e=e.toJSON());let s=Si(c),o=Si(e),a=Zo(s),n=Zo(o);if(a&&n){qt(c,e)||t.push({op:"replace",path:Re(i),value:e});return}if(o!==s){t.push({op:s===void 0?"add":"replace",path:Re(i),value:e});return}if(s==="array"){let p=c,h=Bm(p,e,r);for(let f of h){let k=f.index===-1?"-":f.index.toString(),w=[...i,k];f.op==="remove"?(r.invertible&&t.push({op:"test",path:Re(w),value:gs(p[f.index])}),t.push({op:f.op,path:Re(w)})):f.op==="replace"&&typeof f.value=="object"&&f.value!==null?Hc(p[f.index],f.value,t,w,r):f.op==="move"?t.push({op:"move",from:Re([...i,f.from.toString()]),path:Re(w)}):t.push({op:f.op,path:Re(w),value:f.value})}return}let l=Bd(e),d=Bd(c);for(let p of l){let m=c[p],h=e[p];Object.prototype.hasOwnProperty.call(c,p)?typeof m=="object"&&m!=null&&typeof h=="object"&&h!==null&&Array.isArray(m)===Array.isArray(h)?Hc(m,h,t,[...i,p],r):qt(m,h)||(r.invertible&&t.push({op:"test",path:Re([...i,p]),value:gs(m)}),t.push({op:"replace",path:Re([...i,p]),value:gs(h)})):t.push({op:"add",path:Re([...i,p]),value:gs(h)})}for(let p of d)Object.prototype.hasOwnProperty.call(e,p)||(r.invertible&&t.push({op:"test",path:Re([...i,p]),value:gs(c[p])}),t.push({op:"remove",path:Re([...i,p])}))}function ti(c,e,t){let i=[];return Hc(c,e,i,[],t),i}var ur=Object.create(null);ur.add=0;ur.remove=1;ur.replace=2;ur.move=3;ur.copy=4;ur.test=5;var ea=class extends Fe{constructor(t,i,r,s=new Z,o=new zt(s)){super(i,r,s,o);this.stateOption=t}stateOption;async execute(){let t=this.resolveOrgId();y.debug(`[domain:transition] Transitioning domain lifecycle. Options: file=${this.options.file}, org=${t}, ver=${this.options.ver}, state=${this.stateOption}`);let i=await this.resolveFileId(t),r=await this.resolveTargetState(),s=await this.loadDomain(t,i),o=this.options.ver;if(s.domain.lifecycle==="published"&&r==="draft"&&!o){if(process.stdout.isTTY){let l=s.domain.info.version;o=await pe(`Enter new version (current published version is ${l}):`)}o||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"A new version must be specified when creating a draft from a published domain.",detail:"Provide a version with --ver <ver>."}),process.exit(1))}y.debug(`[domain:transition] Changing lifecycle state from '${s.domain.lifecycle}' to '${r}'...`),s.domain.changeLifecycle(r,o),this.validateDomain(s.domain);let a=s.domain.toJSON(),n=ti(s.originalSchema,a);if(n.length===0){y.debug("[domain:transition] No changes in domain lifecycle detected."),this.formatter.success(`Data domain is already in '${r}' state.`);return}try{let l=await this.fileManager.patchMedia(t,i,{patchOps:n,version:s.metaVersion});y.debug(`[domain:transition] Patch applied successfully. New file version: ${l.newVersion}`),this.formatter.success(`Successfully transitioned data domain state to '${r}' (new file version: ${l.newVersion}).`,{fileId:i,state:r,version:s.domain.info.version,fileVersion:l.newVersion})}catch(l){let d=U(l);this.formatter.error(d),process.exit(1)}}async resolveTargetState(){let t=this.stateOption,i=["draft","committed","published"];return!t&&process.stdout.isTTY&&(t=await Ce("Select target lifecycle state:",[{name:"Draft (draft)",value:"draft"},{name:"Committed (committed)",value:"committed"},{name:"Published (published)",value:"published"}])),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Target lifecycle state is required.",detail:`Specify state as a positional argument (allowed: ${i.join(", ")}).`}),process.exit(1)),i.includes(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle state '${t}'.`,detail:`Allowed states: ${i.join(", ")}`}),process.exit(1)),t}};var Li=class c{key;get kind(){return Wt}catalogKey;scope;lifecycle;version;publishedBy;unpublishedAt;deprecated;deprecatedAt;deprecatedBy;deprecationReason;createdAt;updatedAt;changelog;static createSchema(e){let{key:t="",scope:i="private",publishedBy:r="",createdAt:s=0,updatedAt:o=0,catalogKey:a="",lifecycle:n="stable",version:l=""}=e;if(["public","private","organization"].indexOf(i)===-1)throw new Error(`Invalid scope: ${i}`);let d={key:t,kind:Wt,scope:i,publishedBy:r,createdAt:s,updatedAt:o,catalogKey:a,lifecycle:n,version:l};return typeof e.deprecated=="boolean"&&(d.deprecated=e.deprecated),typeof e.deprecatedAt=="number"&&(d.deprecatedAt=e.deprecatedAt),typeof e.deprecatedBy=="string"&&(d.deprecatedBy=e.deprecatedBy),typeof e.changelog=="string"&&(d.changelog=e.changelog),typeof e.deprecationReason=="string"&&(d.deprecationReason=e.deprecationReason),typeof e.unpublishedAt=="number"&&(d.unpublishedAt=e.unpublishedAt),d}constructor(e={}){let t=c.createSchema(e);this.key=t.key,this.catalogKey=t.catalogKey,this.lifecycle=t.lifecycle,this.scope=t.scope,this.version=t.version,this.publishedBy=t.publishedBy,this.createdAt=t.createdAt,this.updatedAt=t.updatedAt,typeof t.changelog=="string"&&(this.changelog=t.changelog),typeof t.deprecated=="boolean"&&(this.deprecated=t.deprecated),typeof t.deprecatedAt=="number"&&(this.deprecatedAt=t.deprecatedAt),typeof t.deprecatedBy=="string"&&(this.deprecatedBy=t.deprecatedBy),typeof t.deprecationReason=="string"&&(this.deprecationReason=t.deprecationReason),typeof t.unpublishedAt=="number"&&(this.unpublishedAt=t.unpublishedAt)}toJSON(){let e={key:this.key,kind:Wt,scope:this.scope,publishedBy:this.publishedBy,createdAt:this.createdAt,updatedAt:this.updatedAt,catalogKey:this.catalogKey,lifecycle:this.lifecycle,version:this.version};return typeof this.deprecated=="boolean"&&(e.deprecated=this.deprecated),typeof this.deprecatedAt=="number"&&(e.deprecatedAt=this.deprecatedAt),typeof this.deprecatedBy=="string"&&(e.deprecatedBy=this.deprecatedBy),typeof this.deprecationReason=="string"&&(e.deprecationReason=this.deprecationReason),typeof this.unpublishedAt=="number"&&(e.unpublishedAt=this.unpublishedAt),typeof this.changelog=="string"&&this.changelog&&(e.changelog=this.changelog),e}};var Zc;(function(c){c[c.Initializing=0]="Initializing",c[c.PendingDns=1]="PendingDns",c[c.Issuing=2]="Issuing",c[c.Active=3]="Active",c[c.Error=4]="Error"})(Zc||(Zc={}));var ta=class extends Fe{client=F();constructor(e,t,i=new Z,r=new zt(i)){super(e,t,i,r)}async execute(){let e=this.resolveOrgId(),t=await this.resolveFileId(e,"Select a data domain file to publish:"),i=await this.loadDomain(e,t),r=await this.checkPublicationStatus(t,e),s=await this.resolvePublishParams(i.domain,r,t,e);this.prepareDomainLifecycle(i.domain,s.version),this.validateDomain(i.domain,{logWarnings:!0});let o=await this.patchDomainMedia(e,t,i.domain,i.originalSchema,i.metaVersion),a=await this.publishToCatalog(s,r);this.reportSuccess(s,a,o)}async checkPublicationStatus(e,t){y.debug(`[domain:publish] Checking publication status for file '${e}' in org '${t}'...`);try{let i=await this.client.dataCatalog.checkPublicationStatus(e,t,{token:this.client.token});return y.debug(`[domain:publish] Domain already published. Catalog key: ${i.key}`),i}catch(i){let r=U(i);if(r.status===404)return y.debug("[domain:publish] Domain is not published yet (404)."),null;this.formatter.error(r),process.exit(1)}}async resolvePublishParams(e,t,i,r){let s=this.options.catalogVersion||this.options.ver;if(!s&&process.stdout.isTTY){let h=e.info.version||"1.0.0";s=await pe("Enter semantic version:",h)}let o=s||e.info.version||"1.0.0",a=this.options.scope;!a&&process.stdout.isTTY&&(a=await Ce("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),a||(a="public");let n=["public","organization","private"];n.includes(a)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${a}'.`,detail:`Allowed: ${n.join(", ")}`}),process.exit(1));let l=["dev","beta","stable"];l.includes(this.options.lifecycle)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${this.options.lifecycle}'.`,detail:`Allowed: ${l.join(", ")}`}),process.exit(1));let d=this.options.lifecycle,p=this.options.name,m=this.options.description;return t?(p=p||t.name||e.info.name||"",m=m||t.description||e.info.description||""):(!p&&e.info.name&&(p=e.info.name),!p&&process.stdout.isTTY&&(p=await pe("Enter catalog entry name:",e.info.name||"")),p||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required for publishing a new data catalog entry.",detail:"Specify --name <name>."}),process.exit(1)),!m&&e.info.description&&(m=e.info.description),!m&&process.stdout.isTTY&&(m=await pe("Enter catalog entry description:",e.info.description||"")),m||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Description is required for publishing a new data catalog entry.",detail:"Specify --description <desc>."}),process.exit(1))),{fileId:i,orgId:r,version:o,scope:a,lifecycle:d,name:p,description:m,changelog:this.options.changelog||void 0}}prepareDomainLifecycle(e,t){y.debug(`[domain:publish] Preparing domain lifecycle from '${e.lifecycle}' to 'committed' with version '${t}'...`),e.lifecycle==="published"?(e.changeLifecycle("draft",t),e.changeLifecycle("committed")):e.lifecycle==="committed"?e.info.version!==t&&(e.changeLifecycle("draft"),e.info.version=t,e.changeLifecycle("committed")):(e.info.version=t,e.changeLifecycle("committed"))}async patchDomainMedia(e,t,i,r,s){let o=i.toJSON(),a=ti(r,o);if(a.length===0)return y.debug("[domain:publish] No changes in domain schema detected, skipping patch."),s;y.debug(`[domain:publish] Sending patch request (${a.length} ops) to file media...`);try{let n=await this.fileManager.patchMedia(e,t,{patchOps:a,version:s});return y.debug(`[domain:publish] File media patched. New file version: ${n.newVersion}`),n.newVersion}catch(n){let l=U(n);this.formatter.error(l),process.exit(1)}}async publishToCatalog(e,t){let i;if(t)i=t.key,y.debug(`[domain:publish] Using existing catalog entry key: ${i}`);else{y.debug("[domain:publish] Publishing new data catalog entry...");let s={key:"",kind:wt,organization:e.orgId,file:e.fileId,scope:e.scope,name:e.name,description:e.description,publishedBy:"",publishedAt:0,createdAt:0,updatedAt:0,tags:[]};try{i=(await this.client.dataCatalog.publish(s,{token:this.client.token})).key,y.debug(`[domain:publish] Created catalog entry key: ${i}`)}catch(o){let a=U(o);this.formatter.error(a),process.exit(1)}}let r=Li.createSchema({scope:e.scope,lifecycle:e.lifecycle,version:e.version,changelog:e.changelog||void 0});y.debug(`[domain:publish] Publishing version '${e.version}' for catalog key '${i}'...`);try{let s=await this.client.dataCatalog.publishVersion(i,r,{token:this.client.token});return y.debug(`[domain:publish] Version published successfully with key: ${s.key}`),{catalogKey:i,versionKey:s.key,version:e.version}}catch(s){let o=U(s);this.formatter.error(o),process.exit(1)}}reportSuccess(e,t,i){this.formatter.success(`Successfully published version '${e.version}' of data domain to the data catalog!`,{fileId:e.fileId,catalogKey:t.catalogKey,versionKey:t.versionKey,version:e.version,scope:e.scope,lifecycle:e.lifecycle,fileVersion:i})}};var ia=class extends Fe{constructor(t,i,r,s=new Z,o=new zt(s)){super(i,r,s,o);this.file=t}file;async execute(){let t=this.resolveOrgId();y.debug(`[domain:mutate] Mutating domain. File=${this.file}, org=${t}, stdin=${this.options.stdin}, dryRun=${this.options.dryRun}, noValidate=${this.options.noValidate}`),this.validateInputParameters();let i=await this.loadAndValidateLocalSchema(),r=i.key;this.validateTargetFileId(r),this.options.validate!==!1&&!this.options.noValidate&&this.runPreflightValidation(i);let o=await this.loadDomain(t,r);this.assertEditableLifecycle(o.domain.lifecycle,r);let a=ti(o.originalSchema,i);if(a.length===0){this.handleNoOp(r,o.metaVersion);return}if(this.options.dryRun){this.handleDryRun(r,a);return}if(!await this.confirmDestructiveChanges(r,a)){console.log(ie.yellow("Mutation cancelled by user."));return}await this.applyPatch(t,r,a,o.metaVersion)}async loadDomain(t,i){try{return await this.domainLoader.loadDomain(t,i)}catch(r){r instanceof Error&&r.message.includes("is not a data domain")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:r.message}),process.exit(1)),r instanceof Error&&r.message.includes("Invalid data domain schema format")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:r.message}),process.exit(1)),(r&&typeof r=="object"&&"status"in r&&r.status===404||r instanceof Error&&(r.message.includes("not found")||r.message.includes("does not exist")))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Data domain '${i}' does not exist in organization '${t}'.`,detail:"Use 'apinow domain create' to create a new data domain."}),process.exit(1));let s=U(r);this.formatter.error(s),process.exit(1)}}validateInputParameters(){this.file&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),!this.file&&!this.options.stdin&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"A schema file path or --stdin is required.",detail:"Specify [file] or use --stdin."}),process.exit(1))}async loadAndValidateLocalSchema(){try{let t=await this.fileManager.parseMediaInput({mediaPath:this.file,stdin:this.options.stdin});t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"No schema input was provided."}),process.exit(1));let i=t.content;return i.kind&&i.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${i.kind}', but expected '${Ee}'.`}),process.exit(1)),i}catch(t){t instanceof Error&&(t.message.startsWith("Media file not found")||t.message==="Cannot specify both media path and STDIN."||t.message==="invalid API now platform file")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:t.message}),process.exit(1));let r=U(t);this.formatter.error(r),process.exit(1)}}validateTargetFileId(t){let i=this.options.file||this.options.id;i&&i!==t&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Mismatched file ID. The provided schema has key '${t}', but '--file' was specified as '${i}'.`}),process.exit(1))}runPreflightValidation(t){y.debug("[domain:mutate] Running pre-flight local schema validation...");try{let i=new Me(t,[],{readOnly:!0});this.validateDomain(i,{logWarnings:!0})}catch(i){this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Pre-flight data domain schema validation failed.",detail:i instanceof Error?i.message:String(i)}),process.exit(1)}}assertEditableLifecycle(t,i){(t==="committed"||t==="published")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Data domain '${i}' is in '${t}' state and cannot be mutated.`,detail:"Transition the domain to 'draft' state first using 'apinow domain transition draft --ver <newVer>'."}),process.exit(1))}handleNoOp(t,i){y.debug("[domain:mutate] No changes detected between local schema and remote domain."),this.formatter.format==="json"?console.log(JSON.stringify({fileId:t,updated:!1,version:i,message:"No changes detected. Data domain is already up-to-date."},null,2)):this.formatter.success("No changes detected. Data domain is already up-to-date.")}handleDryRun(t,i){if(y.debug(`[domain:mutate] Dry-run completed with ${i.length} patch operation(s).`),this.formatter.format==="json")console.log(JSON.stringify({fileId:t,dryRun:!0,operationsCount:i.length,patch:i},null,2));else{console.log(ie.cyan(`\u2139 [Dry-run] Computed ${i.length} patch operation(s) for domain '${t}':`));for(let r of i){let s=r.op==="add"?ie.green("+"):r.op==="remove"?ie.red("-"):ie.yellow("~");console.log(` ${s} [${r.op}] ${r.path}`)}console.log(""),this.formatter.success("Dry-run completed successfully. No changes were applied to the server.")}}async confirmDestructiveChanges(t,i){return i.some(s=>s.op==="remove")&&!this.options.yes&&process.stdout.isTTY?await oo(`This mutation will remove elements from data domain '${t}'. Do you want to proceed?`,!1):!0}async applyPatch(t,i,r,s){try{let o=await this.fileManager.patchMedia(t,i,{patchOps:r,version:s});y.debug(`[domain:mutate] Patch applied successfully. New file version: ${o.newVersion}`),this.formatter.success(`Successfully mutated data domain '${i}' (new file version: ${o.newVersion}, ${r.length} operation(s) applied).`,{fileId:i,fileVersion:o.newVersion,operationsCount:r.length,updated:!0})}catch(o){let a=U(o);this.formatter.error(a),process.exit(1)}}};var ra=class extends Fe{constructor(t,i,r,s=new Z){super(i,r,s);this.queryArg=t}queryArg;async execute(){let t=this.resolveOrgId(),i=await this.resolveQueries();y.debug(`[domain:search] Searching data domain files for org: ${t}, queries: ${i.join(",")}, parent: ${this.options.parent||"all"}, limit: ${this.options.limit||"none"}`);try{let r=await this.fileManager.search(t,{kind:"domain",query:i,parent:this.options.parent,limit:this.options.limit});y.debug(`[domain:search] Found ${r.length} matching data domain files.`);let s=r.map(o=>({id:o.key,name:o.info?.name||"",parent:o.parents&&o.parents.length>0?o.parents[o.parents.length-1]:"root",isShortcut:o.isShortcut?"Yes":"No"}));this.formatter.list(s,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}async resolveQueries(){let t=[];if(this.queryArg&&t.push(this.queryArg),this.options.query&&this.options.query.length>0&&t.push(...this.options.query),t.length===0&&process.stdout.isTTY){let i=await pe("Enter search query:");i&&i.trim()&&t.push(i.trim())}return t.length===0&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Search query is required.",detail:"Specify <query> or --query <query...>."}),process.exit(1)),t}};function Jd(c){let e=c.command("domain").description("Manage Data Domains");e.command("list").description("List data domain files in an organization").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Filter by parent folder ID").action(async t=>{let i=new K({format:N.resolved.format});await new Go(t,i).execute()}),e.command("search [query]").description("Search data domain files by name or keyword").option("--query <query...>","Search query keywords").option("--parent <parent>","Filter by parent folder ID").option("--limit <limit>","Maximum number of results to return",Yi).option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new ra(t,i,r).execute()}),e.command("create").description("Create a new data domain file record (and optionally upload domain schema media)").option("--name <name>","Name of the data domain").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Parent folder ID").option("--media <path>","Local path to the domain schema JSON to upload").option("--stdin","Read domain schema content from STDIN").action(async t=>{let i=new K({format:N.resolved.format});await new Jo(t,i).execute()}),e.command("read").description("Read data domain file metadata or schema media content").option("--file <fid>","File ID of the data domain").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--meta","Read file metadata (default)").option("--media","Read domain schema media content").action(async t=>{let i=new K({format:N.resolved.format});await new Wo(t,i).execute()}),e.command("transition [state]").description("Transition the lifecycle state of a data domain (draft, committed, published)").option("--file <fid>","File ID of the data domain").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--ver <ver>","New version (required when transitioning from published to draft)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new ea(t,i,r).execute()}),e.command("publish").description("Publish a data domain file to the data catalog").option("--file <fid>","File ID of the data domain").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--ver <ver>","Semantic version to publish (e.g. 1.0.0)").option("--catalog-version <ver>","Semantic version alias (e.g. 1.0.0)").option("--scope <scope>","Publish scope: public, organization, private","public").option("--name <name>","Name for the catalog entry (defaults to domain name)").option("--description <desc>","Description of the catalog entry (defaults to domain description)").option("--lifecycle <lifecycle>","Version lifecycle status (dev, beta, stable)","stable").option("--changelog <changelog>","Changelog description for this version").action(async t=>{let i=new K({format:N.resolved.format});await new ta(t,i).execute()}),e.command("mutate [file]").alias("apply").description("Mutate a data domain by computing and applying a JSON patch against the server version").option("--stdin","Read domain schema content from STDIN").option("--file <fid>","File ID of the data domain (optional, defaults to key in schema)").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--dry-run","Compute diff and preview patch operations without applying them").option("--no-validate","Skip local pre-flight domain schema validation").option("-y, --yes","Automatically accept confirmation prompts for destructive changes").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new ia(t,i,r).execute()})}var et=class extends Ae{fileManager;constructor(e,t,i=new Z){super(e,t),this.fileManager=i}async resolveFileId(e,t="Select an API model file:"){let i=this.options.file||this.options.id;if(!i&&process.stdout.isTTY){y.debug("[api] File ID not provided; searching API model files for selection...");try{let r=await this.fileManager.search(e,{kind:"api"});r.length>0&&(i=await Ce(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){y.debug(`[api] Failed to search API files for selection: ${r}`)}}return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1)),i}};var sa=class extends et{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[api:list] Searching API model files for org: ${e}, parent: ${this.options.parent||"all"}`);try{let t=await this.fileManager.search(e,{kind:"api",parent:this.options.parent});y.debug(`[api:list] Found ${t.length} API files.`);let i=t.map(r=>({id:r.key,name:r.info?.name||"",parent:r.parents&&r.parents.length>0?r.parents[r.parents.length-1]:"root",isShortcut:r.isShortcut?"Yes":"No"}));this.formatter.list(i,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var oa=class extends et{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId();y.debug(`[api:create] Creating API model file: name=${this.options.name}, org=${e}, parent=${this.options.parent}, media=${this.options.media}, stdin=${this.options.stdin}`),this.options.media&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let t=this.options.name;!t&&process.stdout.isTTY&&(t=await pe("Enter API model name:")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));try{let i=await this.fileManager.parseMediaInput({mediaPath:this.options.media,stdin:this.options.stdin});if(i!==void 0){let s=i.content;s.kind&&s.kind!==ke&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${s.kind}', but expected '${ke}'.`}),process.exit(1))}let r=await this.fileManager.create(e,{name:t,kind:"api",parent:this.options.parent,mediaContent:i?.content,key:i?.key});this.formatter.success("API model created successfully!",r)}catch(i){i instanceof Error&&(i.message.startsWith("Media file not found")||i.message==="Cannot specify both media path and STDIN.")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:i.message}),process.exit(1));let s=U(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var aa=class extends et{constructor(e,t,i=new Z){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;y.debug(`[api:read] Reading API model file: file=${t}, org=${e}, meta=${this.options.meta}, media=${this.options.media}`);let i=await this.resolveFileId(e,"Select an API model file to read:");try{if(this.options.media){y.debug(`[api:read] Fetching media schema for API model file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;y.debug("[api:read] Media retrieved successfully."),this.formatter.format==="json"?console.log(JSON.stringify(s,null,2)):console.log(typeof s=="object"&&s!==null?JSON.stringify(s,null,2):s)}else{y.debug(`[api:read] Fetching metadata for API model file ID '${i}'...`);let r=await this.fileManager.read(e,i);y.debug("[api:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}};var na=class extends et{constructor(t,i,r,s=new Z){super(i,r,s);this.queryArg=t}queryArg;async execute(){let t=this.resolveOrgId(),i=await this.resolveQueries();y.debug(`[api:search] Searching API model files for org: ${t}, queries: ${i.join(",")}, parent: ${this.options.parent||"all"}, limit: ${this.options.limit||"none"}`);try{let r=await this.fileManager.search(t,{kind:"api",query:i,parent:this.options.parent,limit:this.options.limit});y.debug(`[api:search] Found ${r.length} matching API files.`);let s=r.map(o=>({id:o.key,name:o.info?.name||"",parent:o.parents&&o.parents.length>0?o.parents[o.parents.length-1]:"root",isShortcut:o.isShortcut?"Yes":"No"}));this.formatter.list(s,["id","name","parent","isShortcut"],{headers:["ID","NAME","PARENT","SHORTCUT"]})}catch(r){let s=U(r);this.formatter.error(s),process.exit(1)}}async resolveQueries(){let t=[];if(this.queryArg&&t.push(this.queryArg),this.options.query&&this.options.query.length>0&&t.push(...this.options.query),t.length===0&&process.stdout.isTTY){let i=await pe("Enter search query:");i&&i.trim()&&t.push(i.trim())}return t.length===0&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Search query is required.",detail:"Specify <query> or --query <query...>."}),process.exit(1)),t}};import ri from"node:fs";import Is from"node:path";function Kt(c,e){let t=c.domain||e;return t?`${t}:${c.key}`:c.key}function ys(c){if(!c)throw new b("Cannot generate parameter name from an empty string.",{code:"E_INVALID_PARAM_NAME",help:"The entity name used for path parameter generation is empty."});let e=c.replace(/([a-z])([A-Z])/g,"$1 $2");e=e.replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2");let i=e.replace(/[^a-zA-Z0-9]/g," ").split(/\s+/).filter(Boolean);if(i.length===0)throw new b(`Cannot generate a valid parameter name from "${c}".`,{code:"E_INVALID_PARAM_NAME",help:"The entity name must contain alphanumeric characters to generate a path parameter."});let s=i.map((o,a)=>{let n=o.toLowerCase();return a===0?n:n.charAt(0).toUpperCase()+n.slice(1)}).join("");return/^[0-9]/.test(s)&&(s="_"+s),`${s}Id`}function Ai(c){let e=c.trim(),t=e.startsWith("/")?e:`/${e}`;return t==="/"?"/":t.replace(/\/+$/,"")}function ca(c,e){let t=c.endsWith("/")?c.slice(0,-1):c,i=e.startsWith("/")?e:`/${e}`;return`${t}${i}`}var ne=class{key;type;parent;isIdentityConstraining=!1;isBroadIdentityRule=!1;constructor(e,t={}){this.parent=e,this.key=t.key||W(),this.type=t.type??""}static isAccessRule(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.type=="string"&&t.kind!=="predicateGroup"}toJSON(){return{key:this.key,type:this.type}}};var bs=class c{description;key;rate;interval;burst;constructor(e={}){this.description=e.description,this.key=c.isRateLimitRuleKey(e.key)?structuredClone(e.key):void 0,this.rate=typeof e.rate=="number"?e.rate:void 0,this.interval=c.isRateLimitRuleInterval(e.interval)?e.interval:void 0,this.burst=typeof e.burst=="number"?e.burst:void 0}toJSON(){let e={};return this.description&&(e.description=this.description),c.isRateLimitRuleKey(this.key)&&(e.key=structuredClone(this.key)),typeof this.rate=="number"&&(e.rate=this.rate),c.isRateLimitRuleInterval(this.interval)&&(e.interval=this.interval),typeof this.burst=="number"&&(e.burst=this.burst),e}static isRateLimitRuleInterval(e){return typeof e!="string"?!1:["second","minute","hour","day"].includes(e)}static isRateLimitRuleKey(e){if(typeof e!="object"||e===null)return!1;let t=e;return"type"in t&&(t.type==="ip"||t.type==="userId"||t.type==="role")}};var ii=class{rules;constructor(e={}){this.rules=e.rules?.map(t=>new bs(t))||[]}toJSON(){return{rules:this.rules.map(e=>e.toJSON())}}};var Mi=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,t),this.type="allowAuthenticated"}};var la=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,t),this.type="allowPublic"}};var da=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;domains;requireVerified;constructor(e,t={}){super(e,t),this.type="matchEmailDomain",this.domains=t.domains?[...t.domains]:[],this.requireVerified=t.requireVerified??!0}toJSON(){return{...super.toJSON(),domains:structuredClone(this.domains),requireVerified:this.requireVerified}}};var Ui=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;target;constructor(e,t={}){super(e,t),this.type="matchResourceOwner",this.association=t.association?{...t.association}:void 0,this.target=t.target??"association"}toJSON(){let e={...super.toJSON(),target:this.target};return this.association&&(e.association={...this.association}),e}};var pa=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;parameters;constructor(e,t={}){super(e,t),this.type="matchPathParameter",this.parameters=Array.isArray(t.parameters)?t.parameters.map(i=>({...i})):[]}toJSON(){return{...super.toJSON(),parameters:this.parameters.map(t=>({...t}))}}};var zi=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;attribute;operator;value;values;constructor(e,t={}){super(e,t),this.type="matchResourceAttribute",this.attribute=t.attribute??"",this.operator=t.operator??"equal",this.value=t.value!==void 0?t.value:"",t.values!==void 0?this.values=Array.isArray(t.values)?[...t.values]:t.values:this.values=[]}static isArrayOperator(e){return e==="in"||e==="notIn"}static isScalarOperator(e){return e==="equal"||e==="notEqual"||e==="greaterThan"||e==="greaterThanOrEqual"||e==="lessThan"||e==="lessThanOrEqual"||e==="startsWith"||e==="endsWith"||e==="contains"}static isArray(e){return typeof e=="string"?c.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?c.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isScalarOperator(e.operator):!1}static assertArray(e){if(!c.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!c.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return c.isArrayOperator(this.operator)}get isScalar(){return c.isScalarOperator(this.operator)}toJSON(){let e=super.toJSON();return this.isArray?{...e,type:"matchResourceAttribute",attribute:this.attribute,operator:this.operator,values:Array.isArray(this.values)?[...this.values]:[]}:{...e,type:"matchResourceAttribute",attribute:this.attribute,operator:this.operator,value:this.value}}};var ua=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;allowedStatuses;deniedStatuses;constructor(e,t={}){super(e,t),this.type="lifecycleStatus",this.allowedStatuses=t.allowedStatuses?[...t.allowedStatuses]:[],this.deniedStatuses=t.deniedStatuses?[...t.deniedStatuses]:[]}toJSON(){let e={...super.toJSON()};return this.allowedStatuses.length>0&&(e.allowedStatuses=structuredClone(this.allowedStatuses)),this.deniedStatuses.length>0&&(e.deniedStatuses=structuredClone(this.deniedStatuses)),e}};var Vi=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;property;operator;value;values;constructor(e,t={}){super(e,t),this.type="matchUserProperty",this.property=t.property??"",this.operator=t.operator??"equal",this.value=t.value!==void 0?t.value:"",t.values!==void 0?this.values=Array.isArray(t.values)?[...t.values]:t.values:this.values=[]}static isArrayOperator(e){return e==="in"||e==="notIn"}static isScalarOperator(e){return e==="equal"||e==="notEqual"||e==="greaterThan"||e==="greaterThanOrEqual"||e==="lessThan"||e==="lessThanOrEqual"||e==="startsWith"||e==="endsWith"||e==="contains"}static isArray(e){return typeof e=="string"?c.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?c.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?c.isScalarOperator(e.operator):!1}static assertArray(e){if(!c.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!c.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return c.isArrayOperator(this.operator)}get isScalar(){return c.isScalarOperator(this.operator)}toJSON(){let e=super.toJSON();return this.isArray?{...e,type:"matchUserProperty",property:this.property,operator:this.operator,values:Array.isArray(this.values)?[...this.values]:[]}:{...e,type:"matchUserProperty",property:this.property,operator:this.operator,value:this.value}}};var ma=class c extends ne{static allowedLevels=["api","exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;mode;allowed;denied;minimumRole;maximumRole;roleMatch;constructor(e,t={}){super(e,t),this.type="matchUserRole",this.mode=t.mode??"allowlist",Array.isArray(t.allowed)&&(this.allowed=[...t.allowed]),Array.isArray(t.denied)&&(this.denied=[...t.denied]),typeof t.minimumRole=="string"&&(this.minimumRole=t.minimumRole),typeof t.maximumRole=="string"&&(this.maximumRole=t.maximumRole),t.roleMatch&&(this.roleMatch=t.roleMatch)}toJSON(){let t={...super.toJSON(),mode:this.mode};return this.allowed!==void 0&&(t.allowed=[...this.allowed]),this.denied!==void 0&&(t.denied=[...this.denied]),this.minimumRole!==void 0&&(t.minimumRole=this.minimumRole),this.maximumRole!==void 0&&(t.maximumRole=this.maximumRole),this.roleMatch!==void 0&&(t.roleMatch=this.roleMatch),t}};var Fi=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;isIdentityConstraining=!0;isBroadIdentityRule=!1;roles;constructor(e,t={}){super(e,t),this.roles=Array.isArray(t.roles)?[...t.roles]:typeof t.roles=="string"?[t.roles]:[]}toJSON(){return{...super.toJSON(),roles:[...this.roles]}}};var ha=class c extends Fi{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchOrganizationRole"}};var fa=class c extends Fi{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchProjectRole"}toJSON(){return{...super.toJSON(),type:"matchProjectRole",roles:[...this.roles]}}};var ga=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchProjectStakeholder"}toJSON(){return{...super.toJSON(),type:"matchProjectStakeholder"}}};var ya=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;allowedRoles;constructor(e,t={}){super(e,t),this.type="matchAssociation",this.association=t.association?{...t.association}:{key:""},this.allowedRoles=t.allowedRoles?[...t.allowedRoles]:[]}toJSON(){let e=super.toJSON();return e.type="matchAssociation",e.association={...this.association},this.allowedRoles&&this.allowedRoles.length>0&&(e.allowedRoles=[...this.allowedRoles]),e}};var ba=class c extends ne{static allowedLevels=["exposure","action"];allowedLevels=c.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="relationalResourceOwner"}toJSON(){return{...super.toJSON()}}};function Wd(c,e){switch(e.type){case"allowAuthenticated":return new Mi(c,e);case"allowPublic":return new la(c,e);case"matchEmailDomain":return new da(c,e);case"matchResourceOwner":return new Ui(c,e);case"relationalResourceOwner":return new ba(c,e);case"matchPathParameter":return new pa(c,e);case"matchResourceAttribute":return new zi(c,e);case"lifecycleStatus":return new ua(c,e);case"matchUserProperty":return new Vi(c,e);case"matchUserRole":return new ma(c,e);case"matchOrganizationRole":return new ha(c,e);case"matchProjectRole":return new fa(c,e);case"matchProjectStakeholder":return new ga(c,e);case"matchAssociation":return new ya(c,e);default:throw new b("Unknown access rule kind",{code:"E_UNKNOWN_ACCESS_RULE_KIND",status:422})}}var qe=class c{kind="predicateGroup";key;label;style;children;parent;constructor(e,t={}){this.parent=e,this.key=t.key||W(),t.label!==void 0&&(this.label=t.label),this.style=t.style==="or"?"or":"and",this.children=Array.isArray(t.children)?t.children.map(i=>i instanceof c||i instanceof ne?i:c.isPredicateGroup(i)?new c(this.parent,i):Wd(this.parent,i)):[]}static isPredicateGroup(e){return!e||typeof e!="object"?!1:e.kind==="predicateGroup"}getLeafRules(){let e=[];for(let t of this.children)t instanceof c?e.push(...t.getLeafRules()):e.push(t);return e}findChild(e){for(let t of this.children){if(t.key===e)return t;if(t instanceof c){let i=t.findChild(e);if(i)return i}}}findRule(e){for(let t of this.children)if(t instanceof c){let i=t.findRule(e);if(i)return i}else if(t.key===e)return t}findGroup(e){for(let t of this.children)if(t instanceof c){if(t.key===e)return t;let i=t.findGroup(e);if(i)return i}}removeChild(e){let t=this.children.findIndex(i=>i.key===e);if(t!==-1)return this.children.splice(t,1),!0;for(let i of this.children)if(i instanceof c&&i.removeChild(e))return!0;return!1}toJSON(){let e={kind:"predicateGroup",key:this.key,style:this.style,children:this.children.map(t=>t.toJSON())};return this.label!==void 0&&this.label!==""&&(e.label=this.label),e}};var It=class{key;label;predicate;parent;constructor(e,t={}){this.parent=e,this.key=t.key||W(),t.label!==void 0&&(this.label=t.label),t.predicate instanceof qe?this.predicate=t.predicate:this.predicate=new qe(this.parent,t.predicate??{kind:"predicateGroup",key:W(),style:"and",children:[]})}findChild(e){return this.predicate.key===e?this.predicate:this.predicate.findChild(e)}findRule(e){return this.predicate.findRule(e)}findGroup(e){return this.predicate.key===e?this.predicate:this.predicate.findGroup(e)}removeChild(e){return this.predicate.removeChild(e)}toJSON(){let e={key:this.key,predicate:this.predicate.toJSON()};return this.label!==void 0&&this.label!==""&&(e.label=this.label),e}};var Te=class{kind;accessScenarios;overrideParentScenarios;rateLimiting;projection;parent;constructor(e,t={}){this.kind=t.kind??"",this.accessScenarios=t.accessScenarios?t.accessScenarios.map(i=>new It(this,i)):[],this.overrideParentScenarios=t.overrideParentScenarios??!1,t.rateLimiting&&(this.rateLimiting=new ii(t.rateLimiting)),t.projection&&(this.projection=structuredClone(t.projection)),this.parent=e}toJSON(){let e={kind:this.kind};return this.accessScenarios.length>0&&(e.accessScenarios=this.accessScenarios.map(t=>t.toJSON())),this.overrideParentScenarios&&(e.overrideParentScenarios=!0),this.rateLimiting&&(e.rateLimiting=this.rateLimiting.toJSON()),this.projection&&(e.projection=structuredClone(this.projection)),e}getAllScenarios(){if(this.overrideParentScenarios)return[...this.accessScenarios];let e=[...this.accessScenarios,...this.parent?.accessScenarios??[],...this.parent?.api?.accessScenarios??[]],t=new Set,i=[];for(let r of e)t.has(r.key)||(t.add(r.key),i.push(r));return i}getAllRateLimiters(){let e=this.parent.getAllRateLimiters();return this.rateLimiting&&e.push(this.rateLimiting),e}};var ks=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="create"}toJSON(){return{...super.toJSON(),kind:"create"}}static isCreateAction(e){return e.kind==="create"}static isCreateActionSchema(e){return e.kind==="create"}};var tt=class extends Te{kind;strategy;retentionPeriod;constructor(e,t={}){super(e,t),this.kind="delete",this.strategy=t.strategy||"soft",this.retentionPeriod=t.retentionPeriod??30}toJSON(){return{...super.toJSON(),kind:"delete",strategy:this.strategy,retentionPeriod:this.retentionPeriod}}static isDeleteAction(e){return e.kind==="delete"}static isDeleteActionSchema(e){return e.kind==="delete"}};var Pt=class extends Te{kind;cacheTtl;constructor(e,t={}){super(e,t),this.kind="list",this.cacheTtl=t.cacheTtl}toJSON(){let e={...super.toJSON(),kind:"list"};return this.cacheTtl!==void 0&&(e.cacheTtl=this.cacheTtl),e}static isListAction(e){return e.kind==="list"}static isListActionSchema(e){return e.kind==="list"}};var qi=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="read"}toJSON(){return{...super.toJSON(),kind:"read"}}static isReadAction(e){return e.kind==="read"}static isReadActionSchema(e){return e.kind==="read"}};var Rt=class extends Te{kind;maxAstDepth;constructor(e,t={}){super(e,t),this.kind="search",this.maxAstDepth=t.maxAstDepth}toJSON(){let e={...super.toJSON(),kind:"search"};return this.maxAstDepth!==void 0&&(e.maxAstDepth=this.maxAstDepth),e}static isSearchActionSchema(e){return e.kind==="search"}static isSearchAction(e){return e.kind==="search"}};var Ki=class extends Te{kind;allowedMethods;constructor(e,t={}){super(e,t),this.kind="update",this.allowedMethods=t.allowedMethods?[...t.allowedMethods]:["PATCH"]}toJSON(){return{...super.toJSON(),kind:"update",allowedMethods:structuredClone(this.allowedMethods)}}static isUpdateAction(e){return e.kind==="update"}static isUpdateActionSchema(e){return e.kind==="update"}};var vs=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="link"}toJSON(){return{...super.toJSON(),kind:"link"}}static isLinkAction(e){return e.kind==="link"}static isLinkActionSchema(e){return e.kind==="link"}};var ws=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="unlink"}toJSON(){return{...super.toJSON(),kind:"unlink"}}static isUnlinkAction(e){return e.kind==="unlink"}static isUnlinkActionSchema(e){return e.kind==="unlink"}};var Bi=class extends Te{kind;constructor(e,t={}){super(e,t),this.kind="restore"}toJSON(){return{...super.toJSON(),kind:"restore"}}static isRestoreAction(e){return e.kind==="restore"}static isRestoreActionSchema(e){return e.kind==="restore"}};function Qc(c,e){switch(e.kind){case"list":return new Pt(c,e);case"read":return new qi(c,e);case"create":return new ks(c,e);case"update":return new Ki(c,e);case"delete":return new tt(c,e);case"search":return new Rt(c,e);case"link":return new vs(c,e);case"unlink":return new ws(c,e);case"restore":return new Bi(c,e);default:throw new b("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}function Hd(c,e){switch(e){case"list":return new Pt(c);case"read":return new qi(c);case"create":return new ks(c);case"update":return new Ki(c);case"delete":return new tt(c);case"search":return new Rt(c);case"link":return new vs(c);case"unlink":return new ws(c);case"restore":return new Bi(c);default:throw new b("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}var hr=class c{kind;key;entity;hasCollection;collectionPath;resourcePath;isRoot;parent;actions;accessScenarios;rateLimiting;paginationContract;truncated;api;static createSchema(e={}){let{key:t=W(),entity:i={key:""},collectionPath:r,resourcePath:s="/",hasCollection:o=!0,isRoot:a,parent:n,actions:l=[],accessScenarios:d,rateLimiting:p,truncated:m,paginationContract:h}=e,f=!!n?.selfRoute,k={kind:Ht,key:t,entity:{...i},hasCollection:f?!1:o,resourcePath:f?"/me":s,actions:l.map(w=>({...w}))};return!f&&r!==void 0&&(k.collectionPath=r),a!==void 0&&(k.isRoot=f?!1:a),n!==void 0&&(k.parent={key:n.key,...n.association?{association:{...n.association}}:{},...n.selfRoute!==void 0?{selfRoute:n.selfRoute}:{}}),Array.isArray(d)&&(k.accessScenarios=d.map(w=>({...w}))),p!==void 0&&(k.rateLimiting={...p}),m!==void 0&&(k.truncated=m),h!==void 0&&(k.paginationContract=structuredClone(h)),k}constructor(e,t){this.api=e;let i=c.createSchema(t);this.kind=i.kind,this.key=i.key,this.entity=i.entity,this.hasCollection=i.hasCollection,this.collectionPath=i.collectionPath,this.resourcePath=i.resourcePath,this.isRoot=i.isRoot,this.parent=i.parent,this.actions=i.actions?i.actions.map(r=>Qc(this,r)):[],this.accessScenarios=i.accessScenarios?i.accessScenarios.map(r=>new It(this,r)):[],i.rateLimiting&&(this.rateLimiting=new ii(i.rateLimiting)),this.truncated=i.truncated,i.paginationContract&&(this.paginationContract=structuredClone(i.paginationContract))}toJSON(){let e={kind:this.kind,key:this.key,entity:{...this.entity},resourcePath:this.resourcePath,actions:this.actions.map(t=>t.toJSON()),hasCollection:this.hasCollection};return this.collectionPath!==void 0&&(e.collectionPath=this.collectionPath),this.isRoot!==void 0&&(e.isRoot=this.isRoot),this.parent!==void 0&&(e.parent={key:this.parent.key,...this.parent.association?{association:{...this.parent.association}}:{},...this.parent.selfRoute!==void 0?{selfRoute:this.parent.selfRoute}:{}}),Array.isArray(this.accessScenarios)&&this.accessScenarios.length>0&&(e.accessScenarios=this.accessScenarios.map(t=>t.toJSON())),this.rateLimiting!==void 0&&(e.rateLimiting=this.rateLimiting.toJSON()),this.truncated!==void 0&&(e.truncated=this.truncated),this.paginationContract&&(e.paginationContract=structuredClone(this.paginationContract)),e}setCollectionPath(e){if(!this.hasCollection)throw new b("Cannot set collection path on an exposure that does not have a collection",{code:"E_PATH_MISSING",help:"The exposed entity you are trying to set a collection path for does not have a collection."});let i=Ai(e).split("/").filter(Boolean);if(i.length!==1)throw new b(`Collection path must contain exactly one segment. Received: "${e}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set path must have a single path segment (e.g., `/products`)"});let r=`/${i[0]}`;if(this.isRoot&&this.api.findCollectionPathCollision(r,this.key))throw new b(`Collection path "${r}" is already in use by another root entity.`,{code:"E_PATH_INUSE",help:"The set path is already in use by another root entity."});let s="";if(this.resourcePath&&this.resourcePath!=="/"){let n=this.resourcePath.split("/").filter(Boolean)[1];n&&/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(n)&&(s=n)}if(!s){let a=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!a||!a.info.name)throw new b("Cannot generate a semantic parameter name because the associated entity or its name is missing.",{code:"E_ENTITY_NOT_FOUND",help:"Ensure the exposed entity points to a valid domain entity with a defined name."});s=`{${ys(a.info.name)}}`}let o=`${r}/${s}`;this.#i(o),this.collectionPath=r,this.resourcePath=o}setResourcePath(e){let t=Ai(e),i=t.split("/").filter(Boolean);if(this.hasCollection){if(!this.collectionPath)throw new b("Cannot set resource path: missing collection path for this exposure",{code:"E_PATH_MISSING",help:"Set the collection path on the exposed entity first."});let r=this.collectionPath.split("/").filter(Boolean);if(r.length!==1)throw new b(`Invalid stored collection path "${this.collectionPath}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set collection path must have a single path segment (e.g., `/products`)"});if(i.length!==2)throw new b(`Resource path must be exactly two segments (collection + parameter). Received: "${t}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set resource path must have exactly two segments (collection + parameter)."});let[s,o]=i;if(s!==r[0])throw new b(`Resource path must start with the collection segment "${r[0]}". Received: "${s}"`,{code:"E_PATH_MISMATCH",help:"Set the resource path to the same value as the collection path + the parameter value."});if(!/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(o))throw new b(`The second segment must be a parameter in braces, e.g. {id}. Received: "${o}"`,{code:"E_PARAMETER_INVALID",help:"Use the braces to surround the parameter name, e.g., {productId}."});this.resourcePath!==t&&(this.#i(`/${s}/${o}`),this.resourcePath=`/${s}/${o}`);return}if(i.length!==1)throw new b(`Resource path must contain exactly one segment when no collection is present. Received: "${t}"`,{code:"E_PATH_SEGMENT_SIZE",help:"The set resource path must have exactly one segment."});if(this.isRoot&&this.api.findResourcePathCollision(t,this.key))throw new b(`Resource path "${t}" is already in use by another root entity.`,{code:"E_PATH_INUSE",help:"The set path is already in use by another root entity."});this.resourcePath!==t&&(this.#i(`/${i[0]}`),this.resourcePath=`/${i[0]}`)}#e(e){let i=[...e.join("/").matchAll(/\{([^}]+)\}/g)].map(s=>s[1]),r=new Set;for(let s of i){if(r.has(s))throw new b(`Duplicate path parameter "{${s}}" detected in branch hierarchy.`,{code:"E_PATH_PARAM_COLLISION",help:"Change the parameter name in either this resource or its ancestor to ensure unique parameter names."});r.add(s)}}#t(e,t){for(let i of this.api.exposes.values())if(i.parent?.key===e){let r=[...t,i.resourcePath];this.#e(r),this.#t(i.key,r)}}#i(e){let t=[e],i=this.parent?.key;for(;i;){let r=this.api.exposes.get(i);if(!r)break;t.unshift(r.resourcePath),i=r.parent?.key}this.#e(t),this.#t(this.key,t)}getAbsoluteResourcePath(){let e=Ai(this.resourcePath);if(this.parent?.selfRoute){let s=this.api.exposes.get(this.parent.key)?.getAbsoluteCollectionPath();return s?ca(s,e):e}let t=e,i=this.parent?.key;for(;i;){let r=this.api.exposes.get(i);if(!r)break;let s=Ai(r.resourcePath);t=ca(s,t),i=r.parent?.key}return t}getAbsoluteCollectionPath(){if(!this.hasCollection||!this.collectionPath)return;let e=Ai(this.collectionPath),t=this.parent?.key;for(;t;){let i=this.api.exposes.get(t);if(!i)break;let r=Ai(i.resourcePath);e=ca(r,e),t=i.parent?.key}return e}getAllRateLimiters(){let e=[];this.api.rateLimiting&&e.push(this.api.rateLimiting);let t=this;for(;t;)t.rateLimiting&&e.push(t.rateLimiting),t=t.parent?this.api.exposes.get(t.parent.key):void 0;return e}getAllRateLimiterRules(){let e=[];this.api.rateLimiting&&e.push(...this.api.rateLimiting.rules);let t=this;for(;t;)t.rateLimiting&&e.push(...t.rateLimiting.rules),t=t.parent?this.api.exposes.get(t.parent.key):void 0;return e}addAction(e){if(this.actions.some(i=>i.kind===e.kind))throw new b(`Action of kind "${e.kind}" already exists for this exposure`,{code:"E_ACTION_USED",help:"There's no need to add an API action again."});if(this.parent?.selfRoute&&!["read","update","delete","unlink"].includes(e.kind))throw new b(`Action "${e.kind}" is not allowed on a selfRoute exposure. Allowed actions are: read, update, delete, unlink.`,{code:"E_INVALID_ACTION",help:"Only 'read', 'update', 'delete', and 'unlink' actions are permitted on a selfRoute."});let t=Qc(this,e);if(this.parent?.selfRoute){let i=new It(t,{key:`${this.key}-current-user-scenario`,label:"Current User Invariant"});i.predicate.children=[new Mi(t),new Ui(t,{target:"user-entity"})],t.accessScenarios=[i]}return this.actions.push(t),t}addActionFromKind(e){if(this.actions.some(i=>i.kind===e))throw new b(`Action of kind "${e}" already exists for this exposure`,{code:"E_ACTION_USED",help:"There's no need to add an API action again."});if(this.parent?.selfRoute&&!["read","update","delete","unlink"].includes(e))throw new b(`Action "${e}" is not allowed on a selfRoute exposure. Allowed actions are: read, update, delete, unlink.`,{code:"E_INVALID_ACTION",help:"Only 'read', 'update', 'delete', and 'unlink' actions are permitted on a selfRoute."});let t=Hd(this,e);if(this.parent?.selfRoute){let i=new It(t,{key:`${this.key}-current-user-scenario`,label:"Current User Invariant"});i.predicate.children=[new Mi(t),new Ui(t,{target:"user-entity"})],t.accessScenarios=[i]}return this.actions.push(t),t}createPaginationContract(){let e=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!e)throw new b(`Entity "${this.entity.key}" not found"`,{code:"E_ENTITY_NOT_FOUND",help:"The set entity does not exist."});this.paginationContract?(this.paginationContract.filterableFields=[],this.paginationContract.searchableFields=[],this.paginationContract.sortableFields=[]):this.paginationContract={filterableFields:[],searchableFields:[],sortableFields:[]};for(let t of e.properties)t.index&&(this.paginationContract.filterableFields.push(t.key),this.paginationContract.sortableFields.push(t.key)),t.search&&this.paginationContract.searchableFields.push(t.key)}getSubResources(e=!1){let t=[],i=r=>{for(let s of this.api.exposes.values())s.parent?.key===r&&(t.push(s),e&&i(s.key))};return i(this.key),t}findSubResource(e,t=!1){let i=this.getSubResources(t),r=Ai(e);return i.find(s=>{if(s.key===e||s.entity.key===e)return!0;let o=this.api.domain?.findEntity(s.entity.key,s.entity.domain);if(o&&o.info.name===e)return!0;if(s.hasCollection&&s.collectionPath){if(s.collectionPath===e||s.collectionPath===r)return!0;let n=s.getAbsoluteCollectionPath();if(n&&(n===e||n===r))return!0}if(s.resourcePath===e||s.resourcePath===r)return!0;let a=s.getAbsoluteResourcePath();return!!(a&&(a===e||a===r))})}getParentExposedEntity(){if(this.parent)return this.api.exposes.get(this.parent.key)}readDomainEntity(){let{entity:e,api:t}=this;if(t.domain)return t.domain.findEntity(e.key,e.domain)}getPathParameters(e={}){return e.absolute?[...this.getAbsoluteResourcePath().matchAll(/\{([^}]+)\}/g)].map(i=>i[1]):this.hasCollection?[...this.resourcePath.matchAll(/\{([^}]+)\}/g)].map(i=>i[1]):[]}exposeEntity(e,t){let i=this.api.domain;if(!i)throw new b("No domain attached to API model",{code:"E_NO_DOMAIN",help:"Attach a data domain to the API model before exposing entities."});let r=this.api.exposes.get(this.key);if(!r)throw new b(`Parent exposure not found: ${this.key}`,{code:"E_PARENT_NOT_FOUND",help:"Make sure the parent exposure key you provided is correct."});let s=r.readDomainEntity();if(!s)throw new b(`Parent entity not found in domain: ${r.entity.key}`,{code:"E_NO_ENTITY",help:"Make sure the parent entity exists in the data domain."});let o=i.findEntity(e.key,e.domain);if(!o)throw new b(`Entity not found in domain: ${e.key}`,{code:"E_NO_ENTITY",help:"Make sure the entity you are trying to expose exists in the data domain."});let a=i.findAssociation(t.key,t.domain);if(!a)throw new b(`No association found from "${s.info.getLabel()||s.key}" to "${e.key}"`,{code:"E_ASSOCIATION_NOT_FOUND",help:"Ensure there is a defined association in the data domain connecting these entities."});let n=s.key,l=o.key,d=a.getParentInstance()?.key,p=d===n||s.listAllParents("up").some(L=>L.key===d),m=a.targets.some(L=>L.key===l||o.listAllParents("up").some(I=>I.key===L.key));if(!p||!m)throw new b(`Association "${t.key}" does not connect parent "${s.info.getLabel()||n}" to "${o.info.getLabel()||l}".`,{code:"E_ASSOCIATION_NOT_FOUND",help:"Ensure there is a defined association in the data domain connecting these entities."});let h=Kt(e,i.key),f=Kt(t,i.key);for(let L of this.api.exposes.values())if(L.parent?.key===r.key&&Kt(L.entity,i.key)===h&&L.parent.association&&Kt(L.parent.association,i.key)===f)throw new b(`Entity ${e.key} is already exposed under this parent with this association.`,{code:"E_ENTITY_ALREADY_EXPOSED",help:"Do not try to expose the same entity with the same association under the same parent."});let k=a.getExposedName(),w=!!a.multiple,S=w?Et(k.toLocaleLowerCase()):k.toLocaleLowerCase(),E=ys(o.info.name||""),A=w?`/${S}`:void 0,_=w?`/${S}/{${E}}`:`/${S}`;if(w&&A){let L=new Set;for(let x of this.api.exposes.values())x.parent?.key===r.key&&x.hasCollection&&x.collectionPath&&L.add(x.collectionPath);let I=1,R=A;for(;L.has(A);)A=`${R}-${I}`,_=`${A}/{${E}}`,I++}let $=a.namespace&&this.api.domain?.key&&a.namespace!==this.api.domain.key,P={kind:Ht,key:W(),entity:{...e},actions:[],isRoot:!1,collectionPath:A,resourcePath:"",hasCollection:w,parent:{key:r.key,association:{key:a.key,...$?{domain:a.namespace}:{}}}},j=new c(this.api,P);return j.setResourcePath(_),this.api.exposes.set(j.key,j),this.api.notifyChange(),j}};var Ss=(c={})=>{let e={...ka,...c};return c.metadata&&(e.metadata={...c.metadata}),{id:g.Currency,config:e}},ka={storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1,validateCurrencyCode:!0},oD={USD_DECIMAL:Ss({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),USD_CENTS:Ss({storageFormat:"integer_cents",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),MULTI_CURRENCY:Ss({storageFormat:"complex_object",allowedCurrencies:["USD","EUR","GBP","JPY","CAD"],decimalPlaces:2,allowNegative:!1}),WITH_NEGATIVES:Ss({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!0}),HIGH_PRECISION:Ss({storageFormat:"decimal",defaultCurrency:"BTC",decimalPlaces:8,allowNegative:!1})};var va={requireVerification:!0,allowSubaddressing:!0,allowInternational:!0};var Yd={requireCountryCode:!0,format:"international",allowExtension:!1,requireVerification:!1,verificationMethod:"sms"};var el=["allowAuthenticated","allowPublic","matchEmailDomain","matchResourceOwner","relationalResourceOwner","matchPathParameter","matchResourceAttribute","lifecycleStatus","matchUserProperty","matchAssociation","matchProjectRole","matchProjectStakeholder"],Xm={allowAuthenticated:["api","exposure","action"],allowPublic:["api","exposure","action"],matchEmailDomain:["api","exposure","action"],matchUserRole:["api","exposure","action"],matchUserProperty:["api","exposure","action"],matchOrganizationRole:["exposure","action"],matchProjectRole:["exposure","action"],matchProjectStakeholder:["exposure","action"],matchResourceOwner:["exposure","action"],relationalResourceOwner:["exposure","action"],matchResourceAttribute:["exposure","action"],matchAssociation:["exposure","action"],matchPathParameter:["exposure","action"],lifecycleStatus:["exposure","action"]};function Xd(c,e){let t;switch(c){case"RBAC":t=[...el,"matchUserRole"];break;case"OrganizationRBAC":t=[...el,"matchOrganizationRole"];break;case"EnterpriseRBAC":t=[...el,"matchUserRole","matchOrganizationRole"];break;default:t=[];break}return e?t.filter(i=>Xm[i]?.includes(e)):t}function tl(c,e){if(e){let t=c.findEntity(e.key,e.domain);return t&&t.hasSemantic(g.User)?t:void 0}for(let t of c.listEntities({includeForeign:!0}))if(t.hasSemantic(g.User))return t}function As(c,e){let t=e||tl(c),i={hasUser:!1,hasUsername:!1,hasPassword:!1,hasRole:!1};if(!t)return i;i.userEntity=t,i.hasUser=!0;for(let r of t.withInheritedProperties())r.hasSemantic(g.UserRole)?(i.roleProperty=r,i.hasRole=!0):r.hasSemantic(g.Username)?(i.usernameProperty=r,i.hasUsername=!0):r.hasSemantic(g.Password)&&(i.passwordProperty=r,i.hasPassword=!0);return i}function Es(c){let e,t;for(let a of c.listEntities())if(!e&&a.hasSemantic(g.Organization)&&(e=a),!t&&a.hasSemantic(g.User)&&(t=a),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=Zd(i,g.OrganizationMembers,g.OrganizationRole),o=s;return!o&&e&&(o=Array.from(e.withInheritedProperties()).find(a=>a.hasSemantic(g.OrganizationRole))),!o&&t&&(o=Array.from(t.withInheritedProperties()).find(a=>a.hasSemantic(g.OrganizationRole))),{hasOrganization:!!e,hasMembersAssociation:!!r,hasOrganizationRole:!!o,orgEntity:e,membersAssoc:r,roleProperty:o}}function il(c){let e,t;for(let a of c.listEntities())if(!e&&a.hasSemantic(g.Project)&&(e=a),!t&&a.hasSemantic(g.User)&&(t=a),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=Zd(i,g.ProjectMembers,g.ProjectRole),o=s;return!o&&e&&(o=Array.from(e.withInheritedProperties()).find(a=>a.hasSemantic(g.ProjectRole))),!o&&t&&(o=Array.from(t.withInheritedProperties()).find(a=>a.hasSemantic(g.ProjectRole))),{hasProject:!!e,hasMembersAssociation:!!r,hasProjectRole:!!o,projectEntity:e,membersAssoc:r,roleProperty:o}}function Zd(c,e,t){let i,r;for(let s of c){let o=[];for(let a of s.listAssociations())o.push(a);for(let a of s.listAllParents("up"))for(let n of a.listAssociations())o.some(l=>l.key===n.key)||o.push(n);for(let a of o)if(a.hasSemantic(e)){let n=a.getSemantic(e);if(!n?.link&&!i&&(i=a),!n?.link)for(let l of a.properties)!r&&l.hasSemantic(t)&&(r=l)}}return{membersAssoc:i,roleProperty:r}}function Zm(c){let e=c.type,i=c.readWebBinding()?.format,r=c.multiple,s;if(e==="string"){let o=c.schema?.maximum,a=typeof o=="number"?o:void 0;if(c.schema?.defaultValue?.type==="function"&&c.schema.defaultValue.value==="random"){let n=c.schema.defaultValue.config;if(n){let l=0,d=!1;n.isFixed?n.length&&(l=n.length,d=!0):a&&(l=a,d=!0),d&&(n.prefix&&(l+=n.prefix.length),n.suffix&&(l+=n.suffix.length),(!a||l>a)&&(a=l))}}s=a?`VARCHAR(${a})`:"TEXT"}else if(e==="number"){let o=c.schema?.defaultValue?.type==="function"&&c.schema.defaultValue.value==="incremental";i==="int32"?s="INTEGER":i==="int64"?s="BIGINT":i==="float"||i==="double"?s="DOUBLE PRECISION":o?s="BIGINT":s="NUMERIC"}else e==="boolean"?s="BOOLEAN":e==="date"?s="DATE":e==="datetime"?s="TIMESTAMPTZ":e==="time"?s="TIME":e==="binary"||e==="json"?s="JSONB":s="TEXT";return r?`${s}[]`:s}function Qd(c){let e=c.getExposedName();if(!e)throw new b("Property missing a name definition.",{code:"E_PROPERTY_NAME_MISSING",status:500});let t=null;if(c.schema?.defaultValue){let p=c.schema.defaultValue.type,m=String(c.schema.defaultValue.value);if(p==="function"){let h=c.type;if(h==="string"){if(m==="uuid-v4"&&c.primary)throw new b("Function 'uuid-v4' cannot be used as a default for a primary key string.",{code:"E_INVALID_DEFAULT_FUNCTION",status:400});if(m!=="random"&&m!=="uuid-v4")throw new b(`Function '${m}' is not supported for string properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else if(h==="number"){if(m!=="incremental")throw new b(`Function '${m}' is not supported for number properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else if(["date","time","datetime"].includes(h)){if(m!=="now")throw new b(`Function '${m}' is not supported for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else throw new b(`Functions are not supported as default values for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}t={type:p,value:m}}let i=!!c.primary,r=!c.required&&!i,s=!!c.unique;!t&&c.hasSemantic(g.DeletedFlag)&&(t={type:"literal",value:"false"});let o=c.getSemantic(g.Currency);if(o){let p=o.config??{},m=p.storageFormat||ka.storageFormat;if(m==="complex_object")return[{name:e,dataType:"JSONB",isNullable:r,isPrimary:i,isUnique:s,defaultRule:null}];if(m==="decimal"||m==="integer_cents"){let h=p.decimalPlaces??ka.decimalPlaces,f=m==="decimal"?`NUMERIC(19, ${h})`:"BIGINT";return[{name:`${e}_amount`,dataType:f,isNullable:r,isPrimary:i,isUnique:s,defaultRule:t},{name:`${e}_currency`,dataType:"CHAR(3)",isNullable:r,isPrimary:!1,isUnique:!1,defaultRule:{type:"literal",value:p.defaultCurrency||"USD"}}]}}let a=[{name:e,dataType:Zm(c),isNullable:r,isPrimary:i,isUnique:s,defaultRule:t}],n=!1,l=c.getSemantic(g.Email);l&&(n=(l.config??va).requireVerification??!0);let d=c.getSemantic(g.Phone);return d&&(n=(d.config??Yd).requireVerification===!0),n&&a.push({name:`_${e}_verified`,dataType:"BOOLEAN",isNullable:!1,isPrimary:!1,isUnique:!1,defaultRule:{type:"literal",value:"false"}}),a}function Qm(c){let e=c.toUpperCase().split("(")[0];return e==="CHARACTER VARYING"&&(e="VARCHAR"),e==="CHARACTER"&&(e="CHAR"),e}function eh(c,e){let t=e.toUpperCase(),i=Qm(c.dataType),r=t.split("(")[0];if(i===r){if(i==="VARCHAR"){let o=c.dataType.match(/\((\d+)\)/),a=o?Number.parseInt(o[1],10):null,n=t.match(/\((\d+)\)/),l=n?Number.parseInt(n[1],10):null;return!!(!l||a&&l>=a)}return!0}return{INTEGER:["BIGINT","NUMERIC","VARCHAR","TEXT"],BIGINT:["NUMERIC","VARCHAR","TEXT"],DATE:["TIMESTAMPTZ"],BOOLEAN:["VARCHAR","TEXT"]}[i]?.includes(r)||!1}function th(c,e,t,i,r){if(!e.actions)return;let s=e.entity.key,o=t.get(s),a=i.findEntity(s);if(!o)return;let n=Array.from(o.withInheritedProperties()),l=new Set(n.map(m=>m.key)),d=Array.from(o.withInheritedAssociations()),p=new Set(d.map(m=>m.key));for(let m of e.actions)if(!(!m.projection||!Array.isArray(m.projection.fields)))for(let h of m.projection.fields)if(h.type==="association"){let f=h.key.split("."),k=f[0];if(p.has(k)){let w=d.find(S=>S.key===k);f.length>1&&(!w||w.schema?.embedded!==!0)&&r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:`Projected association '${h.key}' is invalid because association '${k}' is not embedded.`})}else{let w=!1,S=`Projected association '${h.key}' no longer exists on entity '${o.info.getLabel()}'.`;if(a){let E=Array.from(a.withInheritedAssociations()).find(A=>A.key===k);if(E){let A;try{A=E.getExposedName()}catch{}if(A){let _=d.find($=>{try{return $.getExposedName()===A}catch{return!1}});_&&(f.length>1&&_.schema?.embedded!==!0?S=`Projected association '${h.key}' is invalid because remapped association '${_.key}' is not embedded.`:w=!0)}}}w||r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:S})}}else{let f=h.key.split("."),k=f[0];if(l.has(k)){let w=n.find(S=>S.key===k);f.length>1&&(!w||w.type!=="json"?r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid because root property '${k}' is not of type 'json'.`}):w.jsonSchema&&(St(w.jsonSchema,f.slice(1))||r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid according to the JSON Schema of '${k}'.`})))}else{let w=!1;if(a){let S=Array.from(a.withInheritedProperties()).find(E=>E.key===k);if(S){let E;try{E=S.getExposedName()}catch{}if(E){let A=n.find(_=>{try{return _.getExposedName()===E}catch{return!1}});A&&(f.length===1||A.type==="json")&&(w=!0,f.length>1&&A.jsonSchema&&(St(A.jsonSchema,f.slice(1))||(w=!1)))}}}w||r.actionProjectionsWithMismatches.push({exposureKey:c,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' no longer exists on entity '${o.info.getLabel()}'.`})}}}function ih(c,e,t,i,r){if(!e.paginationContract)return;let s=e.paginationContract,o=e.entity.key,a=t.get(o);if(!a)return;let n=Array.from(a.withInheritedProperties()),l=new Set(n.map(m=>m.key)),d=i.findEntity(o),p=(m,h)=>{if(!(!m||!Array.isArray(m)))for(let f of m){let k=f.split("."),w=k[0];if(l.has(w)){let S=n.find(E=>E.key===w);k.length>1&&(!S||S.type!=="json"?r.paginationFieldsWithMismatches.push({exposureKey:c,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid because root property '${w}' is not of type 'json'.`}):S.jsonSchema&&(St(S.jsonSchema,k.slice(1))||r.paginationFieldsWithMismatches.push({exposureKey:c,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid according to the JSON Schema of '${w}'.`})))}else{let S=!1;if(d){let E=Array.from(d.withInheritedProperties()).find(A=>A.key===w);if(E){let A;try{A=E.getExposedName()}catch{}if(A){let _=n.find($=>{try{return $.getExposedName()===A}catch{return!1}});_&&(k.length===1||_.type==="json")&&(S=!0,k.length>1&&_.jsonSchema&&(St(_.jsonSchema,k.slice(1))||(S=!1)))}}}S||r.paginationFieldsWithMismatches.push({exposureKey:c,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' no longer exists on entity '${a.info.getLabel()}'.`})}}};p(s.filterableFields,"filterable"),p(s.sortableFields,"sortable"),p(s.searchableFields,"searchable")}function ep(c,e){let t=c.domain,i={hasUpdate:!1,canProceed:!0,breakingChanges:[],exposedEntitiesToRemove:[],subEndpointsToRemove:[],userModelRemapping:[],sessionPropertiesToRemove:[],accessRulesWithMismatches:[],paginationFieldsWithMismatches:[],actionProjectionsWithMismatches:[]};if(!t)return i.hasUpdate=!0,i;if(t.key===e.key&&t.info.version===e.info.version)return i;i.hasUpdate=!0;let r=new Map;for(let I of t.listEntities())r.set(I.key,I);let s=new Map;for(let I of e.listEntities())s.set(I.key,I);let o=new Set;for(let[I,R]of c.exposes.entries()){let x=r.has(R.entity.key),D=s.get(R.entity.key);if(!D){let M=r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.exposedEntitiesToRemove.push({key:I,entityKey:R.entity.key,name:R.entity.key,reason:`Entity ${M} no longer exists in the domain.`}),o.add(I);continue}if(x){let M=r.get(R.entity.key),Y=new Map;for(let ee of M.withInheritedProperties())try{let te=ee.getExposedName();te&&Y.set(te,ee)}catch{}let Q=new Map;for(let ee of D.withInheritedProperties())try{let te=ee.getExposedName();te&&Q.set(te,ee)}catch{}for(let[ee,te]of Y.entries()){let _e=Q.get(ee);if(!_e)continue;let de=Qd(te),ye=Qd(_e);for(let Se of de){let le=ye.find(yt=>yt.name===Se.name);if(!le)continue;if(Se.isPrimary&&!le.isPrimary){i.canProceed=!1;let yt=M.info.getLabel(),bt=`Cannot remove Primary Key constraint from column '${Se.name}' in entity '${yt}'.`;i.breakingChanges.push({type:"primary_key_removed",entityKey:M.key,propertyKey:te.key,reason:bt})}if(!eh(Se,le.dataType)){i.canProceed=!1;let yt=M.info.getLabel(),bt=`Cannot safely cast column '${Se.name}' in entity '${yt}' from ${Se.dataType} to ${le.dataType}.`;i.breakingChanges.push({type:"type_change_unsafe",entityKey:M.key,propertyKey:te.key,reason:bt})}let $e=Se.isNullable&&!le.isNullable,De=!!le.defaultRule;if($e&&!De){i.canProceed=!1;let yt=M.info.getLabel(),bt=`Cannot make column '${Se.name}' in entity '${yt}' required without providing a default value to backfill existing records.`;i.breakingChanges.push({type:"column_not_null_missing_default",entityKey:M.key,propertyKey:te.key,reason:bt})}}}}}let a=!0;for(;a;){a=!1;for(let[I,R]of c.exposes.entries())if(!o.has(I)){if(R.isRoot===!1&&!R.parent){let x=r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:I,parentKey:"",associationKey:"",name:R.entity.key,reason:`Sub-endpoint for entity ${x} is missing a parent reference.`}),o.add(I),a=!0;continue}if(R.parent){let x=c.exposes.get(R.parent.key);if(!x){i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:R.parent.selfRoute?"":R.parent.association?.key??"unknown",name:R.entity.key,reason:`Parent exposure "${R.parent.key}" does not exist in the API model.`}),o.add(I),a=!0;continue}let D=r.get(x.entity.key),M=D?.info.getLabel()||x.entity.key;if(o.has(R.parent.key)){i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:R.parent.selfRoute?"":R.parent.association?.key??"unknown",name:R.entity.key,reason:`Parent exposure for entity ${M} is scheduled for removal.`}),o.add(I),a=!0;continue}let Y=s.get(x.entity.key);if(!Y){i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:R.parent.selfRoute?"":R.parent.association?.key??"unknown",name:R.entity.key,reason:`Parent entity ${M} is scheduled for removal.`}),o.add(I),a=!0;continue}if(R.parent.selfRoute){if(!x.hasCollection||!x.collectionPath){i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:"",name:R.entity.key,reason:`Parent exposure for entity ${M} does not have a collection endpoint required for selfRoute.`}),o.add(I),a=!0;continue}let je=s.get(R.entity.key);if(!je||!je.hasSemantic(g.User)){let Ii=je?.info.getLabel()||r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:"",name:R.entity.key,reason:`Entity ${Ii} no longer carries the User semantic required for selfRoute.`}),o.add(I),a=!0;continue}continue}if(!R.parent.association||!R.parent.association.key){let je=r.get(R.entity.key)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:"unknown",name:R.entity.key,reason:`Sub-endpoint for entity ${je} does not define a parent association.`}),o.add(I),a=!0;continue}let Q=R.parent.association.key,ee=R.parent.association.domain,te=e.findAssociation(Q,ee)??Array.from(Y.withInheritedAssociations()).find(je=>je.key===Q),_e=t.findAssociation(Q,ee)??(D?Array.from(D.withInheritedAssociations()).find(je=>je.key===Q):void 0),de=te?.info.getLabel()||_e?.info.getLabel()||Q;if(!te){i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:Q,name:R.entity.key,reason:`Parent association ${de} is missing in the new domain.`}),o.add(I),a=!0;continue}let ye=s.get(R.entity.key),Se=Y.key,le=R.entity.key,$e=te.getParentInstance()?.key,De=$e===Se||Y.listAllParents("up").some(je=>je.key===$e),yt=$e===le||ye&&ye.listAllParents("up").some(je=>je.key===$e),bt=te.targets.some(je=>je.key===le||ye&&ye.listAllParents("up").some(Ii=>Ii.key===je.key)),mp=te.targets.some(je=>je.key===Se||Y.listAllParents("up").some(Ii=>Ii.key===je.key));if(!(De&&bt||yt&&mp)){let Ii=(r.get(R.entity.key)||ye)?.info.getLabel()||R.entity.key;i.subEndpointsToRemove.push({key:I,parentKey:R.parent.key,associationKey:Q,name:R.entity.key,reason:`Target entity ${Ii} is no longer a valid target for the parent association ${de}.`}),o.add(I),a=!0;continue}}}}let n,l;if(c.user&&(n=r.get(c.user.key),l=s.get(c.user.key),!l)){i.canProceed=!1;let R=`User entity '${n?.info.getLabel()||c.user.key}' no longer exists in the new domain version.`;i.breakingChanges.push({type:"user_entity_missing",entityKey:c.user.key,propertyKey:"",reason:R})}if(c.user&&l&&n){let I=Array.from(n.withInheritedProperties()),R=Array.from(l.withInheritedProperties());if(c.session?.properties)for(let x of c.session.properties){let D=I.find(Q=>Q.key===x.key);if(!D){i.sessionPropertiesToRemove.push(x.key);continue}let M;try{M=D.getExposedName()}catch{}if(!M){i.sessionPropertiesToRemove.push(x.key);continue}let Y=R.find(Q=>{try{return Q.getExposedName()===M}catch{return!1}});Y?Y.key!==D.key&&i.userModelRemapping.push({oldPropertyKey:D.key,newPropertyKey:Y.key,exposedName:M,reason:`Property ${D.info.getLabel(D.key)} has been renamed to ${Y.info.getLabel(Y.key)}.`}):i.sessionPropertiesToRemove.push(x.key)}}let d=As(e,l),p=Es(e),m=il(e),h=d.roleProperty??(l?Array.from(l.withInheritedProperties()).find(I=>I.hasSemantic(g.UserRole)):void 0),f=p.roleProperty,k=m.roleProperty,w=h?.schema?.enum,S=f?.schema?.enum,E=k?.schema?.enum,A=(I,R)=>{if(I.type==="matchOrganizationRole"){let x=I;if(!f)i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:R,reason:"No organization role property configured in the new domain model."});else if(S&&Array.isArray(S)&&x.roles)for(let D of x.roles)S.includes(D)||i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:R,reason:`Organization role '${D}' is no longer a valid role in the new domain model.`})}else if(I.type==="matchProjectRole"){let x=I;if(!k)i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:R,reason:"No project role property configured in the new domain model."});else if(E&&Array.isArray(E)&&x.roles)for(let D of x.roles)E.includes(D)||i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:R,reason:`Project role '${D}' is no longer a valid role in the new domain model.`})}},_=(I,R)=>{if(I.type==="matchUserRole"){let x=I;if(!h){i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:"No role field configured on the new user model."});return}if(!w||!Array.isArray(w))return;let D=x.mode;if(D==="allowlist")for(let M of x.allowed??[])w.includes(M)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`Role '${M}' in the allowed list is no longer a valid role in the new user model.`});else if(D==="denylist")for(let M of x.denied??[])w.includes(M)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`Role '${M}' in the denied list is no longer a valid role in the new user model.`});else D==="minRole"?x.minimumRole&&!w.includes(x.minimumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`minimumRole '${x.minimumRole}' is no longer a valid role in the new user model.`}):D==="maxRole"&&x.maximumRole&&!w.includes(x.maximumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:R,reason:`maximumRole '${x.maximumRole}' is no longer a valid role in the new user model.`})}},$=(I,R,x)=>{if(I.type==="matchResourceAttribute"){let D=I;if(!x)return;let M=s.get(x);if(!M)return;let Y=Array.from(M.withInheritedProperties());if(!Y.some(ee=>ee.key===D.attribute)){let ee=r.get(x),te=D.attribute,_e=!1;if(ee){let de=Array.from(ee.withInheritedProperties()).find(ye=>ye.key===D.attribute);if(de){te=de.info.getLabel(de.key);let ye;try{ye=de.getExposedName()}catch{}ye&&Y.find(le=>{try{return le.getExposedName()===ye}catch{return!1}})&&(_e=!0)}}if(!_e){let de=M.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceAttribute",location:R,reason:`Property attribute '${te}' no longer exists on entity '${de}'.`})}}}},P=(I,R,x)=>{if(I.type==="matchResourceOwner"){let D=I;if(D.target==="user-entity"){c.user&&!l&&i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:"User entity is missing in the new domain."});return}if(!x)return;let M=s.get(x);if(!M)return;if(D.association&&D.association.key){let Y=D.association.key,Q=D.association.domain,ee=e.findAssociation(Y,Q),te=Array.from(M.withInheritedAssociations());if(!(ee?te.some(de=>de.key===ee.key):te.some(de=>de.key===Y))){let de=r.get(x),ye=Y,Se=!1;if(de){let $e=Array.from(de.withInheritedAssociations()).find(De=>De.key===Y);if($e){ye=$e.info.getLabel($e.key);let De;try{De=$e.getExposedName()}catch{}De&&te.find(bt=>{try{return bt.getExposedName()===De}catch{return!1}})&&(Se=!0)}}if(!Se){let le=M.info.getLabel();e.resolveOwnershipPath(x)!==null?i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:`Direct ownership association '${ye}' no longer exists on entity '${le}'. The resolved ownership path will be used instead.`}):i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:`Ownership association '${ye}' no longer exists on entity '${le}' and no transitively resolved ownership path is available.`})}}}else if(!(e.resolveOwnershipPath(x)!==null)){let Q=M.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:R,reason:`No ownership association specified and no transitively resolved ownership path exists for entity '${Q}'.`})}}},j=(I,R)=>{if(I.type==="matchUserProperty"){let x=I;if(c.user&&!l){i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:R,reason:"User entity is missing in the new domain."});return}l&&x.property&&(Array.from(l.withInheritedProperties()).some(Y=>Y.key===x.property)||i.userModelRemapping.some(Q=>Q.oldPropertyKey===x.property)||i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:R,reason:`User property '${x.property}' no longer exists on the User entity.`}))}},L=(I,R,x)=>{if(I.type==="matchAssociation"){let M=I.association;if(!M||!M.key){i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:R,reason:"No target association specified for match association access rule."});return}let Y=M.key,Q=M.domain;if(!e.findAssociation(Y,Q)){let te=x?s.get(x):void 0,_e=te?Array.from(te.withInheritedAssociations()):[];if(!_e.some(ye=>ye.key===Y)){let ye=x?r.get(x):void 0,Se=!1;if(ye){let $e=Array.from(ye.withInheritedAssociations()).find(De=>De.key===Y);if($e){let De;try{De=$e.getExposedName()}catch{}De&&_e.find(bt=>{try{return bt.getExposedName()===De}catch{return!1}})&&(Se=!0)}}if(!Se){let le=te?.info.getLabel()||ye?.info.getLabel()||x||"Entity";i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:R,reason:`Target association '${Y}' no longer exists in domain or on entity '${le}'.`})}}}}};if(c.accessScenarios)for(let I of c.accessScenarios)for(let R of I.predicate.getLeafRules())_(R,{type:"api",key:c.key}),A(R,{type:"api",key:c.key}),j(R,{type:"api",key:c.key});for(let[I,R]of c.exposes.entries())if(!o.has(I)){if(R.accessScenarios)for(let x of R.accessScenarios)for(let D of x.predicate.getLeafRules())_(D,{type:"exposure",key:I}),A(D,{type:"exposure",key:I}),$(D,{type:"exposure",key:I},R.entity.key),P(D,{type:"exposure",key:I},R.entity.key),j(D,{type:"exposure",key:I}),L(D,{type:"exposure",key:I},R.entity.key);if(R.actions){for(let x of R.actions)if(x.accessScenarios)for(let D of x.accessScenarios)for(let M of D.predicate.getLeafRules())_(M,{type:"action",key:`${I}:${x.kind}`}),A(M,{type:"action",key:`${I}:${x.kind}`}),$(M,{type:"action",key:`${I}:${x.kind}`},R.entity.key),P(M,{type:"action",key:`${I}:${x.kind}`},R.entity.key),j(M,{type:"action",key:`${I}:${x.kind}`}),L(M,{type:"action",key:`${I}:${x.kind}`},R.entity.key)}th(I,R,s,t,i),ih(I,R,s,t,i)}return i}function tp(c,e,t){if(!t.canProceed)throw new b("Cannot apply domain update because it contains breaking changes. Details in the report.",{code:"E_CANNOT_PROCEED_WITH_UPGRADE",status:400});let i=c.domain;c.dependencies.clear(),c.dependencies.set(e.key,e),c.dependencyList=[{key:e.key,version:e.info.version}];let r=[...t.exposedEntitiesToRemove,...t.subEndpointsToRemove];for(let A of r)c.exposes.delete(A.key);if(c.user&&c.session){let A=new Set(t.sessionPropertiesToRemove),_=new Map;for(let $ of t.userModelRemapping)_.set($.oldPropertyKey,$.newPropertyKey);if(c.session.properties){let $=[];for(let P of c.session.properties){if(A.has(P.key))continue;let j=_.get(P.key);j?$.push({...P,key:j}):$.push(P)}c.session.properties=$}}let s=new Map;for(let A of e.listEntities())s.set(A.key,A);let o=c.user?s.get(c.user.key):void 0,a=As(e,o),n=Es(e),l=il(e),d=a.roleProperty??(o?Array.from(o.withInheritedProperties()).find(A=>A.hasSemantic(g.UserRole)):void 0),p=n.roleProperty,m=l.roleProperty,h=d?.schema?.enum,f=p?.schema?.enum,k=m?.schema?.enum,w=(A,_,$,P,j)=>{if(A.type===_){let L=A;if(!$)return!0;if(P&&Array.isArray(P)&&L.roles&&L.roles.length>0){let I=L.roles.filter(R=>P.includes(R));if(I.length===0)return!0;L.roles=I}return j.push(A),!0}return!1},S=(A,_)=>{let $=[];for(let P of A)if(P.type==="matchUserRole"){let j=P;if(!d)continue;if(h&&Array.isArray(h)){let L=j.mode;if(L==="allowlist"){let I=j.allowed??[];if(I.length>0){let R=I.filter(x=>h.includes(x));if(R.length===0)continue;j.allowed=R}}else if(L==="denylist"){let I=j.denied??[];I.length>0&&(j.denied=I.filter(R=>h.includes(R)))}else if(L==="minRole"){if(j.minimumRole&&!h.includes(j.minimumRole))continue}else if(L==="maxRole"&&j.maximumRole&&!h.includes(j.maximumRole))continue}$.push(P)}else{if(w(P,"matchOrganizationRole",p,f,$))continue;if(w(P,"matchProjectRole",m,k,$))continue;if(P.type==="matchResourceAttribute"&&_){let j=P,L=s.get(_);if(!L)continue;let I=Array.from(L.withInheritedProperties());if(I.some(x=>x.key===j.attribute))$.push(P);else{let x,D=i?.findEntity(_);if(D){let Y=Array.from(D.withInheritedProperties()).find(Q=>Q.key===j.attribute);if(Y){let Q;try{Q=Y.getExposedName()}catch{}Q&&(x=I.find(ee=>{try{return ee.getExposedName()===Q}catch{return!1}}))}}if(x)j.attribute=x.key,$.push(P);else continue}}else if(P.type==="matchResourceOwner"&&_){let j=P;if(j.target==="user-entity")$.push(P);else if(j.association&&j.association.key){let L=s.get(_);if(!L)continue;let I=Array.from(L.withInheritedAssociations()),R=j.association.key;if(I.some(D=>D.key===R))$.push(P);else{let D,M=i?.findEntity(_);if(M){let Q=Array.from(M.withInheritedAssociations()).find(ee=>ee.key===R);if(Q){let ee;try{ee=Q.getExposedName()}catch{}if(ee){let te=I.find(_e=>{try{return _e.getExposedName()===ee}catch{return!1}});te&&(D=te.key)}}}D?(j.association.key=D,$.push(P)):(j.association=void 0,$.push(P))}}else $.push(P)}else if(P.type==="matchUserProperty"){let j=P;if(c.user){let L=s.get(c.user.key);if(L&&j.property)if(Array.from(L.withInheritedProperties()).some(x=>x.key===j.property))$.push(P);else{let x=t.userModelRemapping.find(D=>D.oldPropertyKey===j.property);x?(j.property=x.newPropertyKey,$.push(P)):(j.property="",$.push(P))}else $.push(P)}else $.push(P)}else if(P.type==="matchAssociation"){let j=P;if(j.association&&j.association.key){let L=_?s.get(_):void 0;if(L&&_){let I=Array.from(L.withInheritedAssociations());if(!I.some(x=>x.key===j.association.key)){let x=i?.findEntity(_);if(x){let M=Array.from(x.withInheritedAssociations()).find(Y=>Y.key===j.association.key);if(M){let Y;try{Y=M.getExposedName()}catch{}if(Y){let Q=I.find(ee=>{try{return ee.getExposedName()===Y}catch{return!1}});Q&&(j.association.key=Q.key)}}}}}}$.push(P)}else $.push(P)}return $},E=(A,_)=>{let $=[];for(let P of A.children)if(P instanceof qe)E(P,_),$.push(P);else{let j=S([P],_);$.push(...j)}A.children=$};if(c.accessScenarios)for(let A of c.accessScenarios)E(A.predicate);for(let A of c.exposes.values()){let _=A.entity.key,$=s.get(_),P=i?.findEntity(_),j=x=>x,L=x=>x,I=!1,R=!1;if($){let x=Array.from($.withInheritedProperties()),D=new Set(x.map(Q=>Q.key)),M=Array.from($.withInheritedAssociations()),Y=new Set(M.map(Q=>Q.key));j=Q=>{let ee=Q.split("."),te=ee[0],_e=te,de=!1;if(D.has(te))de=!0;else if(P){let Se=Array.from(P.withInheritedProperties()).find(le=>le.key===te);if(Se){let le;try{le=Se.getExposedName()}catch{}if(le){let $e=x.find(De=>{try{return De.getExposedName()===le}catch{return!1}});$e&&(_e=$e.key,de=!0)}}}ee[0]=_e;let ye=ee.join(".");return de||(I=!0),ye},L=Q=>{let ee=Q.split("."),te=ee[0],_e=te,de=!1;if(Y.has(te))de=!0;else if(P){let Se=Array.from(P.withInheritedAssociations()).find(le=>le.key===te);if(Se){let le;try{le=Se.getExposedName()}catch{}if(le){let $e=M.find(De=>{try{return De.getExposedName()===le}catch{return!1}});$e&&(_e=$e.key,de=!0)}}}ee[0]=_e;let ye=ee.join(".");return de||(R=!0),ye}}if(A.accessScenarios)for(let x of A.accessScenarios)E(x.predicate,_);if(A.actions)for(let x of A.actions){if(x.accessScenarios)for(let D of x.accessScenarios)E(D.predicate,_);x.projection&&Array.isArray(x.projection.fields)&&(x.projection.fields=x.projection.fields.map(D=>{if(D.type==="association"){R=!1;let M=L(D.key),Q=t.actionProjectionsWithMismatches.some(ee=>ee.exposureKey===A.key&&ee.actionKind===x.kind&&ee.fieldType==="association"&&ee.fieldKey===D.key)||R?!0:D.invalid;return{...D,key:M,invalid:Q}}else{I=!1;let M=j(D.key),Q=t.actionProjectionsWithMismatches.some(ee=>ee.exposureKey===A.key&&ee.actionKind===x.kind&&ee.fieldType==="property"&&ee.fieldKey===D.key)||I?!0:D.invalid;return{...D,key:M,invalid:Q}}}))}if(A.paginationContract&&$){let x=A.paginationContract;x.filterableFields&&(x.filterableFields=x.filterableFields.map(j)),x.sortableFields&&(x.sortableFields=x.sortableFields.map(j)),x.searchableFields&&(x.searchableFields=x.searchableFields.map(j))}}c.notifyChange()}var Ei=class c extends cr{kind;key;info;user;authentication;authorization;session;exposes;accessScenarios;rateLimiting;termsOfService;contact;license;pagination;#e=!0;#t=!1;get domain(){if(this.dependencyList.length===0)return;let e=this.dependencyList[0];return this.dependencies.get(e.key)}static createSchema(e={}){let{key:t=W(),exposes:i=[],pagination:r}=e,s=he.fromJSON(e.info,{name:"Unnamed API"}).toJSON(),o={kind:ke,key:t,info:s,exposes:i,pagination:r?structuredClone(r):{kind:"cursor"}};return e.user&&(o.user=structuredClone(e.user)),e.dependencyList&&(o.dependencyList=structuredClone(e.dependencyList)),e.authentication&&(o.authentication=structuredClone(e.authentication)),e.authorization&&(o.authorization=structuredClone(e.authorization)),e.session&&(o.session=structuredClone(e.session)),Array.isArray(e.accessScenarios)&&(o.accessScenarios=structuredClone(e.accessScenarios)),e.rateLimiting&&(o.rateLimiting=structuredClone(e.rateLimiting)),e.termsOfService&&(o.termsOfService=e.termsOfService),e.contact&&(o.contact=structuredClone(e.contact)),e.license&&(o.license=structuredClone(e.license)),o}constructor(e,t){let i=c.createSchema(e),r=[];if(t instanceof Me)t.readOnly?r.push(t):(console.warn(`Domain ${t.key} is not read only, cloning it. This may have performance implications.`),r.push(t.clone({readOnly:!0})));else if(typeof t=="object"&&t.kind===Ee)r.push(new Me(t,void 0,{readOnly:!0}));else if(t)throw new b("Invalid domain provided. Expected a DataDomain instance or schema.",{code:"E_DOMAIN_INVALID",help:"It looks like the provided data domain is not a valid instance or domain schema."});if(t){if(!t.info.version)throw new b(`Domain ${t.key} must have a version.`,{code:"E_DOMAIN_NO_VERSION",help:"Before attaching the data domain, give it a version name. Only versioned domains can be attached to an API model."});i.dependencyList=[{key:t.key,version:t.info.version}]}super(i.dependencyList,r),this.kind=i.kind,this.key=i.key,this.info=new he(i.info),this.user=i.user,this.pagination=i.pagination?structuredClone(i.pagination):{kind:"cursor"},i.authentication&&(this.authentication=structuredClone(i.authentication)),i.authorization&&(this.authorization=structuredClone(i.authorization)),i.session&&(this.session=structuredClone(i.session)),Array.isArray(i.exposes)?this.exposes=new Map(i.exposes.map(s=>[s.key,new hr(this,s)])):this.exposes=new Map,Array.isArray(i.accessScenarios)?this.accessScenarios=i.accessScenarios.map(s=>new It(this,s)):this.accessScenarios=[],i.rateLimiting&&(this.rateLimiting=new ii(i.rateLimiting)),i.termsOfService&&(this.termsOfService=i.termsOfService),i.contact&&(this.contact=i.contact),i.license&&(this.license=i.license),this.#e=!1}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON(),exposes:Array.from(this.exposes.values()).map(t=>t.toJSON()),pagination:structuredClone(this.pagination)};return this.user&&(e.user={...this.user}),this.dependencyList.length>0&&(e.dependencyList=structuredClone(this.dependencyList)),this.authentication&&(e.authentication=structuredClone(this.authentication)),this.authorization&&(e.authorization=structuredClone(this.authorization)),this.session&&(e.session=structuredClone(this.session)),Array.isArray(this.accessScenarios)&&this.accessScenarios.length>0&&(e.accessScenarios=this.accessScenarios.map(t=>t.toJSON())),this.rateLimiting&&(e.rateLimiting=this.rateLimiting.toJSON()),this.termsOfService&&(e.termsOfService=this.termsOfService),this.contact&&(e.contact=structuredClone(this.contact)),this.license&&(e.license=structuredClone(this.license)),e}notifyChange(){this.#t||this.#e||(this.#t=!0,queueMicrotask(()=>{this.#t=!1;let e=new Event("change");this.dispatchEvent(e)}))}exposeEntity(e,t={}){let i=this.domain;if(!i)throw new b("No domain attached to API model",{code:"E_NO_DOMAIN",help:"Attach a data domain to the API model before exposing entities."});let r=Kt(e,this.domain?.key);if(t.selfRoute){if(!t.parentId)throw new b("Parent ID must be specified for selfRoute exposure",{code:"E_NO_PARENT",help:"Provide a parent when exposing a selfRoute."});if(t.association)throw new b("Association must not be specified for selfRoute exposure",{code:"E_UNEXPECTED_ASSOCIATION",help:"selfRoute does not use associations."});let m=this.exposes.get(t.parentId);if(!m)throw new b(`Parent exposure not found: ${t.parentId}`,{code:"E_PARENT_NOT_FOUND",help:"Make sure the parent exposure key you provided is correct."});if(!m.hasCollection||!m.collectionPath)throw new b("Parent exposure must have a collection endpoint for selfRoute",{code:"E_NO_COLLECTION",help:"selfRoute requires the parent exposure to have a collection path."});let h=i.findEntity(e.key,e.domain);if(!h)throw new b(`Entity not found in domain: ${e.key}`,{code:"E_NO_ENTITY",help:"Make sure the entity you are trying to expose exists in the data domain."});if(!h.hasSemantic(g.User))throw new b("selfRoute exposure can only be created for an entity carrying the User semantic",{code:"E_NOT_USER_ENTITY",help:"Annotate the entity with the User semantic before exposing it as a selfRoute."});for(let w of this.exposes.values())if(w.parent?.selfRoute&&w.parent.key===t.parentId)throw new b(`A selfRoute exposure is already registered for parent ${t.parentId}`,{code:"E_ENTITY_ALREADY_EXPOSED",help:"Only one selfRoute exposure can be created per parent exposure."});let f={kind:Ht,key:W(),entity:e,actions:[],isRoot:!1,hasCollection:!1,resourcePath:"/me",parent:{key:m.key,selfRoute:!0}},k=new hr(this,f);return this.exposes.set(k.key,k),this.notifyChange(),k}let{parentId:s,association:o}=t;if(s&&!o)throw new b("Association not specified for nested entity",{code:"E_NO_ASSOCIATION",help:"Provide an association when exposing a nested entity."});if(!s&&o)throw new b("Association specified for non nested entity",{code:"E_NO_PARENT",help:"Provide a parent when exposing a nested entity."});if(s&&o){let m=this.exposes.get(s);if(!m)throw new b(`Parent exposure not found: ${s}`,{code:"E_PARENT_NOT_FOUND",help:"Make sure the parent exposure key you provided is correct."});return m.exposeEntity(e,o)}for(let m of this.exposes.values())if(m.isRoot&&Kt(m.entity,this.domain?.key)===r)throw new b(`Entity ${e.key} is already exposed as a root entity.`,{code:"E_ENTITY_ALREADY_EXPOSED",help:"Do not try to expose already exposed entity."});let a=i.findEntity(e.key,e.domain);if(!a)throw new b(`Entity not found in domain: ${e.key}`,{code:"E_NO_ENTITY",help:"Make sure the entity you are trying to expose exists in the data domain."});let{collectionPath:n,resourcePath:l}=this.generateUniqueRootPaths(a.info.name||""),d={kind:Ht,key:W(),entity:{...e},actions:[],isRoot:!0,collectionPath:n,resourcePath:l,hasCollection:!0},p=new hr(this,d);return this.exposes.set(p.key,p),this.notifyChange(),p}generateUniqueRootPaths(e){let t=Et(e.toLocaleLowerCase()),i=ys(e),r=`/${t}`,s=`/${t}/{${i}}`,o=1,a=r;for(;this.findCollectionPathCollision(r);)r=`${a}-${o}`,s=`${r}/{${i}}`,o++;return{collectionPath:r,resourcePath:s}}removeExposedEntity(e){if(!this.exposes.has(e))throw new b(`Exposed entity with key "${e}" not found.`,{code:"E_NO_EXPOSURE",help:"The exposed entity you are trying to remove does not exist."});this.removeWithChildren(e),this.notifyChange()}removeWithChildren(e){if(!this.exposes.has(e))return;let t=new Set([e]),i=r=>{for(let s of this.exposes.values())s.parent?.key===r&&!t.has(s.key)&&(t.add(s.key),i(s.key))};i(e);for(let r of t)this.exposes.delete(r)}cleanForDomainChange(){this.dependencies.clear(),this.dependencyList=[],this.exposes=new Map,this.user=void 0,this.session&&(this.session.properties=[]),this.notifyChange()}attachDataDomain(e){if(!e.info.version)throw new b("Cannot attach DataDomain without a version. Please set the version in the domain info.",{code:"E_DOMAIN_NO_VERSION",help:"Before attaching the data domain, give it a version name. Only versioned domains can be attached to an API model."});this.cleanForDomainChange(),this.dependencies.set(e.key,e),this.dependencyList=[{key:e.key,version:e.info.version}];for(let t of e.listEntities())if(t.hasSemantic(g.User)){this.user={key:t.key};break}this.notifyChange()}findExposedByEntity(e){let t=Kt(e,this.domain?.key);for(let i of this.exposes.values())if(Kt(i.entity,this.domain?.key)===t)return i}findResourcePathCollision(e,t){for(let i of this.exposes.values())if(!(t&&i.key===t)&&i.isRoot&&i.resourcePath===e)return i}findCollectionPathCollision(e,t){for(let i of this.exposes.values())if(!(t&&i.key===t)&&i.isRoot&&i.hasCollection&&i.collectionPath===e)return i}hasDomainUpdate(e){let t=this.domain;return t?t.key!==e.key||t.info.version!==e.info.version:!0}analyzeDomainUpdate(e){return ep(this,e)}applyDomainUpdate(e,t){tp(this,e,t),this.notifyChange()}};function fr(c){return c.replace(/([A-Z]+)([A-Z][a-z\d])/g,"$1_$2").replace(/([a-z\d])([A-Z])/g,"$1_$2").replace(/[^a-zA-Z0-9_]+/g,"_").replace(/_+/g,"_").replace(/^_+|_+$/g,"").toLowerCase()}var _s=class{used=new Set;register(e){let t=fr(e);if(!this.used.has(t))return this.used.add(t),t;let i=1,r=`${t}_${i}`;for(;this.used.has(r);)i++,r=`${t}_${i}`;return this.used.add(r),r}has(e){return this.used.has(fr(e))}clear(){this.used.clear()}};var rl;(function(c){c.LatLon="lat,lon",c.LonLat="lon,lat",c.PostGIS="postgis",c.Degree="degree",c.WKT="wkt",c.GeoJSON="geojson"})(rl||(rl={}));var sl;(function(c){c.Meters="meters",c.Kilometers="kilometers",c.Miles="miles",c.Feet="feet",c.Yards="yards",c.NauticalMiles="nautical_miles"})(sl||(sl={}));var ol;(function(c){c.WGS84="EPSG:4326",c.WebMercator="EPSG:3857",c.NAD83="EPSG:4269",c.NAD27="EPSG:4267"})(ol||(ol={}));var gr={format:rl.LatLon,spatialReferenceSystem:ol.WGS84,defaultDistanceUnit:sl.Meters,enableSpatialIndexing:!0,enableValidation:!0,enablePostGISIntegration:!0,postGISGeometryType:"POINT",enableDistanceQueries:!0,maxQueryDistance:1e5,enableBoundingBoxQueries:!0,enablePolygonQueries:!1,enableGeoClustering:!1,apiEndpointPrefix:"/nearby",includeElevation:!1,coordinatePrecision:6,enableReverseGeocoding:!1};function al(c){return c.split("#")[1]}function wa(c){return c?c.charAt(0).toUpperCase()+c.slice(1):""}var Bt=class{memorySchemas={};memoryNames={};differentiatedInputFieldsCache=new Map;#e=!1;get hasFileUpload(){return this.#e}getSchemas(){let e={};for(let[t,i]of Object.entries(this.memorySchemas))e[this.memoryNames[t]]=i;return e}generateRootRef(e){return this.generateEntity(e,!1),{$ref:`#/components/schemas/${this.generateSchemaKey(e,!1)}`}}generateCreateInputRef(e){return this.generateEntity(e,"create"),{$ref:`#/components/schemas/${this.generateSchemaKey(e,"create")}`}}generateUpdateInputRef(e){return this.generateEntity(e,"update"),{$ref:`#/components/schemas/${this.generateSchemaKey(e,"update")}`}}generatePatchInputRef(e){return this.generateEntity(e,"patch"),{$ref:`#/components/schemas/${this.generateSchemaKey(e,"patch")}`}}generateInputRef(e,t="create"){return t==="patch"?this.generatePatchInputRef(e):t==="update"?this.generateUpdateInputRef(e):this.generateCreateInputRef(e)}generateProjectedRef(e,t,i){let r,s=i||"read";if("projection"in t&&t.projection?(r=t.projection,"kind"in t&&t.kind&&(s=t.kind)):"type"in t&&"fields"in t&&(r=t),!r||!Array.isArray(r.fields)||r.fields.length===0)return this.generateRootRef(e);let o=this.getProjectionFingerprint(r),a=`${e.key}:projected:${s.toLowerCase()}:${o}`;return this.memorySchemas[a]||this.generateProjectedEntity(e,s,r,a),{$ref:`#/components/schemas/${this.memoryNames[a]}`}}generateLinkInputRef(e,t,i){let r=e.info.name||e.key,s=`${this.generateSchemaKey(e,!1)}LinkInput`;if(this.memorySchemas[s])return{$ref:`#/components/schemas/${s}`};let o={type:"object",properties:{},required:[]};this.memorySchemas[s]=o,this.memoryNames[s]=s,e.info.displayName&&(o.title=`Link ${e.info.displayName} Input`);let a=[],n=r.toLowerCase();for(let p of e.properties)if(p.primary){let m=(p.info.name||p.key).toLowerCase(),h=`${n}_${m}`;o.properties||(o.properties={});let f=this.mapPropertyBase(p,void 0,!0);f.description=`The identifier of the ${r} to link.`,o.properties[h]=f,a.push(h)}let l=t,d=t.semantics.find(p=>p.link);if(d?.link){let p=d.link,m=i.findAssociation(p.key,p.domain);m&&(l=m)}for(let p of l.listProperties()){if(this.isSystemProperty(p))continue;let m=p.info.name||p.key;o.properties||(o.properties={}),o.properties[m]=this.mapPropertyBase(p,void 0,!0);let h=p.schema?.defaultValue?.value!==void 0;p.required&&!h&&a.push(m)}return a.length>0?o.required=a:delete o.required,{$ref:`#/components/schemas/${s}`}}generateSchemaKey(e,t){let i=e.info.name||"entity "+e.key;return t?t==="patch"?`${i}PatchInput`:this.hasDifferentiatedInputFields(e)?`${i}${t==="update"?"Update":"Create"}Input`:`${i}Input`:i}getCacheKey(e,t){if(!t)return e.key;if(t==="patch")return`${e.key}:input:patch`;if(this.hasDifferentiatedInputFields(e)){let i=t==="update"?"update":"create";return`${e.key}:input:${i}`}return`${e.key}:input`}isSystemProperty(e){let t=[g.CreatedTimestamp,g.UpdatedTimestamp,g.DeletedTimestamp,g.DeletedFlag,g.Version,g.ClientIPAddress,g.Calculated,g.Derived];return e.semantics.some(i=>t.includes(i.id))}isSystemAssociation(e){let t=[g.ResourceOwnerIdentifier,g.CreatedBy,g.UpdatedBy,g.DeletedBy];return e.semantics.some(i=>t.includes(i.id))}isReadOnlyOrSystemProperty(e){return!!e.readOnly||this.isSystemProperty(e)}isReadOnlyOrSystemAssociation(e){return!!e.readOnly||this.isSystemAssociation(e)}isWriteOnlyProperty(e){return!!e.writeOnly||e.hasSemantic(g.Password)}hasDifferentiatedInputFields(e,t=new Set){let i=t.size===0;if(i&&this.differentiatedInputFieldsCache.has(e.key))return!!this.differentiatedInputFieldsCache.get(e.key);if(t.has(e))return!1;t.add(e);let r=!1;for(let s of e.properties){if(s.readBinding("web")?.hidden)continue;if((s.readOnly||s.immutable)&&!this.isSystemProperty(s)){r=!0;break}let a=s.schema?.defaultValue?.value!==void 0;if(s.required&&a&&!s.readOnly&&!this.isSystemProperty(s)){r=!0;break}}if(!r){for(let s of e.associations)if(!s.readBinding("web")?.hidden){if(s.readOnly&&!this.isSystemAssociation(s)){r=!0;break}if(s.schema?.embedded===!0){for(let a of s.listTargets())if(this.hasDifferentiatedInputFields(a,t)){r=!0;break}if(r)break}}}return i&&this.differentiatedInputFieldsCache.set(e.key,r),r}stripInputExample(e,t,i){if(!t||typeof t!="object"||Array.isArray(t))return t;let r=i==="update"||i==="patch",s=new Set;for(let d of e.properties)(this.isSystemProperty(d)||d.readOnly||r&&d.immutable)&&s.add(d.getExposedName());let o=new Set,a=new Map,n=new Set;for(let d of e.associations){let p=d.getExposedName();if(this.isSystemAssociation(d)||d.readOnly)o.add(p);else if(d.schema?.embedded===!0){let m=Array.from(d.listTargets());m.length===1&&(a.set(p,m[0]),d.multiple&&n.add(p))}}let l={};for(let[d,p]of Object.entries(t)){if(s.has(d)||o.has(d))continue;let m=a.get(d);m?n.has(d)?Array.isArray(p)?l[d]=p.map(h=>this.stripInputExample(m,h,i)):l[d]=p:p&&typeof p=="object"?l[d]=this.stripInputExample(m,p,i):l[d]=p:l[d]=p}return l}stripOutputExample(e,t){if(!t||typeof t!="object"||Array.isArray(t))return t;let i=new Set;for(let a of e.properties)this.isWriteOnlyProperty(a)&&i.add(a.getExposedName());let r=new Map,s=new Set;for(let a of e.associations){let n=a.getExposedName();if(a.schema?.embedded===!0){let l=Array.from(a.listTargets());l.length===1&&(r.set(n,l[0]),a.multiple&&s.add(n))}}let o={};for(let[a,n]of Object.entries(t)){if(i.has(a))continue;let l=r.get(a);l?s.has(a)?Array.isArray(n)?o[a]=n.map(d=>this.stripOutputExample(l,d)):o[a]=n:n&&typeof n=="object"?o[a]=this.stripOutputExample(l,n):o[a]=n:o[a]=n}return o}generateEntity(e,t){let i=this.getCacheKey(e,t);if(this.memorySchemas[i])return;let r={type:"object",properties:{},required:[]};this.memorySchemas[i]=r;let s=this.generateSchemaKey(e,t);if(this.memoryNames[i]=s,e.info.displayName)if(!t)r.title=e.info.displayName;else if(t==="patch")r.title=`${e.info.displayName} Patch Input`;else if(this.hasDifferentiatedInputFields(e)){let m=t==="update"?"Update":"Create";r.title=`${e.info.displayName} ${m} Input`}else r.title=`${e.info.displayName} Input`;if(e.info.description&&(r.description=e.info.description),e.semantics.length>0){r["x-api-now-semantics"]={};for(let m of e.semantics)r["x-api-now-semantics"][al(m.id)]=m.config?m.config:{}}let o=[],a=!!t,n=t==="create"||t===!0,l=t==="update"||t==="patch",d=t==="patch";for(let m of e.properties){if(a){if(this.isSystemProperty(m)||m.readOnly||l&&m.immutable)continue}else if(this.isWriteOnlyProperty(m))continue;let h=m.readBinding("web");if(h?.hidden)continue;let f=m.hasSemantic(g.PublicUniqueName),k=m.schema?.defaultValue?.value!==void 0,w=n&&k;!d&&m.required&&(!a||!m.readOnly)&&!w&&!(a&&f)&&o.push(m.info.name||m.key),r.properties||(r.properties={}),r.properties[m.info.name||m.key]=this.mapPropertyBase(m,h,a,d)}for(let m of e.associations){if(a&&(this.isSystemAssociation(m)||m.readOnly)||m.readBinding("web")?.hidden)continue;let f=Array.from(m.listTargets());if(f.length===0)continue;let k=!m.schema?.embedded,w=[];for(let _ of f)if(k){let $=_.info.displayName||_.info.name||_.key;w.push({type:"string",description:`The ID of the linked ${$}.`})}else _!==e&&this.generateEntity(_,t),w.push({$ref:`#/components/schemas/${this.generateSchemaKey(_,t)}`});let S;if(w.length>1){let _=m.schema?.unionType||"anyOf";_==="oneOf"?S={oneOf:w}:_==="allOf"?S={allOf:w}:S={anyOf:w}}else S=w[0];let E=m.info.name||m.key;r.properties||(r.properties={}),m.multiple?r.properties[E]={type:d?["array","null"]:"array",items:S}:d?k&&w.length===1?r.properties[E]=typeof S=="object"&&S!==null?{...S,type:["string","null"]}:S:r.properties[E]={oneOf:[S,{type:"null"}]}:r.properties[E]=typeof S=="object"&&S!==null?{...S}:S;let A=r.properties[E];if(typeof A=="object"&&A!==null){let _=A;m.info.displayName&&(_.title=m.info.displayName),m.info.description&&(_.description=m.info.description)}}o.length>0?r.required=o:delete r.required;let p=e.toExample("application/json",{renderMocked:!1,renderOptional:!0});if(p){let m;if(typeof p=="string")try{m=JSON.parse(p)}catch{m=p}else m=p;m&&typeof m=="object"&&!Array.isArray(m)&&(a?m=this.stripInputExample(e,m,t):m=this.stripOutputExample(e,m)),r.example=m}}getProjectionFingerprint(e){let t=[...e.fields].sort((i,r)=>{let s=(i.type||"").localeCompare(r.type||"");return s!==0?s:i.key.localeCompare(r.key)});return`${e.type}:${t.map(i=>`${i.type||"property"}:${i.key}`).join(";")}`}resolveProjectedSchemaKey(e,t,i,r){if(this.memoryNames[i])return this.memoryNames[i];let s=e.info.name||`entity_${e.key}`,o=wa(t)||"Response",a=r||`${s}${o}Response`,n=new Set(Object.values(this.memoryNames));if(!n.has(a))return a;let l=2;for(;n.has(`${a}${l}`);)l++;return`${a}${l}`}generateProjectedEntity(e,t,i,r,s){if(this.memorySchemas[r])return;let o={type:"object",properties:{},required:[]};this.memorySchemas[r]=o;let a=this.resolveProjectedSchemaKey(e,t,r,s);this.memoryNames[r]=a;let n=e.info.name||"entity "+e.key,l=wa(t)||"Response";if(e.info.displayName?o.title=`${e.info.displayName} ${l} Response`:o.title=`${wa(n)} ${l} Response`,e.info.description&&(o.description=e.info.description),e.semantics.length>0){o["x-api-now-semantics"]={};for(let h of e.semantics)o["x-api-now-semantics"][al(h.id)]=h.config?h.config:{}}let d=i.type==="include",p=[];for(let h of e.properties){if(this.isWriteOnlyProperty(h))continue;let f=h.readBinding("web");if(f?.hidden)continue;let k=h.info.name||h.key,w=i.fields.filter(P=>{if(P.type&&P.type!=="property")return!1;let[j]=P.key.split(".");return j===h.key||h.info.name&&j===h.info.name}),S=w.some(P=>!P.key.includes(".")),E=w.filter(P=>P.key.includes(".")),A=!1,_;if(d?S?A=!0:E.length>0&&h.type==="json"&&(A=!0,_=E.map(P=>P.key.split(".").slice(1))):S?A=!1:E.length>0&&h.type==="json"?(A=!0,_=E.map(P=>P.key.split(".").slice(1))):A=!0,!A)continue;let $=this.mapPropertyBase(h,f,!1);_&&_.length>0&&($=this.projectJsonSchema($,_,i.type)),o.properties||(o.properties={}),o.properties[k]=$,h.required&&!h.readOnly&&p.push(k)}for(let h of e.associations){if(h.readBinding("web")?.hidden)continue;let k=Array.from(h.listTargets());if(k.length===0)continue;let w=h.info.name||h.key,S=i.fields.filter(x=>{if(x.type&&x.type!=="association")return!1;let[D]=x.key.split(".");return D===h.key||h.info.name&&D===h.info.name}),E=S.some(x=>!x.key.includes(".")),A=S.filter(x=>x.key.includes(".")),_=h.schema?.embedded===!0,$=A.length>0&&_,P=!1;if(d?(E||$)&&(P=!0):E?P=!1:P=!0,!P)continue;let j=!h.schema?.embedded,L=[];for(let x of k)if(j){let D=x.info.displayName||x.info.name||x.key;L.push({type:"string",description:`The ID of the linked ${D}.`})}else if($){let D=new Set(Array.from(x.withInheritedAssociations()).flatMap(te=>[te.key,te.info.name||""])),M={type:d?"include":"exclude",fields:A.map(te=>{let _e=te.key.split(".").slice(1).join("."),[de]=_e.split(".");return{type:D.has(de)?"association":"property",key:_e,...te.domain?{domain:te.domain}:{}}})},Y=this.getProjectionFingerprint(M),Q=`${x.key}:projected:${t.toLowerCase()}:${Y}`,ee=`${a}_${wa(w)}`;this.generateProjectedEntity(x,t,M,Q,ee),L.push({$ref:`#/components/schemas/${this.memoryNames[Q]}`})}else x!==e&&this.generateEntity(x,!1),L.push({$ref:`#/components/schemas/${this.generateSchemaKey(x,!1)}`});let I;if(L.length>1){let x=h.schema?.unionType||"anyOf";x==="oneOf"?I={oneOf:L}:x==="allOf"?I={allOf:L}:I={anyOf:L}}else I=L[0];o.properties||(o.properties={}),h.multiple?o.properties[w]={type:"array",items:I}:o.properties[w]=typeof I=="object"&&I!==null?{...I}:I;let R=o.properties[w];if(typeof R=="object"&&R!==null){let x=R;h.info.displayName&&(x.title=h.info.displayName),h.info.description&&(x.description=h.info.description)}}if(p.length>0&&o.properties){let h=p.filter(f=>Object.prototype.hasOwnProperty.call(o.properties,f));h.length>0?o.required=h:delete o.required}else delete o.required;let m=e.toExample("application/json",{renderMocked:!1,renderOptional:!0});if(m){let h;if(typeof m=="string")try{h=JSON.parse(m)}catch{h=m}else h=m;h&&typeof h=="object"&&!Array.isArray(h)&&(h=this.filterProjectedExample(h,o.properties)),o.example=h}}projectJsonSchema(e,t,i){if(!e||typeof e!="object")return e;let r=structuredClone(e);if(!r.properties||typeof r.properties!="object")return r;let s=new Set,o=new Map;for(let a of t){if(!a||a.length===0)continue;let[n,...l]=a;if(l.length===0)s.add(n);else{let d=o.get(n);d||(d=[],o.set(n,d)),d.push(l)}}if(i==="include"){let a={};for(let[n,l]of Object.entries(r.properties))if(s.has(n))a[n]=l;else if(o.has(n)){let d=o.get(n);d&&(a[n]=this.projectJsonSchema(l,d,"include"))}r.properties=a}else{let a={};for(let[n,l]of Object.entries(r.properties))if(!s.has(n))if(o.has(n)){let d=o.get(n);d&&(a[n]=this.projectJsonSchema(l,d,"exclude"))}else a[n]=l;r.properties=a}if(r.required&&Array.isArray(r.required)){let a=r.required.filter(n=>r.properties&&Object.prototype.hasOwnProperty.call(r.properties,n));a.length>0?r.required=a:delete r.required}return r}filterProjectedExample(e,t){if(!e||typeof e!="object"||!t)return e;let i={};for(let[r,s]of Object.entries(e)){if(!Object.prototype.hasOwnProperty.call(t,r))continue;let o=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&"properties"in o&&o.properties?i[r]=this.filterProjectedExample(s,o.properties):i[r]=s}return i}mapPropertyBase(e,t,i=!1,r=!1){let s={};(e.readOnly||this.isSystemProperty(e))&&!i&&(s.readOnly=!0),this.isWriteOnlyProperty(e)&&(s.writeOnly=!0),e.deprecated&&(s.deprecated=!0);let o=r&&!e.multiple;if(e.schema){if(typeof e.schema.minimum=="number"&&(e.type==="string"?s.minLength=e.schema.minimum:e.schema.exclusiveMinimum?s.exclusiveMinimum=e.schema.minimum:s.minimum=e.schema.minimum),typeof e.schema.maximum=="number"&&(e.type==="string"?s.maxLength=e.schema.maximum:e.schema.exclusiveMaximum?s.exclusiveMaximum=e.schema.maximum:s.maximum=e.schema.maximum),e.schema.pattern&&(s.pattern=e.schema.pattern),e.schema.enum&&(s.enum=o&&!e.schema.enum.includes(null)?[...e.schema.enum,null]:[...e.schema.enum]),e.schema.defaultValue?.value!==void 0)if(e.schema.defaultValue.type==="literal"||!e.schema.defaultValue.type){let m=Fc(e);m!==void 0&&(s.default=m)}else e.schema.defaultValue.type==="function"&&(s["x-default-generator"]=e.schema.defaultValue.value,e.schema.defaultValue.config&&(s["x-default-generator-config"]=e.schema.defaultValue.config));if(e.schema.examples&&e.schema.examples.length>0)s.example=e.schema.examples[0];else if(e.schema.defaultValue?.type==="function"){let m=e.toExample("application/json");m!==void 0&&(s.example=m)}}e.info.displayName&&(s.title=e.info.displayName);let a=this.formatFunctionGeneratorTag(e.schema?.defaultValue);if(a?e.info.description?s.description=e.info.description.includes(a)?e.info.description:`${a} ${e.info.description}`:s.description=a:e.info.description&&(s.description=e.info.description),e.hasSemantic(g.Password)&&(s.format="password"),t?.xml&&(s.xml={...t.xml}),e.semantics.length>0){s["x-api-now-semantics"]={};for(let m of e.semantics)!this.#e&&(m.id===g.FileURL||m.id===g.ImageURL)&&(this.#e=!0),s["x-api-now-semantics"][al(m.id)]=m.config?m.config:{}}switch(e.type){case"json":if(e.jsonSchema&&typeof e.jsonSchema=="object"){let m=structuredClone(e.jsonSchema);o?m.allOf?s.oneOf=[m,{type:"null"}]:m.oneOf?(Object.assign(s,m),s.oneOf=[...m.oneOf,{type:"null"}]):m.anyOf?(Object.assign(s,m),s.anyOf=[...m.anyOf,{type:"null"}]):m.type?(Object.assign(s,m),Array.isArray(s.type)?s.type.includes("null")||(s.type=[...s.type,"null"]):typeof s.type=="string"&&(s.type=[s.type,"null"])):(Object.assign(s,m),s.type=["object","null"]):Object.assign(s,m)}else s.type=o?["object","null"]:"object",s.additionalProperties=!0;break;case"string":s.type=o?["string","null"]:"string";break;case"number":{let m=t?.format==="int32"||t?.format==="int64"?"integer":"number";s.type=o?[m,"null"]:m,e.schema?.multipleOf!==void 0&&(s.multipleOf=e.schema.multipleOf);break}case"boolean":s.type=o?["boolean","null"]:"boolean";break;case"date":s.type=o?["string","null"]:"string",s.format="date";break;case"datetime":s.type=o?["string","null"]:"string",s.format="date-time";break;case"time":s.type=o?["string","null"]:"string",s.format="time";break;case"binary":if(s.type=o?["string","null"]:"string",s.format="binary",t?.fileTypes&&t.fileTypes.length>0){let m=t.fileTypes.join(", ");s.contentMediaType=t.fileTypes.length===1?t.fileTypes[0]:m;let h=`**Allowed file types:** ${m}`;s.description=s.description?`${s.description}
|
|
54
54
|
|
|
55
55
|
${h}`:h}break;default:s.type=o?["string","null"]:"string"}let n=e.getSemantic(g.GeospatialCoordinates);if(n){let m=n.config??gr,h=m.format||"lat,lon",f="";h==="geojson"?f='Coordinates must be in GeoJSON Point format (e.g. `{"type": "Point", "coordinates": [longitude, latitude]}`). Note that coordinates are represented in [longitude, latitude] order as per the GeoJSON specification.':h==="lat,lon"?f="Coordinates must be in `latitude,longitude` string format (e.g. `40.7128,-74.0060`).":h==="lon,lat"?f="Coordinates must be in `longitude,latitude` string format (e.g. `-74.0060,40.7128`).":h==="wkt"||h==="postgis"?f="Coordinates must be in WKT POINT format (e.g. `POINT(longitude latitude)`). Note that WKT uses [longitude, latitude] order.":h==="degree"&&(f="Coordinates must be in degree format (e.g. `40.7128\xB0N, 74.0060\xB0W`)."),s.description=s.description?`${s.description}
|
|
56
56
|
|
|
@@ -155,7 +155,7 @@ Removes the many-to-many relationship link from the join table within an atomic
|
|
|
155
155
|
* **Precondition Exclusivity:** Unlink is an association removal operation that does not evaluate conditional HTTP precondition headers (\`If-Match\` is not supported).
|
|
156
156
|
* **Response Expectations:** Returns \`204 No Content\` with an empty response body.`,parameters:a,responses:{204:{description:`The **${s.entityNameUpper}** was successfully unlinked.
|
|
157
157
|
|
|
158
|
-
This endpoint returns a \`204 No Content\` status code upon success.`}}};return r.securityProcessor.applyActionSecurity(e,n,r.model),r.responseEnricher.apply(e,n,{hasBody:!1,isResource:!0,isCreate:!1}),n.responses?.["400"]&&(n.responses[400].description="Bad Request. The request parameters failed validation (e.g., missing or invalid path parameters, or the target route does not configure a many-to-many association)."),n.responses?.["404"]&&(n.responses[404].description=`The relationship link between this resource and the specified **${s.entityNameUpper}** was not found, or one of the referenced records does not exist.`),{path:o,method:"delete",operation:n}}};var Ua=class{actionKind="search";process(e,t,i,r,s){let o=t.getAbsoluteCollectionPath();if(!t.hasCollection||!o)return;r.hasSearchAction=!0;let a=`${o}/search`,n=[],l=[],d=[],p=t.paginationContract,m=p?.sortableFields,h=Array.isArray(m)&&m.length?new Set(m):void 0,f=p?.filterableFields,k=Array.isArray(f)&&f.length?new Set(f):void 0;for(let M of i.withInheritedProperties()){if(M.writeOnly||M.hasSemantic(g.Password))continue;let Y=M.getExposedName();M.search&&n.push(M),M.index&&((!h||h.has(M.key)||h.has(Y))&&l.push(Y),(!k||k.has(M.key)||k.has(Y))&&d.push(Y))}let w=n.length>0?n.map(M=>`\`${M.getExposedName()}\``).join(", "):"*None configured*";r.whereAstInjected||(r.whereAstInjected=!0);let S=t.actions.find(tt.isDeleteAction),E=S&&S.strategy==="soft",A=r.model.pagination.kind==="cursor",_=r.model.pagination.maxLimit??100
|
|
158
|
+
This endpoint returns a \`204 No Content\` status code upon success.`}}};return r.securityProcessor.applyActionSecurity(e,n,r.model),r.responseEnricher.apply(e,n,{hasBody:!1,isResource:!0,isCreate:!1}),n.responses?.["400"]&&(n.responses[400].description="Bad Request. The request parameters failed validation (e.g., missing or invalid path parameters, or the target route does not configure a many-to-many association)."),n.responses?.["404"]&&(n.responses[404].description=`The relationship link between this resource and the specified **${s.entityNameUpper}** was not found, or one of the referenced records does not exist.`),{path:o,method:"delete",operation:n}}};var Ua=class{actionKind="search";process(e,t,i,r,s){let o=t.getAbsoluteCollectionPath();if(!t.hasCollection||!o)return;r.hasSearchAction=!0;let a=`${o}/search`,n=[],l=[],d=[],p=t.paginationContract,m=p?.sortableFields,h=Array.isArray(m)&&m.length?new Set(m):void 0,f=p?.filterableFields,k=Array.isArray(f)&&f.length?new Set(f):void 0;for(let M of i.withInheritedProperties()){if(M.writeOnly||M.hasSemantic(g.Password))continue;let Y=M.getExposedName();M.search&&n.push(M),M.index&&((!h||h.has(M.key)||h.has(Y))&&l.push(Y),(!k||k.has(M.key)||k.has(Y))&&d.push(Y))}let w=n.length>0?n.map(M=>`\`${M.getExposedName()}\``).join(", "):"*None configured*";r.whereAstInjected||(r.whereAstInjected=!0);let S=t.actions.find(tt.isDeleteAction),E=S&&S.strategy==="soft",A=r.model.pagination.kind==="cursor",_=r.model.pagination.maxLimit??100,$=r.pathExtractor.extract(a),P=$.length>0,j=[...$,...E?[{in:"query",name:"trash",required:!1,schema:{type:"string",enum:["only","include"],description:"Filter by soft-deleted state. Use `only` to retrieve only deleted records, or `include` to include them alongside active records."},example:"only"},{in:"query",name:"include_deleted",required:!1,schema:{type:"boolean",description:"Whether to include soft-deleted records in the results. Set to `true` to return all records (active and deleted)."},example:!0}]:[]],L=r.schemaGen.generateRootRef(i),I=[];n.length>0&&I.push({[n[0].getExposedName()]:{contains:"keyword"}});let R=d.filter(M=>n.length===0||M!==n[0].getExposedName());R.length>0&&I.push({[R[0]]:{eq:"sample_value"}}),R.length>1&&I.push({or:[{[R[0]]:{eq:"sample_value_1"}},{[R[1]]:{eq:"sample_value_2"}}]});let x={};n.length>0&&(x.q="keyword"),I.length>0&&(x.filter={and:I}),l.length>0&&(x.sort=[{field:l[0],direction:"desc"},...l.length>1?[{field:l[1],direction:"asc"}]:[]]),x.limit=Math.min(25,_),A||(x.page=1);let D={tags:[s.entityNameUpper],operationId:r.registry.register(`search_${Et(s.operationIdKey)}`),summary:`Search ${s.pluralName}`,description:`Retrieves a paginated collection of **${s.entityNameUpper}** records matching advanced AST search criteria.
|
|
159
159
|
|
|
160
160
|
Unlike the standard \`GET\` List endpoint, this endpoint uses a \`POST\` request with a JSON query payload for structured filtering (\`and\`, \`or\`), comparison operators, and full-text substring searching.
|
|
161
161
|
|
|
@@ -163,7 +163,7 @@ Unlike the standard \`GET\` List endpoint, this endpoint uses a \`POST\` request
|
|
|
163
163
|
The \`contains\` operator is permitted exclusively on configured search fields: ${w}. Attempting to use the \`contains\` operator on any other field will result in a \`422 Unprocessable Entity\` to prevent unoptimized table scans.
|
|
164
164
|
|
|
165
165
|
### Gotchas & Common Pitfalls
|
|
166
|
-
`+(
|
|
166
|
+
`+(P?"* **Nested Sub-Resource Scoping:** Results are strictly scoped to the parent resource in the path. If no matching records exist under this parent, the endpoint returns `200 OK` with an empty `data: []` array (never `404`).\n":"")+(A?"* **Pagination Strategy (Cursor):** Uses cursor pagination. Pass `cursor` from `meta.next_cursor` of a previous page. Offset parameters (`page`, `offset`) are rejected with `422 Unprocessable Entity`.\n* **Cursor Invalidation:** Cursors are bound to the exact query filter and sort criteria. Modifying `filter`, `where`, or `sort` invalidates existing cursor tokens.\n":"* **Pagination Strategy (Offset):** Uses offset pagination. Pass `page` (1-based) or `offset` (0-based) along with `limit`. Passing both `page` and `offset`, or passing `cursor`, is rejected with 422.\n")+"* **Sort Restrictions:** Only indexed and explicitly permitted `sortableFields` can be used in the `sort` array. Specifying unindexed or unrecognized sort fields will result in a `422 Unprocessable Entity`.\n"+(E?"* **Soft-Delete Filtering:** Active records are searched by default. Use `?trash=only` to search soft-deleted records, or `?trash=include` (or `?include_deleted=true`) to search both active and soft-deleted records.\n":"")+"* **Data Privacy & Projections:** Sensitive, write-only, and non-projected properties are automatically omitted from returned items. Results are returned in a standard envelope containing the `data` array and `meta` pagination details.",requestBody:{required:!0,content:{"application/json":{schema:{$ref:"#/components/schemas/SearchRequestBody"},example:x}}},responses:{200:{description:`Successfully retrieved a paginated list of **${s.entityNameUpper}** records matching the search criteria.
|
|
167
167
|
|
|
168
168
|
Returns an array of records wrapped in a standard \`data\` envelope. The response also includes a \`meta\` object containing pagination details.`,content:{"application/json":{schema:{type:"object",properties:{data:{type:"array",items:e.projection?r.schemaGen.generateProjectedRef(i,e):L,description:`List of search results for ${s.pluralName}. Can be empty. See the \`meta\` object for pagination details.`},meta:{$ref:"#/components/schemas/PaginationMeta"}},required:["data","meta"]}}}}}};return j.length>0&&(D.parameters=j),r.securityProcessor.applyActionSecurity(e,D,r.model),r.responseEnricher.apply(e,D,{hasBody:!0,isResource:!1,isCreate:!1}),D.responses?.["400"]&&(D.responses[400]={description:"Bad Request. The request body is malformed, unparsable JSON, or contains invalid HTTP request syntax.",summary:"Bad Request",content:{"application/json":{schema:{$ref:"#/components/schemas/Error400BadRequestValidationFailed"}}}}),D.responses?.["422"]&&(D.responses[422]={description:"Unprocessable Entity. The search payload failed validation (e.g., malformed AST structure, unsupported operator for a property type, targeting an un-searchable property with `contains`, specifying un-sortable fields, or incompatible pagination parameters).",summary:"Validation Error",content:{"application/json":{schema:{$ref:"#/components/schemas/Error422UnprocessableEntity"}}}}),{path:a,method:"post",operation:D}}};var za=class{actionKind="restore";process(e,t,i,r,s){let o=t.getAbsoluteCollectionPath();if(!t.hasCollection||!o)return;let a=`${o}/restore`,n=r.pathExtractor.extract(a),l=n.length>0,d=i.primaryKey(),p=d?.type==="number",m=p?{type:"integer",description:"Integer resource identifier."}:d?.type==="string"?{type:"string",minLength:1,description:"String resource identifier."}:{oneOf:[{type:"string",minLength:1,description:"String resource identifier."},{type:"integer",description:"Integer resource identifier."}]},h=p?[101,102]:["rec_9x20a3","rec_8b11c4"],f={tags:[s.entityNameUpper],operationId:r.registry.register(`restore_${s.operationIdKey}`),summary:`Restore ${s.pluralName}`,description:`Restores one or more soft-deleted **${s.entityNameUpper}** records by their IDs.
|
|
169
169
|
|
|
@@ -174,25 +174,25 @@ Clears soft-deletion markers, returning target records to active status.
|
|
|
174
174
|
* **Cascading Child Restoration:** Recursively restores associated child records that were soft-deleted at the exact same deletion timestamp.
|
|
175
175
|
`+(l?"* **Nested Sub-Resource Scoping:** All target records must belong to the parent resource specified in the path; otherwise, the request rolls back with `404 Not Found`.\n":"")+"* **Soft-Delete Prerequisite:** Only applicable to entities configured with the soft-delete strategy. Hard-deleted records cannot be recovered. Calling this endpoint when soft delete is not configured returns `400 Bad Request`.\n* **Response Expectations:** Returns `204 No Content` with an empty body. Clients requiring updated resource state should query the Read or List endpoints after restoration.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{ids:{type:"array",minItems:1,items:m,description:"A non-empty array of resource identifiers to restore.",example:h}},required:["ids"]}}}},responses:{204:{description:`The **${s.entityNameUpper}** records were successfully restored.
|
|
176
176
|
|
|
177
|
-
This endpoint returns a \`204 No Content\` status code upon success, indicating that all specified records (and any cascading child records soft-deleted at the same time) have been restored to active status, with no content in the response payload body.`}}};return n.length>0&&(f.parameters=n),r.securityProcessor.applyActionSecurity(e,f,r.model),r.responseEnricher.apply(e,f,{hasBody:!0,isResource:!0,isCreate:!1}),f.responses?.["400"]&&(f.responses[400]={description:'Bad Request. The request body is malformed, unparsable JSON, missing the "ids" field, contains an empty array, or soft delete is not configured for this entity.',summary:"Bad Request",content:{"application/json":{schema:{$ref:"#/components/schemas/Error400BadRequestValidationFailed"}}}}),f.responses?.["404"]&&(f.responses[404].description="One or more of the specified record IDs was not found, is already active (not soft-deleted), fails authorization, or does not belong to the parent resource scope."),f.responses?.["422"]&&(f.responses[422]={description:"Unprocessable Entity. The request payload failed schema validation (e.g., non-numeric identifiers when integers are expected, or whitespace string values).",summary:"Validation Error",content:{"application/json":{schema:{$ref:"#/components/schemas/Error422UnprocessableEntity"}}}}),{path:a,method:"post",operation:f}}};var Va=class{processors=new Map;constructor(){this.register(new Na),this.register(new Ta),this.register(new ja),this.register(new Ca),this.register(new Da),this.register(new La),this.register(new Ma),this.register(new Ua),this.register(new za)}register(e){this.processors.set(e.actionKind,e)}get(e){return this.processors.get(e)}};var Fa=class{createErrorSchemas(){let e=(t,i,r,s,o)=>{let a={type:{type:"string",format:"uri",description:"A URI reference that identifies the problem type.",example:r},title:{type:"string",description:"A short, human-readable summary of the problem type.",example:s},status:{type:"integer",description:"The HTTP status code generated by the origin server for this occurrence of the problem.",example:i},detail:{type:"string",description:"A human-readable explanation specific to this occurrence of the problem."},instance:{type:"string",format:"uri",description:"A URI reference that identifies the specific occurrence of the problem."}};return t==="ValidationError"&&(a.errors={type:"array",description:"A list of specifically mapped validation rule failures.",items:{type:"object",properties:{field:{type:"string",description:"The property name that failed validation."},message:{type:"string",description:"Description of the validation failure."},pointer:{type:"string",description:"JSON pointer pointing to the invalid property within the request body."},code:{type:"string",description:"Machine-readable rule identifier."}}}}),{title:t,type:"object",description:o,properties:a,required:["type","title","status"]}};return{Error400BadRequestValidationFailed:e("ValidationError",400,"https://docs.apinow.app/errors/validation-failed","Validation Error","Request payload fails schema validation (missing fields, wrong types) or contains invalid query parameters."),Error400BadRequestInvalidFormat:e("InvalidRequestFormatError",400,"https://docs.apinow.app/errors/invalid-request","Invalid Request Format","The request body is not parsable as JSON (when expected), or other malformations."),Error401Unauthorized:e("AuthenticationRequiredError",401,"https://docs.apinow.app/errors/authentication-required","Authentication Required","JWT is missing, malformed, or invalid (e.g., signature mismatch, expired)."),Error403Forbidden:e("AccessDeniedError",403,"https://docs.apinow.app/errors/access-denied","Access Denied","An authenticated user does not have permission to perform the requested operation on the resource based on rules."),Error404NotFound:e("ResourceNotFoundError",404,"https://docs.apinow.app/errors/resource-not-found","Resource Not Found","The requested resource (e.g., specific entity instance via ID) does not exist."),Error409Conflict:e("ResourceConflictError",409,"https://docs.apinow.app/errors/resource-conflict","Resource Conflict","Attempt to create a resource that would violate a uniqueness constraint (e.g., unique email already exists)."),Error412PreconditionFailed:e("PreconditionFailedError",412,"https://docs.apinow.app/errors/precondition-failed","Precondition Failed","The resource's current state did not match the condition specified in an If-Match or If-Unmodified-Since request header, or an invalid wildcard condition was supplied."),Error422UnprocessableEntity:e("ValidationError",422,"https://docs.apinow.app/errors/validation","Validation Error","The request payload failed semantic or schema validation (e.g., missing required fields, invalid data types, or constraint violations)."),Error429TooManyRequests:e("RateLimitExceededError",429,"https://docs.apinow.app/errors/rate-limit-exceeded","Rate Limit Exceeded","API consumer has exceeded configured rate limits."),Error500InternalServerError:e("InternalServerError",500,"https://docs.apinow.app/errors/internal-server-error","Internal Server Error","An unexpected error occurred on the server while processing the request. Details should not expose sensitive info.")}}};var qa=class{createOffsetPaginationMeta(){return{type:"object",description:"Offset pagination metadata.",properties:{per_page:{type:"integer",default:20,minimum:1,maximum:100,description:"Number of items per page",example:10},current_page:{type:"integer",default:1,minimum:1,description:"The current page number",example:1},first_page:{type:"integer",default:1,minimum:1,description:"The first page number. The first page is always 1.",example:1},is_empty:{type:"boolean",description:"Whether the collection is empty.",example:!1},total:{type:"integer",minimum:0,description:"The total number of items",example:100},has_total:{type:"boolean",description:"Whether the total number of items is available. This is not same as `isEmpty`.\n\nThe `isEmpty` reports about the current set of results. However `hasTotal` reports about the total number of records, regardless of the current.",example:!0},last_page:{type:"integer",minimum:1,description:"The last page number.",example:10},has_more_pages:{type:"boolean",description:"Whether there are more pages.",example:!0},has_pages:{type:"boolean",description:"Whether the collection has pages.",example:!0}},required:["per_page","current_page","first_page","is_empty","has_total","has_more_pages","has_pages"]}}createCursorPaginationMeta(){return{type:"object",description:"Cursor pagination metadata.",properties:{next_cursor:{type:"string",description:"The cursor to use for pagination.",title:"Next cursor",example:"eyJ2IjpbInVzcl85eTIwYTMiXSwicyI6W3siZiI6ImlkIiwiZCI6ImFzYyJ9XX0="},has_more:{type:"boolean",description:"Whether there are more pages.",title:"Has more",example:!0}},required:["next_cursor","has_more"]}}generateSearchRequestBody(e){let t=e.kind==="cursor",i=t?{cursor:{type:"string",description:"Pagination cursor retrieved from a previous response meta object."}}:{page:{type:"integer",minimum:1,default:1,description:"Page number for offset pagination."},offset:{type:"integer",minimum:0,default:0,description:"Number of records to skip for offset pagination."}};return{type:"object",properties:{q:{type:"string",description:"Free-text search keyword evaluated across all configured searchable string fields."},filter:{type:"object",description:"The AST query object for structured filtering and boolean logic.",$ref:"#/components/schemas/SearchWhereAST"},where:{type:"object",description:"Alias for `filter`. The AST query object for structured filtering.",$ref:"#/components/schemas/SearchWhereAST"},sort:{type:"array",description:"An array of sorting directives applied in order.",items:{type:"object",properties:{field:{type:"string",description:"The name of the indexable property to sort by."},direction:{type:"string",enum:["asc","desc"],description:"The sort direction (ascending or descending)."}},required:["field","direction"]}},limit:{type:"integer",minimum:t?1:1,maximum:t?e.maxLimit??100:e.maxLimit??100,default:t?e.defaultLimit??20:e.defaultLimit??20},...i}}}};var Ka=class{getAstComponentSchemas(){return{SearchWhereAST:{type:"object",description:"The root query object. Supports nested logical operators and field-level conditions.",$ref:"#/components/schemas/SearchWhereNode"},SearchWhereNode:{type:"object",description:"A node in the AST. Can be a logical operator (AND/OR) or a specific field condition.",oneOf:[{title:"LogicalAndNode",type:"object",properties:{and:{type:"array",items:{$ref:"#/components/schemas/SearchWhereNode"}}},required:["and"],additionalProperties:!1},{title:"LogicalOrNode",type:"object",properties:{or:{type:"array",items:{$ref:"#/components/schemas/SearchWhereNode"}}},required:["or"],additionalProperties:!1},{title:"FieldConditionNode",type:"object",minProperties:1,maxProperties:1,description:"A dynamic key representing the field name, mapped to its operator conditions.",patternProperties:{"^[a-zA-Z0-9_]+$":{$ref:"#/components/schemas/SearchWhereOperatorMap"}},additionalProperties:!1}]},SearchWhereOperatorMap:{type:"object",minProperties:1,maxProperties:1,properties:{eq:{},neq:{},in:{type:"array"},nin:{type:"array"},gt:{type:["number","string"]},gte:{type:["number","string"]},lt:{type:["number","string"]},lte:{type:["number","string"]},contains:{type:"string"},match:{type:"string"},exists:{type:"boolean"}},additionalProperties:!1}}}};var Ba=class{contribute(e,t){if(t.model.authentication?.strategy!=="UsernamePassword")return;let i=t.model.session;if(!i)return;let r=t.model.user?t.domain.findEntity(t.model.user.key):void 0;if(!r)return;let s=r.properties.find(S=>S.semantics.some(E=>E.id===g.Username)),o=r.properties.find(S=>S.semantics.some(E=>E.id===g.Password));if(!s||!o)return;let a=s.getExposedName(),n=o.getExposedName(),l="The username.",d=["alex_carter"],p;s.semantics.some(S=>S.id===g.Email)?(l="The email address.",d=["alex.carter@example.com"],p="email"):s.semantics.some(S=>S.id===g.Phone)&&(l="The phone number.",d=["+15551234567"]);let m={success:{type:"boolean",description:"Indicates if the authentication was successful.",examples:[!0]}};i.jwt?.enabled&&(m.token={type:"string",description:"The JSON Web Token (JWT) representing the active session. Include this in the Authorization header as a Bearer token.",examples:["eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI..."]});let h={};i.cookie?.enabled&&(h["Set-Cookie"]={description:"The secure session cookie containing the authentication state. Managed automatically by the browser.",schema:{type:"string"}}),e["/auth/login"]={post:{tags:["Authentication"],operationId:t.registry.register("auth_login"),summary:"Log in to the application",description:"Authenticates a user via credentials. Returns a JWT token and/or sets a secure HttpOnly session cookie depending on the configured transports.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{[a]:{type:"string",description:l,examples:d,...p?{format:p}:{}},[n]:{type:"string",format:"password",description:"The plain-text password.",examples:["password123"]}},required:[a,n]}}}},responses:{200:{description:"Authentication successful.",headers:h,content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:m,required:["success"]}},required:["data"]}}}},400:{description:"Bad Request. Missing username or password."},401:{description:"Unauthorized. Invalid credentials."}},security:[]}};let f=t.schemaGen.generateRootRef(r),k=t.schemaGen.generateCreateInputRef(r);f&&k&&(e["/auth/register"]={post:{tags:["Authentication"],operationId:t.registry.register("auth_register"),summary:"Register a new user account",description:"Creates a new user record in the system using the provided payload. The fields match the user entity validation schema.",requestBody:{required:!0,content:{"application/json":{schema:k}}},responses:{201:{description:"User registered successfully. Returns the created user record.",content:{"application/json":{schema:{type:"object",properties:{data:f},required:["data"]}}}},400:{description:"Bad Request. Validation failed."},409:{description:"Conflict. The unique identifier (e.g. email) already exists."}},security:[]}});let w={};i.cookie?.enabled&&(w["Set-Cookie"]={description:"Sets the session cookie to expire immediately, clearing it from the browser.",schema:{type:"string"}}),e["/auth/logout"]={post:{tags:["Authentication"],operationId:t.registry.register("auth_logout"),summary:"Log out of the application",description:"Terminates the active session. If cookie transport is used, clears the session cookie in the browser.",responses:{200:{description:"Logout successful.",headers:w,content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{success:{type:"boolean",examples:[!0]}},required:["success"]}},required:["data"]}}}}}}}}};var Ga=class{contribute(e,t){let i=t.domain.listEntities(),r=!1,s=!1;for(let d of i)if(Array.from(t.model.exposes.values()).some(m=>m.entity.key===d.key))for(let m of d.withInheritedProperties()){let h=m.semantics.find(k=>k.id===g.Email);h&&((h.config||{}).requireVerification??!0)&&(r=!0);let f=m.semantics.find(k=>k.id===g.Phone);f&&((f.config||{}).requireVerification??!1)&&(s=!0)}let o=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_email"),summary:"Verify an email address",description:"Verifies an email address using a verification token received via email.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The high-entropy verification token received via email.",examples:["4f9a1b8c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a"]}},required:["token"]}}}},responses:{200:{description:"Verification successful.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["Email verified successfully."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Missing fields, invalid token, or expired token."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}}),a=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_email_resend"),summary:"Resend email verification token",description:"Resends an email verification link with a new token to the provided email address. Returns 200 OK regardless of whether a matching unverified account exists to prevent account enumeration.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",format:"email",description:"The email address to resend verification to.",examples:["user@example.com"]}},required:["email"]}}}},responses:{200:{description:"Verification request processed. Returns a generic message to prevent account enumeration.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["If an unverified account matches, a new verification message has been sent."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Missing fields or invalid email."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}}),n=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_phone"),summary:"Verify a phone number",description:"Verifies a phone number using a 6-digit numeric SMS OTP code.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{phone:{type:"string",description:"The E.164 formatted phone number to verify.",examples:["+15551234567"]},code:{type:"string",pattern:"^[0-9]{6}$",description:"The 6-digit numeric SMS OTP code.",examples:["481923"]}},required:["phone","code"]}}}},responses:{200:{description:"Verification successful.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["Phone verified successfully."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Invalid or expired code, or maximum attempts exceeded."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}}),l=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_phone_resend"),summary:"Resend phone verification code",description:"Resends a phone verification SMS OTP code to the provided phone number. Returns 200 OK regardless of whether a matching unverified account exists to prevent account enumeration.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{phone:{type:"string",description:"The E.164 formatted phone number to resend verification to.",examples:["+15551234567"]}},required:["phone"]}}}},responses:{200:{description:"Verification request processed. Returns a generic message to prevent account enumeration.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["If an unverified account matches, a new verification message has been sent."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Missing fields or invalid phone number."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}});r&&(e["/verify-email"]=o(),e["/verify-email/resend"]=a()),s&&(e["/verify-phone"]=n(),e["/verify-phone/resend"]=l())}};var Ja=class{getTags(e){return e.schemaGen.hasFileUpload?[{name:"File Upload",description:"To maintain a strict `application/json` data exchange contract for standard API entity actions, this API utilizes a decoupled upload architecture for handling binary data.\n\n### The File Upload Workflow\n1. **Upload Request:** The API Consumer requests an upload URL from the `POST /.well-known/upload` endpoint, specifying the filename and content type.\n2. **Upload:** The API Consumer uploads the physical file using a PUT request to the returned `upload_url`.\n3. **Attach:** The API Consumer passes the returned temporary `file_reference` string as a standard JSON value when calling the `POST` (Create) or `PUT/PATCH` (Update) action for the actual entity."}]:[]}contribute(e,t){t.schemaGen.hasFileUpload&&(e["/.well-known/upload"]={post:{tags:["File Upload"],operationId:t.registry.register("file_upload_request"),summary:"Request a file upload URL",description:"Generates file upload metadata and returns either a signed URL (for cloud storage like GCS) or a local fallback upload URL pointing back to this controller (for local development/testing).\n\nAfter obtaining the `upload_url`, perform a PUT request to upload the file to that URL. The returned `file_reference` token should be passed into the entity Create or Update action payload.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{filename:{type:"string",description:"The name of the file being uploaded (e.g. image.png).",example:"image.png"},contentType:{type:"string",description:"The MIME type of the file (e.g. image/png).",example:"image/png"}},required:["filename","contentType"]}}}},responses:{200:{description:"Upload request processed successfully. Returns the temporary token and upload URL wrapped in a standard `data` envelope.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{file_reference:{type:"string",description:"Temporary upload token. Save this string into the entity Create or Update payload.",example:"file-ref-abc-123"},upload_url:{type:"string",format:"uri",description:"The URL where you should PUT the binary file payload.",example:"https://storage.googleapis.com/..."}},required:["file_reference","upload_url"]}},required:["data"]}}}},400:{description:"Bad Request. Missing filename or contentType."},404:{description:"Not Found. File upload is not supported on this API."}}}})}};var Wa=class{contribute(e,t){for(let i of t.model.exposes.values()){let r=t.domain.findEntity(i.entity.key);r&&this.contributeEntity(e,i,r,t)}}contributeEntity(e,t,i,r){let s=t.getAbsoluteCollectionPath();if(!s)return;let o=i.info.getLabel(),a=vr(o),n=r.schemaGen.generateRootRef(i),l=r.resolveOperationIdKey(t,i);for(let d of i.properties){let p=d.getSemantic(g.GeospatialCoordinates);if(p){let m=p.config??gr,h=m.apiEndpointPrefix||"/nearby",f=d.info.name||d.key,k=t.actions.find(A=>A.kind==="list"),w=k??t.actions[0],S=k?.projection?r.schemaGen.generateProjectedRef(i,k):n,E=(A,_,O,I=!1,j,L=!1)=>(A.tags=[a],A.summary=_,A.description=O,w&&(r.securityProcessor.applyActionSecurity(w,A,r.model),r.responseEnricher.apply(w,A,{hasBody:I,isResource:!1,isCreate:!1})),j&&A.responses?.["400"]&&(A.responses[400].description=j),L&&A.responses&&(A.responses[404]={description:"The parent resource was not found.",summary:"Not Found",content:{"application/json":{schema:{$ref:"#/components/schemas/Error404NotFound"}}}}),A);if(m.enableDistanceQueries){let A=`${s}${h}`,_=e[A]||{};e[A]=_;let O=r.pathExtractor.extract(A),I=[...O,{in:"query",name:"lat",required:!0,schema:{type:"number",description:"Latitude of the center point (-90 to 90)"}},{in:"query",name:"lon",required:!0,schema:{type:"number",description:"Longitude of the center point (-180 to 180)"}},{in:"query",name:"distance",required:!0,schema:{type:"number",description:"Radius distance for the proximity search"}},{in:"query",name:"unit",required:!1,schema:{type:"string",enum:["meters","kilometers","miles","feet","yards","nautical_miles"],default:m.defaultDistanceUnit||"meters",description:"Distance unit"}}],j=m.maxQueryDistance?` (maximum allowed: ${m.maxQueryDistance} ${m.defaultDistanceUnit||"meters"})`:"";_.get=E({operationId:r.registry.register(`nearby_${l}_${f}`),parameters:I,responses:{200:{description:`List of **${o}** records near the coordinates wrapped in a standard \`data\` envelope.
|
|
177
|
+
This endpoint returns a \`204 No Content\` status code upon success, indicating that all specified records (and any cascading child records soft-deleted at the same time) have been restored to active status, with no content in the response payload body.`}}};return n.length>0&&(f.parameters=n),r.securityProcessor.applyActionSecurity(e,f,r.model),r.responseEnricher.apply(e,f,{hasBody:!0,isResource:!0,isCreate:!1}),f.responses?.["400"]&&(f.responses[400]={description:'Bad Request. The request body is malformed, unparsable JSON, missing the "ids" field, contains an empty array, or soft delete is not configured for this entity.',summary:"Bad Request",content:{"application/json":{schema:{$ref:"#/components/schemas/Error400BadRequestValidationFailed"}}}}),f.responses?.["404"]&&(f.responses[404].description="One or more of the specified record IDs was not found, is already active (not soft-deleted), fails authorization, or does not belong to the parent resource scope."),f.responses?.["422"]&&(f.responses[422]={description:"Unprocessable Entity. The request payload failed schema validation (e.g., non-numeric identifiers when integers are expected, or whitespace string values).",summary:"Validation Error",content:{"application/json":{schema:{$ref:"#/components/schemas/Error422UnprocessableEntity"}}}}),{path:a,method:"post",operation:f}}};var Va=class{processors=new Map;constructor(){this.register(new Na),this.register(new Ta),this.register(new ja),this.register(new Ca),this.register(new Da),this.register(new La),this.register(new Ma),this.register(new Ua),this.register(new za)}register(e){this.processors.set(e.actionKind,e)}get(e){return this.processors.get(e)}};var Fa=class{createErrorSchemas(){let e=(t,i,r,s,o)=>{let a={type:{type:"string",format:"uri",description:"A URI reference that identifies the problem type.",example:r},title:{type:"string",description:"A short, human-readable summary of the problem type.",example:s},status:{type:"integer",description:"The HTTP status code generated by the origin server for this occurrence of the problem.",example:i},detail:{type:"string",description:"A human-readable explanation specific to this occurrence of the problem."},instance:{type:"string",format:"uri",description:"A URI reference that identifies the specific occurrence of the problem."}};return t==="ValidationError"&&(a.errors={type:"array",description:"A list of specifically mapped validation rule failures.",items:{type:"object",properties:{field:{type:"string",description:"The property name that failed validation."},message:{type:"string",description:"Description of the validation failure."},pointer:{type:"string",description:"JSON pointer pointing to the invalid property within the request body."},code:{type:"string",description:"Machine-readable rule identifier."}}}}),{title:t,type:"object",description:o,properties:a,required:["type","title","status"]}};return{Error400BadRequestValidationFailed:e("ValidationError",400,"https://docs.apinow.app/errors/validation-failed","Validation Error","Request payload fails schema validation (missing fields, wrong types) or contains invalid query parameters."),Error400BadRequestInvalidFormat:e("InvalidRequestFormatError",400,"https://docs.apinow.app/errors/invalid-request","Invalid Request Format","The request body is not parsable as JSON (when expected), or other malformations."),Error401Unauthorized:e("AuthenticationRequiredError",401,"https://docs.apinow.app/errors/authentication-required","Authentication Required","JWT is missing, malformed, or invalid (e.g., signature mismatch, expired)."),Error403Forbidden:e("AccessDeniedError",403,"https://docs.apinow.app/errors/access-denied","Access Denied","An authenticated user does not have permission to perform the requested operation on the resource based on rules."),Error404NotFound:e("ResourceNotFoundError",404,"https://docs.apinow.app/errors/resource-not-found","Resource Not Found","The requested resource (e.g., specific entity instance via ID) does not exist."),Error409Conflict:e("ResourceConflictError",409,"https://docs.apinow.app/errors/resource-conflict","Resource Conflict","Attempt to create a resource that would violate a uniqueness constraint (e.g., unique email already exists)."),Error412PreconditionFailed:e("PreconditionFailedError",412,"https://docs.apinow.app/errors/precondition-failed","Precondition Failed","The resource's current state did not match the condition specified in an If-Match or If-Unmodified-Since request header, or an invalid wildcard condition was supplied."),Error422UnprocessableEntity:e("ValidationError",422,"https://docs.apinow.app/errors/validation","Validation Error","The request payload failed semantic or schema validation (e.g., missing required fields, invalid data types, or constraint violations)."),Error429TooManyRequests:e("RateLimitExceededError",429,"https://docs.apinow.app/errors/rate-limit-exceeded","Rate Limit Exceeded","API consumer has exceeded configured rate limits."),Error500InternalServerError:e("InternalServerError",500,"https://docs.apinow.app/errors/internal-server-error","Internal Server Error","An unexpected error occurred on the server while processing the request. Details should not expose sensitive info.")}}};var qa=class{createOffsetPaginationMeta(){return{type:"object",description:"Offset pagination metadata.",properties:{per_page:{type:"integer",default:20,minimum:1,maximum:100,description:"Number of items per page",example:10},current_page:{type:"integer",default:1,minimum:1,description:"The current page number",example:1},first_page:{type:"integer",default:1,minimum:1,description:"The first page number. The first page is always 1.",example:1},is_empty:{type:"boolean",description:"Whether the collection is empty.",example:!1},total:{type:"integer",minimum:0,description:"The total number of items",example:100},has_total:{type:"boolean",description:"Whether the total number of items is available. This is not same as `isEmpty`.\n\nThe `isEmpty` reports about the current set of results. However `hasTotal` reports about the total number of records, regardless of the current.",example:!0},last_page:{type:"integer",minimum:1,description:"The last page number.",example:10},has_more_pages:{type:"boolean",description:"Whether there are more pages.",example:!0},has_pages:{type:"boolean",description:"Whether the collection has pages.",example:!0}},required:["per_page","current_page","first_page","is_empty","has_total","has_more_pages","has_pages"]}}createCursorPaginationMeta(){return{type:"object",description:"Cursor pagination metadata.",properties:{next_cursor:{type:"string",description:"The cursor to use for pagination.",title:"Next cursor",example:"eyJ2IjpbInVzcl85eTIwYTMiXSwicyI6W3siZiI6ImlkIiwiZCI6ImFzYyJ9XX0="},has_more:{type:"boolean",description:"Whether there are more pages.",title:"Has more",example:!0}},required:["next_cursor","has_more"]}}generateSearchRequestBody(e){let t=e.kind==="cursor",i=t?{cursor:{type:"string",description:"Pagination cursor retrieved from a previous response meta object."}}:{page:{type:"integer",minimum:1,default:1,description:"Page number for offset pagination."},offset:{type:"integer",minimum:0,default:0,description:"Number of records to skip for offset pagination."}};return{type:"object",properties:{q:{type:"string",description:"Free-text search keyword evaluated across all configured searchable string fields."},filter:{type:"object",description:"The AST query object for structured filtering and boolean logic.",$ref:"#/components/schemas/SearchWhereAST"},where:{type:"object",description:"Alias for `filter`. The AST query object for structured filtering.",$ref:"#/components/schemas/SearchWhereAST"},sort:{type:"array",description:"An array of sorting directives applied in order.",items:{type:"object",properties:{field:{type:"string",description:"The name of the indexable property to sort by."},direction:{type:"string",enum:["asc","desc"],description:"The sort direction (ascending or descending)."}},required:["field","direction"]}},limit:{type:"integer",minimum:t?1:1,maximum:t?e.maxLimit??100:e.maxLimit??100,default:t?e.defaultLimit??20:e.defaultLimit??20},...i}}}};var Ka=class{getAstComponentSchemas(){return{SearchWhereAST:{type:"object",description:"The root query object. Supports nested logical operators and field-level conditions.",$ref:"#/components/schemas/SearchWhereNode"},SearchWhereNode:{type:"object",description:"A node in the AST. Can be a logical operator (AND/OR) or a specific field condition.",oneOf:[{title:"LogicalAndNode",type:"object",properties:{and:{type:"array",items:{$ref:"#/components/schemas/SearchWhereNode"}}},required:["and"],additionalProperties:!1},{title:"LogicalOrNode",type:"object",properties:{or:{type:"array",items:{$ref:"#/components/schemas/SearchWhereNode"}}},required:["or"],additionalProperties:!1},{title:"FieldConditionNode",type:"object",minProperties:1,maxProperties:1,description:"A dynamic key representing the field name, mapped to its operator conditions.",patternProperties:{"^[a-zA-Z0-9_]+$":{$ref:"#/components/schemas/SearchWhereOperatorMap"}},additionalProperties:!1}]},SearchWhereOperatorMap:{type:"object",minProperties:1,maxProperties:1,properties:{eq:{},neq:{},in:{type:"array"},nin:{type:"array"},gt:{type:["number","string"]},gte:{type:["number","string"]},lt:{type:["number","string"]},lte:{type:["number","string"]},contains:{type:"string"},match:{type:"string"},exists:{type:"boolean"}},additionalProperties:!1}}}};var Ba=class{contribute(e,t){if(t.model.authentication?.strategy!=="UsernamePassword")return;let i=t.model.session;if(!i)return;let r=t.model.user?t.domain.findEntity(t.model.user.key):void 0;if(!r)return;let s=r.properties.find(S=>S.semantics.some(E=>E.id===g.Username)),o=r.properties.find(S=>S.semantics.some(E=>E.id===g.Password));if(!s||!o)return;let a=s.getExposedName(),n=o.getExposedName(),l="The username.",d=["alex_carter"],p;s.semantics.some(S=>S.id===g.Email)?(l="The email address.",d=["alex.carter@example.com"],p="email"):s.semantics.some(S=>S.id===g.Phone)&&(l="The phone number.",d=["+15551234567"]);let m={success:{type:"boolean",description:"Indicates if the authentication was successful.",examples:[!0]}};i.jwt?.enabled&&(m.token={type:"string",description:"The JSON Web Token (JWT) representing the active session. Include this in the Authorization header as a Bearer token.",examples:["eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI..."]});let h={};i.cookie?.enabled&&(h["Set-Cookie"]={description:"The secure session cookie containing the authentication state. Managed automatically by the browser.",schema:{type:"string"}}),e["/auth/login"]={post:{tags:["Authentication"],operationId:t.registry.register("auth_login"),summary:"Log in to the application",description:"Authenticates a user via credentials. Returns a JWT token and/or sets a secure HttpOnly session cookie depending on the configured transports.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{[a]:{type:"string",description:l,examples:d,...p?{format:p}:{}},[n]:{type:"string",format:"password",description:"The plain-text password.",examples:["password123"]}},required:[a,n]}}}},responses:{200:{description:"Authentication successful.",headers:h,content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:m,required:["success"]}},required:["data"]}}}},400:{description:"Bad Request. Missing username or password."},401:{description:"Unauthorized. Invalid credentials."}},security:[]}};let f=t.schemaGen.generateRootRef(r),k=t.schemaGen.generateCreateInputRef(r);f&&k&&(e["/auth/register"]={post:{tags:["Authentication"],operationId:t.registry.register("auth_register"),summary:"Register a new user account",description:"Creates a new user record in the system using the provided payload. The fields match the user entity validation schema.",requestBody:{required:!0,content:{"application/json":{schema:k}}},responses:{201:{description:"User registered successfully. Returns the created user record.",content:{"application/json":{schema:{type:"object",properties:{data:f},required:["data"]}}}},400:{description:"Bad Request. Validation failed."},409:{description:"Conflict. The unique identifier (e.g. email) already exists."}},security:[]}});let w={};i.cookie?.enabled&&(w["Set-Cookie"]={description:"Sets the session cookie to expire immediately, clearing it from the browser.",schema:{type:"string"}}),e["/auth/logout"]={post:{tags:["Authentication"],operationId:t.registry.register("auth_logout"),summary:"Log out of the application",description:"Terminates the active session. If cookie transport is used, clears the session cookie in the browser.",responses:{200:{description:"Logout successful.",headers:w,content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{success:{type:"boolean",examples:[!0]}},required:["success"]}},required:["data"]}}}}}}}}};var Ga=class{contribute(e,t){let i=t.domain.listEntities(),r=!1,s=!1;for(let d of i)if(Array.from(t.model.exposes.values()).some(m=>m.entity.key===d.key))for(let m of d.withInheritedProperties()){let h=m.semantics.find(k=>k.id===g.Email);h&&((h.config||{}).requireVerification??!0)&&(r=!0);let f=m.semantics.find(k=>k.id===g.Phone);f&&((f.config||{}).requireVerification??!1)&&(s=!0)}let o=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_email"),summary:"Verify an email address",description:"Verifies an email address using a verification token received via email.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{token:{type:"string",description:"The high-entropy verification token received via email.",examples:["4f9a1b8c2d3e4f5a6b7c8d9e0f1a2b3c4d5e6f7a8b9c0d1e2f3a4b5c6d7e8f9a"]}},required:["token"]}}}},responses:{200:{description:"Verification successful.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["Email verified successfully."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Missing fields, invalid token, or expired token."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}}),a=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_email_resend"),summary:"Resend email verification token",description:"Resends an email verification link with a new token to the provided email address. Returns 200 OK regardless of whether a matching unverified account exists to prevent account enumeration.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{email:{type:"string",format:"email",description:"The email address to resend verification to.",examples:["user@example.com"]}},required:["email"]}}}},responses:{200:{description:"Verification request processed. Returns a generic message to prevent account enumeration.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["If an unverified account matches, a new verification message has been sent."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Missing fields or invalid email."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}}),n=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_phone"),summary:"Verify a phone number",description:"Verifies a phone number using a 6-digit numeric SMS OTP code.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{phone:{type:"string",description:"The E.164 formatted phone number to verify.",examples:["+15551234567"]},code:{type:"string",pattern:"^[0-9]{6}$",description:"The 6-digit numeric SMS OTP code.",examples:["481923"]}},required:["phone","code"]}}}},responses:{200:{description:"Verification successful.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["Phone verified successfully."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Invalid or expired code, or maximum attempts exceeded."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}}),l=()=>({post:{tags:["Verification"],operationId:t.registry.register("verify_phone_resend"),summary:"Resend phone verification code",description:"Resends a phone verification SMS OTP code to the provided phone number. Returns 200 OK regardless of whether a matching unverified account exists to prevent account enumeration.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{phone:{type:"string",description:"The E.164 formatted phone number to resend verification to.",examples:["+15551234567"]}},required:["phone"]}}}},responses:{200:{description:"Verification request processed. Returns a generic message to prevent account enumeration.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{message:{type:"string",examples:["If an unverified account matches, a new verification message has been sent."]}},required:["message"]}},required:["data"]}}}},400:{description:"Bad Request. Missing fields or invalid phone number."},429:{description:"Too Many Requests. Rate limit exceeded on verification attempts."}},security:[]}});r&&(e["/verify-email"]=o(),e["/verify-email/resend"]=a()),s&&(e["/verify-phone"]=n(),e["/verify-phone/resend"]=l())}};var Ja=class{getTags(e){return e.schemaGen.hasFileUpload?[{name:"File Upload",description:"To maintain a strict `application/json` data exchange contract for standard API entity actions, this API utilizes a decoupled upload architecture for handling binary data.\n\n### The File Upload Workflow\n1. **Upload Request:** The API Consumer requests an upload URL from the `POST /.well-known/upload` endpoint, specifying the filename and content type.\n2. **Upload:** The API Consumer uploads the physical file using a PUT request to the returned `upload_url`.\n3. **Attach:** The API Consumer passes the returned temporary `file_reference` string as a standard JSON value when calling the `POST` (Create) or `PUT/PATCH` (Update) action for the actual entity."}]:[]}contribute(e,t){t.schemaGen.hasFileUpload&&(e["/.well-known/upload"]={post:{tags:["File Upload"],operationId:t.registry.register("file_upload_request"),summary:"Request a file upload URL",description:"Generates file upload metadata and returns either a signed URL (for cloud storage like GCS) or a local fallback upload URL pointing back to this controller (for local development/testing).\n\nAfter obtaining the `upload_url`, perform a PUT request to upload the file to that URL. The returned `file_reference` token should be passed into the entity Create or Update action payload.",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{filename:{type:"string",description:"The name of the file being uploaded (e.g. image.png).",example:"image.png"},contentType:{type:"string",description:"The MIME type of the file (e.g. image/png).",example:"image/png"}},required:["filename","contentType"]}}}},responses:{200:{description:"Upload request processed successfully. Returns the temporary token and upload URL wrapped in a standard `data` envelope.",content:{"application/json":{schema:{type:"object",properties:{data:{type:"object",properties:{file_reference:{type:"string",description:"Temporary upload token. Save this string into the entity Create or Update payload.",example:"file-ref-abc-123"},upload_url:{type:"string",format:"uri",description:"The URL where you should PUT the binary file payload.",example:"https://storage.googleapis.com/..."}},required:["file_reference","upload_url"]}},required:["data"]}}}},400:{description:"Bad Request. Missing filename or contentType."},404:{description:"Not Found. File upload is not supported on this API."}}}})}};var Wa=class{contribute(e,t){for(let i of t.model.exposes.values()){let r=t.domain.findEntity(i.entity.key);r&&this.contributeEntity(e,i,r,t)}}contributeEntity(e,t,i,r){let s=t.getAbsoluteCollectionPath();if(!s)return;let o=i.info.getLabel(),a=vr(o),n=r.schemaGen.generateRootRef(i),l=r.resolveOperationIdKey(t,i);for(let d of i.properties){let p=d.getSemantic(g.GeospatialCoordinates);if(p){let m=p.config??gr,h=m.apiEndpointPrefix||"/nearby",f=d.info.name||d.key,k=t.actions.find(A=>A.kind==="list"),w=k??t.actions[0],S=k?.projection?r.schemaGen.generateProjectedRef(i,k):n,E=(A,_,$,P=!1,j,L=!1)=>(A.tags=[a],A.summary=_,A.description=$,w&&(r.securityProcessor.applyActionSecurity(w,A,r.model),r.responseEnricher.apply(w,A,{hasBody:P,isResource:!1,isCreate:!1})),j&&A.responses?.["400"]&&(A.responses[400].description=j),L&&A.responses&&(A.responses[404]={description:"The parent resource was not found.",summary:"Not Found",content:{"application/json":{schema:{$ref:"#/components/schemas/Error404NotFound"}}}}),A);if(m.enableDistanceQueries){let A=`${s}${h}`,_=e[A]||{};e[A]=_;let $=r.pathExtractor.extract(A),P=[...$,{in:"query",name:"lat",required:!0,schema:{type:"number",description:"Latitude of the center point (-90 to 90)"}},{in:"query",name:"lon",required:!0,schema:{type:"number",description:"Longitude of the center point (-180 to 180)"}},{in:"query",name:"distance",required:!0,schema:{type:"number",description:"Radius distance for the proximity search"}},{in:"query",name:"unit",required:!1,schema:{type:"string",enum:["meters","kilometers","miles","feet","yards","nautical_miles"],default:m.defaultDistanceUnit||"meters",description:"Distance unit"}}],j=m.maxQueryDistance?` (maximum allowed: ${m.maxQueryDistance} ${m.defaultDistanceUnit||"meters"})`:"";_.get=E({operationId:r.registry.register(`nearby_${l}_${f}`),parameters:P,responses:{200:{description:`List of **${o}** records near the coordinates wrapped in a standard \`data\` envelope.
|
|
178
178
|
|
|
179
179
|
Results are sorted in ascending order of geographic distance from the specified center point.`,content:{"application/json":{schema:{type:"object",properties:{data:{type:"array",items:S}},required:["data"]}}}}}},`Find ${o}s near coordinates`,`Returns a list of **${o}** records sorted by distance from the specified coordinates.
|
|
180
180
|
|
|
181
181
|
Performs a radial proximity query using PostGIS \`ST_DWithin\` and orders records by distance (\`ST_Distance ASC\`). Coordinates must be provided via \`lat\` and \`lon\` query parameters (or the composite \`point=lat,lon\` shorthand). The search radius is specified by \`distance\` in the chosen \`unit\` (defaults to \`${m.defaultDistanceUnit||"meters"}\`)${j}.
|
|
182
182
|
|
|
183
|
-
Active records only are returned; soft-deleted records are automatically excluded. Results are returned wrapped in a standard \`data\` envelope.`,!1,"Bad Request. Invalid or missing coordinates (lat/lon), invalid distance parameter, or requested distance exceeds the maximum allowed radius."
|
|
183
|
+
Active records only are returned; soft-deleted records are automatically excluded. Results are returned wrapped in a standard \`data\` envelope.`,!1,"Bad Request. Invalid or missing coordinates (lat/lon), invalid distance parameter, or requested distance exceeds the maximum allowed radius.",$.length>0)}if(m.enableBoundingBoxQueries){let A=`${s}${h}/bbox`,_=e[A]||{};e[A]=_;let $=r.pathExtractor.extract(A),P=[...$,{in:"query",name:"minLat",required:!0,schema:{type:"number",description:"Minimum Latitude of bounding box"}},{in:"query",name:"minLon",required:!0,schema:{type:"number",description:"Minimum Longitude of bounding box"}},{in:"query",name:"maxLat",required:!0,schema:{type:"number",description:"Maximum Latitude of bounding box"}},{in:"query",name:"maxLon",required:!0,schema:{type:"number",description:"Maximum Longitude of bounding box"}}];_.get=E({operationId:r.registry.register(`bbox_${l}_${f}`),parameters:P,responses:{200:{description:`List of **${o}** records within the bounding box wrapped in a standard \`data\` envelope.`,content:{"application/json":{schema:{type:"object",properties:{data:{type:"array",items:S}},required:["data"]}}}}}},`Find ${o}s within Bounding Box`,`Returns a list of **${o}** records that fall within the rectangular map viewport specified by min/max latitude/longitude coordinates.
|
|
184
184
|
|
|
185
185
|
Performs a spatial containment query using PostGIS \`ST_Within\` and \`ST_MakeEnvelope\`. Requires \`minLat\`, \`minLon\`, \`maxLat\`, and \`maxLon\` query parameters defining the geographic bounding box.
|
|
186
186
|
|
|
187
|
-
Active records only are returned; soft-deleted records are automatically excluded. Results are returned wrapped in a standard \`data\` envelope.`,!1,"Bad Request. Invalid or missing bounding box parameters (minLat, minLon, maxLat, maxLon)."
|
|
187
|
+
Active records only are returned; soft-deleted records are automatically excluded. Results are returned wrapped in a standard \`data\` envelope.`,!1,"Bad Request. Invalid or missing bounding box parameters (minLat, minLon, maxLat, maxLon).",$.length>0)}if(m.enablePolygonQueries===!0){let A=`${s}${h}/polygon`,_=e[A]||{};e[A]=_;let $=r.pathExtractor.extract(A),P={operationId:r.registry.register(`polygon_${l}_${f}`),requestBody:{required:!0,content:{"application/json":{schema:{type:"object",properties:{polygon:{oneOf:[{type:"string",description:"WKT representation (e.g. POLYGON((...)))"},{type:"object",description:"GeoJSON Polygon representation"}]}},required:["polygon"]}}}},responses:{200:{description:`List of **${o}** records intersecting with the polygon wrapped in a standard \`data\` envelope.`,content:{"application/json":{schema:{type:"object",properties:{data:{type:"array",items:S}},required:["data"]}}}}}};$.length>0&&(P.parameters=$),_.post=E(P,`Find ${o}s intersecting custom Polygon`,`Returns a list of **${o}** records whose coordinates intersect with the custom user-defined GeoJSON or WKT polygon.
|
|
188
188
|
|
|
189
189
|
Performs a spatial intersection query using PostGIS \`ST_Intersects\`. Accepts either a Well-Known Text (WKT) string (e.g. \`POLYGON((...))\`) or a standard GeoJSON Polygon object in the \`polygon\` request body field.
|
|
190
190
|
|
|
191
|
-
Active records only are returned; soft-deleted records are automatically excluded. Results are returned wrapped in a standard \`data\` envelope.`,!0,"Bad Request. Missing or invalid polygon payload (must be a valid WKT string or GeoJSON Polygon object)."
|
|
191
|
+
Active records only are returned; soft-deleted records are automatically excluded. Results are returned wrapped in a standard \`data\` envelope.`,!0,"Bad Request. Missing or invalid polygon payload (must be a valid WKT string or GeoJSON Polygon object).",$.length>0)}if(m.enableGeoClustering===!0){let A=`${s}${h}/cluster`,_=e[A]||{};e[A]=_;let $=r.pathExtractor.extract(A),P=[...$,{in:"query",name:"minLat",required:!0,schema:{type:"number",description:"Minimum Latitude of bounding box"}},{in:"query",name:"minLon",required:!0,schema:{type:"number",description:"Minimum Longitude of bounding box"}},{in:"query",name:"maxLat",required:!0,schema:{type:"number",description:"Maximum Latitude of bounding box"}},{in:"query",name:"maxLon",required:!0,schema:{type:"number",description:"Maximum Longitude of bounding box"}},{in:"query",name:"precision",required:!1,schema:{type:"integer",description:"Geohash precision level (1-12)"}},{in:"query",name:"zoom",required:!1,schema:{type:"integer",description:"Map zoom level"}}];_.get=E({operationId:r.registry.register(`cluster_${l}_${f}`),parameters:P,responses:{200:{description:`Geo-clustered point centroids and counts of **${o}** records wrapped in a standard \`data\` envelope.`,content:{"application/json":{schema:this.createGeoClusterSchema()}}}}},`Get geo-clustered ${o}s`,`Aggregates spatial coordinate points of **${o}** into clustered markers for optimized map rendering.
|
|
192
192
|
|
|
193
193
|
Performs spatial aggregation using PostGIS \`ST_GeoHash\` and \`COUNT(*)\` to group points into centroid Clustering resolution can be controlled via an explicit geohash \`precision\` (1-12) or map \`zoom\` level (1-18), which automatically maps to appropriate precision levels (1-9).
|
|
194
194
|
|
|
195
|
-
Active records only are clustered; soft-deleted records are automatically excluded. Returns an array of point centroids with their associated \`point_count\` wrapped in a standard \`data\` envelope.`,!1,"Bad Request. Invalid or missing bounding box parameters (minLat, minLon, maxLat, maxLon) or invalid precision level.",O.length>0)}}}}createGeoClusterSchema(){return{type:"object",properties:{data:{type:"array",items:{type:"object",properties:{type:{type:"string",example:"Point"},coordinates:{type:"array",items:{type:"number"},example:[-74.006,40.7128]},point_count:{type:"integer",example:5}},required:["type","coordinates"]}}},required:["data"]}}};var Ha=class{model;#e=!1;get hasListAction(){return this.#e}#t=!1;get hasSearchAction(){return this.#t}processorRegistry=new Va;authContributor=new Ba;verificationContributor=new Ga;fileUploadContributor=new Ja;geospatialContributor=new Wa;errorSchemaFactory=new Fa;paginationSchemaFactory=new qa;searchAstSchemaFactory=new Ka;constructor(e){this.model=e}generateInfo(){let e={title:this.model.info.displayName||this.model.info.name||"API",version:this.model.info.version||"1.0.0"};return this.model.info.description&&(e.description=this.model.info.description),this.model.termsOfService&&(e.termsOfService=this.model.termsOfService),this.model.contact&&(e.contact={...this.model.contact}),this.model.license&&(e.license={...this.model.license}),e}generate(e){let{domain:t}=this.model;if(!t)throw new Error("Data domain is required for OAS generation");let i=new Oa(this.model,t,e);i.preRegisterReadOperations();let r={};this.authContributor.contribute(r,i),this.verificationContributor.contribute(r,i),this.fileUploadContributor.contribute(r,i);for(let p of this.model.exposes.values()){let m=t.findEntity(p.entity.key);if(!m||!i.schemaGen.generateRootRef(m))continue;let f=i.linkResolver.resolveEntityLinks(m,i),k=Object.keys(f).length>0,w=i.resolveOperationIdKey(p,m),S=m.info.getLabel(),E=vr(S),A=Et(E),_={links:f,hasLinks:k,operationIdKey:w,entityName:S,entityNameUpper:E,pluralName:A};for(let O of p.actions){let I=this.processorRegistry.get(O.kind);if(!I)continue;let j=I.process(O,p,m,i,_);if(j){let L=Array.isArray(j)?j:[j];for(let P of L)r[P.path]=r[P.path]||{},r[P.path][P.method]=P.operation}}this.geospatialContributor.contributeEntity(r,p,m,i)}this.#e=i.hasListAction,this.#t=i.hasSearchAction;let s=i.schemaGen.getSchemas();Object.assign(s,this.errorSchemaFactory.createErrorSchemas());let o=i.securityRequirementsResolver.generateSecuritySchemes(this.model),a={};if(i.whereAstInjected&&Object.assign(s,this.searchAstSchemaFactory.getAstComponentSchemas()),this.hasListAction||this.hasSearchAction){let p=this.model.pagination.kind==="cursor"?this.paginationSchemaFactory.createCursorPaginationMeta():this.paginationSchemaFactory.createOffsetPaginationMeta();s.PaginationMeta=p}this.hasSearchAction&&(s.SearchRequestBody=this.paginationSchemaFactory.generateSearchRequestBody(this.model.pagination)),a.schemas=s,Object.keys(o).length>0&&(a.securitySchemes=o);let n={openapi:"3.1.0",info:this.generateInfo()};e?.servers&&(n.servers=e.servers),Object.keys(r).length>0&&(n.paths=r),Object.keys(a).length>0&&(n.components=a);let l=i.securityRequirementsResolver.generateGlobalSecurityRequirements(this.model);l.length>0&&(n.security=l);let d=this.fileUploadContributor.getTags(i);return d.length>0&&(n.tags||(n.tags=[]),n.tags.push(...d)),n}};var Ya=class extends et{file;client;constructor(e,t,i,r=new Z,s=F()){super(t,i,r),this.file=e,this.client=s}async execute(){y.debug(`[api:oas] Executing OAS generation. File=${this.file}, stdin=${this.options.stdin}`);try{this.validateInputParameters();let e=await this.loadApiModelSchema(),t=await this.resolveDataDomain(e),i=new Ei(e,t),r=this.generateOasSpec(i);this.emitOutput(r)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}get shouldReadFromStdin(){return!!(this.options.stdin||this.file==="-")}validateInputParameters(){(this.file||this.options.file||this.options.id)&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),this.file&&(this.file.includes("/")||this.file.includes("\\")||this.file.endsWith(".json"))&&(ri.existsSync(this.file)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${Is.resolve(this.file)}`}),process.exit(1)))}async loadApiModelSchema(){return this.shouldReadFromStdin?this.loadFromStdin():this.file&&ri.existsSync(this.file)?this.loadFromLocalFile(this.file):this.loadFromRemote()}async loadFromStdin(){y.debug("[api:oas] Reading API model schema from STDIN...");let e=await this.fileManager.readStdin(),t;try{t=JSON.parse(e)}catch(i){let r=i instanceof Error?i.message:String(i);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse schema JSON from STDIN: ${r}`}),process.exit(1)}return this.validateSchemaKind(t),t}loadFromLocalFile(e){let t=Is.resolve(e);y.debug(`[api:oas] Reading local API model file from path: ${t}`);let i;try{i=ri.readFileSync(t,"utf8")}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to read file at ${t}: ${o}`}),process.exit(1)}let r;try{r=JSON.parse(i)}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse JSON file at ${t}: ${o}`}),process.exit(1)}return this.validateSchemaKind(r),r}async loadFromRemote(){let e=this.resolveOrgId(),t=await this.resolveTargetFileId(e);y.debug(`[api:oas] Fetching file metadata for ID '${t}' in org '${e}'...`);let i=await this.fileManager.read(e,t);i.kind!==Yt&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File '${t}' is not an API model. The file kind is '${i.kind}', but expected '${Yt}'.`}),process.exit(1)),y.debug(`[api:oas] Fetching media schema for API model ID '${t}'...`);let r=await this.fileManager.readMedia(e,t);return this.validateSchemaKind(r.media),r.media}async resolveTargetFileId(e){let t=this.options.file||this.options.id||(this.file&&!ri.existsSync(this.file)?this.file:void 0);return t||this.resolveFileId(e,"Select an API model file to generate OAS for:")}validateSchemaKind(e){(!e||typeof e!="object"||Array.isArray(e))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid API model schema. Expected a JSON object."}),process.exit(1));let t=e;t.kind!==ke&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${String(t.kind)}', but expected '${ke}'.`}),process.exit(1))}async resolveDataDomain(e){if(this.options.domain)return this.loadLocalDomain(this.options.domain);let t=e.dependencyList||[];return this.resolveCatalogDomain(t,e.info?.name||e.key)}loadLocalDomain(e){let t=Is.resolve(e);y.debug(`[api:oas] Loading local Data Domain schema from: ${t}`),ri.existsSync(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${t}`}),process.exit(1));let i;try{i=JSON.parse(ri.readFileSync(t,"utf8"))}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${o}`}),process.exit(1)}(!i||typeof i!="object"||Array.isArray(i))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid Data Domain schema. Expected a JSON object."}),process.exit(1));let r=i;return r.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid Data Domain schema. The media kind is '${String(r.kind)}', but expected '${Ee}'.`}),process.exit(1)),new Me(i,[],{readOnly:!0})}async resolveCatalogDomain(e,t){e.length===0&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`API model '${t}' does not have a data domain dependency attached. OAS generation requires an attached data domain.`}),process.exit(1)),y.debug(`[api:oas] Resolving ${e.length} dependency from data catalog...`);let r=(await this.client.dataCatalog.listDependencies(e,{token:this.client.token})).data||[];r.length===0&&(this.formatter.error({code:"CLI_ERR_API_FAILURE",message:`Could not resolve data domain dependency for API model '${t}' from the data catalog. Ensure the data domain is published in the catalog.`}),process.exit(1));let s=e[0]?.key,o=r.find(a=>a.key===s)??r[0];return new Me(o,r,{readOnly:!0})}generateOasSpec(e){y.debug("[api:oas] Generating OpenAPI Specification using OasGenerator...");let t=this.options.server?.map(r=>({url:r}));return new Ha(e).generate(t?{servers:t}:void 0)}emitOutput(e){let t=JSON.stringify(e,null,2);if(this.options.output){let i=Is.resolve(this.options.output),r=Is.dirname(i);ri.existsSync(r)||ri.mkdirSync(r,{recursive:!0}),ri.writeFileSync(i,t,"utf8"),y.debug(`[api:oas] OAS specification written to: ${i}`),this.formatter.success(`OpenAPI specification written to ${i}`)}else console.log(t)}};import xi from"node:fs";import un from"node:path";function it(c){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(c)?c:JSON.stringify(c)}function rt(c){try{let e=c.readBinding("web");return e?.name?e.name:c.info.name&&c.info.name!=="new_property"?c.info.name:c.key}catch{return c.info.name&&c.info.name!=="new_property"?c.info.name:c.key}}function $t(c){try{let e=c.readBinding("web");return e?.name?e.name:c.info.name&&c.info.name!=="new_association"?c.info.name:c.key}catch{return c.info.name&&c.info.name!=="new_association"?c.info.name:c.key}}function ce(c){return c?c.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[^a-zA-Z0-9]/g," ").split(/\s+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}function ht(c){let e=ce(c);return e?e.charAt(0).toLowerCase()+e.slice(1):""}var wr=class{mapPropertyType(e,t={}){let i=e.schema?.enum,r;return Array.isArray(i)&&i.length>0?r=this.generateEnumType(i):r=this.resolvePrimitiveType(e,t.isInput??!1),e.multiple===!0?this.wrapArray(r):r}mapAssociationType(e,t){let i=e.schema?.embedded===!0,r;if(i){let s=Array.from(e.listTargets());if(s.length===0)r=t&&t.key===e.key?ce(t.getExposedName()):"Record<string, unknown>";else if(s.length===1){let o=s[0];r=o?ce(o.getExposedName()):"Record<string, unknown>"}else r=s.map(a=>ce(a.getExposedName())).join(" | ")}else r="string";return e.multiple===!0?this.wrapArray(r):r}generateEnumType(e){if(!Array.isArray(e)||e.length===0)return"string";let t=e.map(i=>typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`:typeof i=="number"||typeof i=="boolean"?String(i):i===null?"null":"unknown");return Array.from(new Set(t)).join(" | ")}resolvePrimitiveType(e,t=!1){switch(e.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return"string";case"datetime":return t?"string | Date":"string";case"time":return"string";case"json":return e.jsonSchema&&typeof e.jsonSchema=="object"&&"title"in e.jsonSchema&&typeof e.jsonSchema.title=="string"?ce(e.jsonSchema.title):"Record<string, unknown>";case"binary":return"Blob | File";default:return"unknown"}}wrapArray(e){return e.includes("|")&&!e.startsWith("(")&&!e.endsWith(")")?`(${e})[]`:`${e}[]`}};var Xa=class{schemaGen;typeMapper;constructor(e,t){this.typeMapper=e??new wr,this.schemaGen=t??new Bt}emitUnifiedInputInterface(e,t){let i=[];i.push(`/**
|
|
195
|
+
Active records only are clustered; soft-deleted records are automatically excluded. Returns an array of point centroids with their associated \`point_count\` wrapped in a standard \`data\` envelope.`,!1,"Bad Request. Invalid or missing bounding box parameters (minLat, minLon, maxLat, maxLon) or invalid precision level.",$.length>0)}}}}createGeoClusterSchema(){return{type:"object",properties:{data:{type:"array",items:{type:"object",properties:{type:{type:"string",example:"Point"},coordinates:{type:"array",items:{type:"number"},example:[-74.006,40.7128]},point_count:{type:"integer",example:5}},required:["type","coordinates"]}}},required:["data"]}}};var Ha=class{model;#e=!1;get hasListAction(){return this.#e}#t=!1;get hasSearchAction(){return this.#t}processorRegistry=new Va;authContributor=new Ba;verificationContributor=new Ga;fileUploadContributor=new Ja;geospatialContributor=new Wa;errorSchemaFactory=new Fa;paginationSchemaFactory=new qa;searchAstSchemaFactory=new Ka;constructor(e){this.model=e}generateInfo(){let e={title:this.model.info.displayName||this.model.info.name||"API",version:this.model.info.version||"1.0.0"};return this.model.info.description&&(e.description=this.model.info.description),this.model.termsOfService&&(e.termsOfService=this.model.termsOfService),this.model.contact&&(e.contact={...this.model.contact}),this.model.license&&(e.license={...this.model.license}),e}generate(e){let{domain:t}=this.model;if(!t)throw new Error("Data domain is required for OAS generation");let i=new Oa(this.model,t,e);i.preRegisterReadOperations();let r={};this.authContributor.contribute(r,i),this.verificationContributor.contribute(r,i),this.fileUploadContributor.contribute(r,i);for(let p of this.model.exposes.values()){let m=t.findEntity(p.entity.key);if(!m||!i.schemaGen.generateRootRef(m))continue;let f=i.linkResolver.resolveEntityLinks(m,i),k=Object.keys(f).length>0,w=i.resolveOperationIdKey(p,m),S=m.info.getLabel(),E=vr(S),A=Et(E),_={links:f,hasLinks:k,operationIdKey:w,entityName:S,entityNameUpper:E,pluralName:A};for(let $ of p.actions){let P=this.processorRegistry.get($.kind);if(!P)continue;let j=P.process($,p,m,i,_);if(j){let L=Array.isArray(j)?j:[j];for(let I of L)r[I.path]=r[I.path]||{},r[I.path][I.method]=I.operation}}this.geospatialContributor.contributeEntity(r,p,m,i)}this.#e=i.hasListAction,this.#t=i.hasSearchAction;let s=i.schemaGen.getSchemas();Object.assign(s,this.errorSchemaFactory.createErrorSchemas());let o=i.securityRequirementsResolver.generateSecuritySchemes(this.model),a={};if(i.whereAstInjected&&Object.assign(s,this.searchAstSchemaFactory.getAstComponentSchemas()),this.hasListAction||this.hasSearchAction){let p=this.model.pagination.kind==="cursor"?this.paginationSchemaFactory.createCursorPaginationMeta():this.paginationSchemaFactory.createOffsetPaginationMeta();s.PaginationMeta=p}this.hasSearchAction&&(s.SearchRequestBody=this.paginationSchemaFactory.generateSearchRequestBody(this.model.pagination)),a.schemas=s,Object.keys(o).length>0&&(a.securitySchemes=o);let n={openapi:"3.1.0",info:this.generateInfo()};e?.servers&&(n.servers=e.servers),Object.keys(r).length>0&&(n.paths=r),Object.keys(a).length>0&&(n.components=a);let l=i.securityRequirementsResolver.generateGlobalSecurityRequirements(this.model);l.length>0&&(n.security=l);let d=this.fileUploadContributor.getTags(i);return d.length>0&&(n.tags||(n.tags=[]),n.tags.push(...d)),n}};var Ya=class extends et{file;client;constructor(e,t,i,r=new Z,s=F()){super(t,i,r),this.file=e,this.client=s}async execute(){y.debug(`[api:oas] Executing OAS generation. File=${this.file}, stdin=${this.options.stdin}`);try{this.validateInputParameters();let e=await this.loadApiModelSchema(),t=await this.resolveDataDomain(e),i=new Ei(e,t),r=this.generateOasSpec(i);this.emitOutput(r)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}get shouldReadFromStdin(){return!!(this.options.stdin||this.file==="-")}validateInputParameters(){(this.file||this.options.file||this.options.id)&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),this.file&&(this.file.includes("/")||this.file.includes("\\")||this.file.endsWith(".json"))&&(ri.existsSync(this.file)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${Is.resolve(this.file)}`}),process.exit(1)))}async loadApiModelSchema(){return this.shouldReadFromStdin?this.loadFromStdin():this.file&&ri.existsSync(this.file)?this.loadFromLocalFile(this.file):this.loadFromRemote()}async loadFromStdin(){y.debug("[api:oas] Reading API model schema from STDIN...");let e=await this.fileManager.readStdin(),t;try{t=JSON.parse(e)}catch(i){let r=i instanceof Error?i.message:String(i);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse schema JSON from STDIN: ${r}`}),process.exit(1)}return this.validateSchemaKind(t),t}loadFromLocalFile(e){let t=Is.resolve(e);y.debug(`[api:oas] Reading local API model file from path: ${t}`);let i;try{i=ri.readFileSync(t,"utf8")}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to read file at ${t}: ${o}`}),process.exit(1)}let r;try{r=JSON.parse(i)}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse JSON file at ${t}: ${o}`}),process.exit(1)}return this.validateSchemaKind(r),r}async loadFromRemote(){let e=this.resolveOrgId(),t=await this.resolveTargetFileId(e);y.debug(`[api:oas] Fetching file metadata for ID '${t}' in org '${e}'...`);let i=await this.fileManager.read(e,t);i.kind!==Yt&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File '${t}' is not an API model. The file kind is '${i.kind}', but expected '${Yt}'.`}),process.exit(1)),y.debug(`[api:oas] Fetching media schema for API model ID '${t}'...`);let r=await this.fileManager.readMedia(e,t);return this.validateSchemaKind(r.media),r.media}async resolveTargetFileId(e){let t=this.options.file||this.options.id||(this.file&&!ri.existsSync(this.file)?this.file:void 0);return t||this.resolveFileId(e,"Select an API model file to generate OAS for:")}validateSchemaKind(e){(!e||typeof e!="object"||Array.isArray(e))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid API model schema. Expected a JSON object."}),process.exit(1));let t=e;t.kind!==ke&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${String(t.kind)}', but expected '${ke}'.`}),process.exit(1))}async resolveDataDomain(e){if(this.options.domain)return this.loadLocalDomain(this.options.domain);let t=e.dependencyList||[];return this.resolveCatalogDomain(t,e.info?.name||e.key)}loadLocalDomain(e){let t=Is.resolve(e);y.debug(`[api:oas] Loading local Data Domain schema from: ${t}`),ri.existsSync(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${t}`}),process.exit(1));let i;try{i=JSON.parse(ri.readFileSync(t,"utf8"))}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${o}`}),process.exit(1)}(!i||typeof i!="object"||Array.isArray(i))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid Data Domain schema. Expected a JSON object."}),process.exit(1));let r=i;return r.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid Data Domain schema. The media kind is '${String(r.kind)}', but expected '${Ee}'.`}),process.exit(1)),new Me(i,[],{readOnly:!0})}async resolveCatalogDomain(e,t){e.length===0&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`API model '${t}' does not have a data domain dependency attached. OAS generation requires an attached data domain.`}),process.exit(1)),y.debug(`[api:oas] Resolving ${e.length} dependency from data catalog...`);let r=(await this.client.dataCatalog.listDependencies(e,{token:this.client.token})).data||[];r.length===0&&(this.formatter.error({code:"CLI_ERR_API_FAILURE",message:`Could not resolve data domain dependency for API model '${t}' from the data catalog. Ensure the data domain is published in the catalog.`}),process.exit(1));let s=e[0]?.key,o=r.find(a=>a.key===s)??r[0];return new Me(o,r,{readOnly:!0})}generateOasSpec(e){y.debug("[api:oas] Generating OpenAPI Specification using OasGenerator...");let t=this.options.server?.map(r=>({url:r}));return new Ha(e).generate(t?{servers:t}:void 0)}emitOutput(e){let t=JSON.stringify(e,null,2);if(this.options.output){let i=Is.resolve(this.options.output),r=Is.dirname(i);ri.existsSync(r)||ri.mkdirSync(r,{recursive:!0}),ri.writeFileSync(i,t,"utf8"),y.debug(`[api:oas] OAS specification written to: ${i}`),this.formatter.success(`OpenAPI specification written to ${i}`)}else console.log(t)}};import xi from"node:fs";import un from"node:path";function it(c){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(c)?c:JSON.stringify(c)}function rt(c){try{let e=c.readBinding("web");return e?.name?e.name:c.info.name&&c.info.name!=="new_property"?c.info.name:c.key}catch{return c.info.name&&c.info.name!=="new_property"?c.info.name:c.key}}function $t(c){try{let e=c.readBinding("web");return e?.name?e.name:c.info.name&&c.info.name!=="new_association"?c.info.name:c.key}catch{return c.info.name&&c.info.name!=="new_association"?c.info.name:c.key}}function ce(c){return c?c.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").replace(/[^a-zA-Z0-9]/g," ").split(/\s+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join(""):""}function ht(c){let e=ce(c);return e?e.charAt(0).toLowerCase()+e.slice(1):""}var wr=class{mapPropertyType(e,t={}){let i=e.schema?.enum,r;return Array.isArray(i)&&i.length>0?r=this.generateEnumType(i):r=this.resolvePrimitiveType(e,t.isInput??!1),e.multiple===!0?this.wrapArray(r):r}mapAssociationType(e,t){let i=e.schema?.embedded===!0,r;if(i){let s=Array.from(e.listTargets());if(s.length===0)r=t&&t.key===e.key?ce(t.getExposedName()):"Record<string, unknown>";else if(s.length===1){let o=s[0];r=o?ce(o.getExposedName()):"Record<string, unknown>"}else r=s.map(a=>ce(a.getExposedName())).join(" | ")}else r="string";return e.multiple===!0?this.wrapArray(r):r}generateEnumType(e){if(!Array.isArray(e)||e.length===0)return"string";let t=e.map(i=>typeof i=="string"?`'${i.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`:typeof i=="number"||typeof i=="boolean"?String(i):i===null?"null":"unknown");return Array.from(new Set(t)).join(" | ")}resolvePrimitiveType(e,t=!1){switch(e.type){case"string":return"string";case"number":return"number";case"boolean":return"boolean";case"date":return"string";case"datetime":return t?"string | Date":"string";case"time":return"string";case"json":return e.jsonSchema&&typeof e.jsonSchema=="object"&&"title"in e.jsonSchema&&typeof e.jsonSchema.title=="string"?ce(e.jsonSchema.title):"Record<string, unknown>";case"binary":return"Blob | File";default:return"unknown"}}wrapArray(e){return e.includes("|")&&!e.startsWith("(")&&!e.endsWith(")")?`(${e})[]`:`${e}[]`}};var Xa=class{schemaGen;typeMapper;constructor(e,t){this.typeMapper=e??new wr,this.schemaGen=t??new Bt}emitUnifiedInputInterface(e,t){let i=[];i.push(`/**
|
|
196
196
|
* Input payload for creating or updating a ${e}.
|
|
197
197
|
*/`),i.push(`export interface ${e}Input {`);for(let r of t.properties){if(this.isExcludedFromInput(r,"create"))continue;let s=rt(r),o=this.typeMapper.mapPropertyType(r,{isInput:!0}),n=this.isOptionalOnInput(r,"create")?"?":"";r.info.description&&i.push(` /** ${r.info.description} */`),i.push(` ${it(s)}${n}: ${o}`)}for(let r of t.associations){if(this.isExcludedFromInputAssoc(r))continue;let s=$t(r),o=this.typeMapper.mapAssociationType(r,t),a=r.required?"":"?";r.info.description&&i.push(` /** ${r.info.description} */`),i.push(` ${it(s)}${a}: ${o}`)}return i.push("}"),i.push(`export type ${e}CreateInput = ${e}Input`),i.push(`export type ${e}UpdateInput = ${e}Input`),i.join(`
|
|
198
198
|
`)}emitCreateInputInterface(e,t){let i=[];i.push(`/**
|
|
@@ -218,7 +218,7 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
218
218
|
`)}emitFilteredInterface(e,t,i,r){let s=i.type==="include",o=[];o.push(`/**
|
|
219
219
|
* ${r} response for ${t.info.name||t.key}.
|
|
220
220
|
*/`),o.push(`export interface ${e} {`);for(let a of t.properties){if(a.writeOnly===!0||this.isWebHidden(a))continue;let n=rt(a),l=i.fields.some(k=>{if(k.type&&k.type!=="property")return!1;let[w]=k.key.split(".");return w===a.key||w===n});if(!(s?l:!l))continue;let p=this.typeMapper.mapPropertyType(a),m=this.isReadOnlyProperty(a),h=a.required?"":"?",f=m?"readonly ":"";o.push(` ${f}${it(n)}${h}: ${p}`)}for(let a of t.associations){if(this.isWebHidden(a)||Array.from(a.listTargets()).length===0)continue;let l=$t(a),d=i.fields.some(w=>{if(w.type&&w.type!=="association")return!1;let[S]=w.key.split(".");return S===a.key||S===l});if(!(s?d:!d))continue;let m=this.typeMapper.mapAssociationType(a,t),h=this.isReadOnlyAssociation(a),f=a.required?"":"?",k=h?"readonly ":"";o.push(` ${k}${it(l)}${f}: ${m}`)}return o.push("}"),o.join(`
|
|
221
|
-
`)}resolveEmbeddedImports(e){let t=new Set,i=ce(e.getExposedName());for(let r of e.associations)if(!this.isWebHidden(r)&&r.schema?.embedded===!0)for(let s of r.listTargets()){let o=ce(s.getExposedName());o&&o!==i&&t.add(`import type { ${o} } from './${o}.js'`)}return Array.from(t).sort()}isReadOnlyProperty(e){return!!e.readOnly||this.schemaGen.isSystemProperty(e)}isReadOnlyAssociation(e){return!!e.readOnly||this.schemaGen.isSystemAssociation(e)}isWebHidden(e){return e.readBinding("web")?.hidden===!0}};var Gt=class{resolveCollectionPath(e){return e.getAbsoluteCollectionPath()||e.collectionPath||void 0}resolveResourcePath(e){return e.getAbsoluteResourcePath()||e.resourcePath}extractPathParameters(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map(i=>i.slice(1,-1)):[]}buildUrl(e,t){return e.replace(/\{([^}]+)\}/g,(i,r)=>{let s=t[r];if(s==null)throw new Error(`Missing required path parameter "${r}" for path "${e}"`);return encodeURIComponent(String(s))})}generatePathExpression(e,t){let i=this.extractPathParameters(e);if(i.length===0)return`'${e}'`;let r=e;for(let s of i){let o=t[s]||s;r=r.replace(`{${s}}`,`\${
|
|
221
|
+
`)}resolveEmbeddedImports(e){let t=new Set,i=ce(e.getExposedName());for(let r of e.associations)if(!this.isWebHidden(r)&&r.schema?.embedded===!0)for(let s of r.listTargets()){let o=ce(s.getExposedName());o&&o!==i&&t.add(`import type { ${o} } from './${o}.js'`)}return Array.from(t).sort()}isReadOnlyProperty(e){return!!e.readOnly||this.schemaGen.isSystemProperty(e)}isReadOnlyAssociation(e){return!!e.readOnly||this.schemaGen.isSystemAssociation(e)}isWebHidden(e){return e.readBinding("web")?.hidden===!0}};var Gt=class{resolveCollectionPath(e){return e.getAbsoluteCollectionPath()||e.collectionPath||void 0}resolveResourcePath(e){return e.getAbsoluteResourcePath()||e.resourcePath}extractPathParameters(e){let t=e.match(/\{([^}]+)\}/g);return t?t.map(i=>i.slice(1,-1)):[]}buildUrl(e,t){return e.replace(/\{([^}]+)\}/g,(i,r)=>{let s=t[r];if(s==null)throw new Error(`Missing required path parameter "${r}" for path "${e}"`);return encodeURIComponent(String(s))})}generatePathExpression(e,t){let i=this.extractPathParameters(e);if(i.length===0)return`'${e}'`;let r=e;for(let s of i){let o=t[s]||s;r=r.replace(`{${s}}`,`\${${o}}`)}return`path\`${r}\``}};var Sr=class{pathResolver;constructor(e=new Gt){this.pathResolver=e}hasGeospatial(e){return Array.from(e.properties).some(t=>t.semantics.some(i=>i.id===g.GeospatialCoordinates))}getGeospatialConfig(e){for(let t of e.properties){let i=t.getSemantic(g.GeospatialCoordinates);if(i)return i.config??gr}}emitGeospatialMethods(e,t,i){let r=this.getGeospatialConfig(t);if(!r)return[];let s=e.getAbsoluteCollectionPath();if(!s)return[];let o=r.apiEndpointPrefix||"/nearby",a=[];if(r.enableDistanceQueries!==!1){let n=`${s}${o}`,l=this.pathResolver.extractPathParameters(n),d={};for(let m of l)d[m]=`this.pathParams['${m}']`;let p=this.pathResolver.generatePathExpression(n,d);a.push(` /** Finds ${i} records within a specified distance from a coordinate point. */
|
|
222
222
|
public async nearby(options: { lat: number; lon: number; distance?: number; unit?: string; limit?: number }): Promise<Page<${i}>> {
|
|
223
223
|
return this.transport.request<Page<${i}>>(${p}, {
|
|
224
224
|
method: 'GET',
|
|
@@ -272,13 +272,13 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
272
272
|
actionName: 'read',
|
|
273
273
|
})
|
|
274
274
|
}`),r.push(` /** Retrieves the ${i} record for current user session with conditional ETag caching support. */
|
|
275
|
-
public async readConditional(options
|
|
275
|
+
public async readConditional(options: ConditionalOptions): Promise<ConditionalResult<${f}>> {
|
|
276
276
|
return this.transport.requestConditional<${f}>({
|
|
277
277
|
method: 'GET',
|
|
278
278
|
path: ${E},
|
|
279
279
|
resourceName: '${s}',
|
|
280
280
|
actionName: 'read',
|
|
281
|
-
etag: options
|
|
281
|
+
etag: options.etag,
|
|
282
282
|
})
|
|
283
283
|
}`)}else{let E=this.generateResourcePathExpr(e,!1);r.push(` /** Retrieves a single ${i} record by ID. */
|
|
284
284
|
public async read(id: string): Promise<${f}> {
|
|
@@ -289,16 +289,16 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
289
289
|
actionName: 'read',
|
|
290
290
|
})
|
|
291
291
|
}`),r.push(` /** Retrieves a single ${i} record by ID with conditional ETag caching support. */
|
|
292
|
-
public async readConditional(id: string, options
|
|
292
|
+
public async readConditional(id: string, options: ConditionalOptions): Promise<ConditionalResult<${f}>> {
|
|
293
293
|
return this.transport.requestConditional<${f}>({
|
|
294
294
|
method: 'GET',
|
|
295
295
|
path: ${E},
|
|
296
296
|
resourceName: '${s}',
|
|
297
297
|
actionName: 'read',
|
|
298
|
-
etag: options
|
|
298
|
+
etag: options.etag,
|
|
299
299
|
})
|
|
300
300
|
}`)}break}case"create":{if(!o)break;let E=this.generateCollectionPathExpr(e);r.push(` /** Creates a new ${i} record. */
|
|
301
|
-
public async create(body: ${l}, options?:
|
|
301
|
+
public async create(body: ${l}, options?: MutationOptions): Promise<${f}> {
|
|
302
302
|
if (options?.validate !== false) {
|
|
303
303
|
assertCreateInput(body)
|
|
304
304
|
}
|
|
@@ -309,8 +309,8 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
309
309
|
resourceName: '${s}',
|
|
310
310
|
actionName: 'create',
|
|
311
311
|
})
|
|
312
|
-
}`);break}case"update":{let A=
|
|
313
|
-
public async
|
|
312
|
+
}`);break}case"update":{let E=S,A=Array.isArray(E.allowedMethods)?E.allowedMethods:[];if(A.includes("PATCH"))if(a){let _=this.generateResourcePathExpr(e,!0);r.push(` /** Applies partial updates to current user's ${i}. */
|
|
313
|
+
public async patch(body: ${p}, options?: MutationOptions): Promise<${f}> {
|
|
314
314
|
if (options?.validate !== false) {
|
|
315
315
|
assertPatchInput(body)
|
|
316
316
|
}
|
|
@@ -319,10 +319,10 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
319
319
|
path: ${_},
|
|
320
320
|
body,
|
|
321
321
|
resourceName: '${s}',
|
|
322
|
-
actionName: '
|
|
322
|
+
actionName: 'patch',
|
|
323
323
|
})
|
|
324
324
|
}`)}else{let _=this.generateResourcePathExpr(e,!1);r.push(` /** Applies partial updates to an existing ${i} record. */
|
|
325
|
-
public async
|
|
325
|
+
public async patch(id: string, body: ${p}, options?: MutationOptions): Promise<${f}> {
|
|
326
326
|
if (options?.validate !== false) {
|
|
327
327
|
assertPatchInput(body)
|
|
328
328
|
}
|
|
@@ -331,10 +331,10 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
331
331
|
path: ${_},
|
|
332
332
|
body,
|
|
333
333
|
resourceName: '${s}',
|
|
334
|
-
actionName: '
|
|
334
|
+
actionName: 'patch',
|
|
335
335
|
})
|
|
336
|
-
}`)}if(A.includes("PUT"))if(a){let _=this.generateResourcePathExpr(e,!0);r.push(` /**
|
|
337
|
-
public async
|
|
336
|
+
}`)}if(A.includes("PUT"))if(a){let _=this.generateResourcePathExpr(e,!0);r.push(` /** Updates current user's ${i} with provided payload. */
|
|
337
|
+
public async update(body: ${d}, options?: MutationOptions): Promise<${f}> {
|
|
338
338
|
if (options?.validate !== false) {
|
|
339
339
|
assertUpdateInput(body)
|
|
340
340
|
}
|
|
@@ -343,10 +343,10 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
343
343
|
path: ${_},
|
|
344
344
|
body,
|
|
345
345
|
resourceName: '${s}',
|
|
346
|
-
actionName: '
|
|
346
|
+
actionName: 'update',
|
|
347
347
|
})
|
|
348
|
-
}`)}else{let _=this.generateResourcePathExpr(e,!1);r.push(` /**
|
|
349
|
-
public async
|
|
348
|
+
}`)}else{let _=this.generateResourcePathExpr(e,!1);r.push(` /** Updates an existing ${i} record with provided payload. */
|
|
349
|
+
public async update(id: string, body: ${d}, options?: MutationOptions): Promise<${f}> {
|
|
350
350
|
if (options?.validate !== false) {
|
|
351
351
|
assertUpdateInput(body)
|
|
352
352
|
}
|
|
@@ -355,11 +355,11 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
355
355
|
path: ${_},
|
|
356
356
|
body,
|
|
357
357
|
resourceName: '${s}',
|
|
358
|
-
actionName: '
|
|
358
|
+
actionName: 'update',
|
|
359
359
|
})
|
|
360
360
|
}`)}break}case"delete":{if(a){let E=this.generateResourcePathExpr(e,!0);r.push(` /** Deletes the ${i} record for current user session. */
|
|
361
361
|
public async delete(): Promise<void> {
|
|
362
|
-
|
|
362
|
+
await this.transport.request({
|
|
363
363
|
method: 'DELETE',
|
|
364
364
|
path: ${E},
|
|
365
365
|
resourceName: '${s}',
|
|
@@ -367,7 +367,7 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
367
367
|
})
|
|
368
368
|
}`)}else{let E=this.generateResourcePathExpr(e,!1);r.push(` /** Deletes a single ${i} record by ID. */
|
|
369
369
|
public async delete(id: string): Promise<void> {
|
|
370
|
-
|
|
370
|
+
await this.transport.request({
|
|
371
371
|
method: 'DELETE',
|
|
372
372
|
path: ${E},
|
|
373
373
|
resourceName: '${s}',
|
|
@@ -403,13 +403,13 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
403
403
|
})
|
|
404
404
|
}`);break}case"unlink":{let E=this.generateResourcePathExpr(e,!1);r.push(` /** Unlinks an associated record from ${i}. */
|
|
405
405
|
public async unlink(id: string): Promise<void> {
|
|
406
|
-
|
|
406
|
+
await this.transport.request({
|
|
407
407
|
method: 'DELETE',
|
|
408
408
|
path: ${E},
|
|
409
409
|
resourceName: '${s}',
|
|
410
410
|
actionName: 'unlink',
|
|
411
411
|
})
|
|
412
|
-
}`);break}}let w=this.geoEmitter.emitGeospatialMethods(e,t,i);return w.length>0&&r.push(...w),r}generateCollectionPathExpr(e){let t=this.pathResolver.resolveCollectionPath(e)||"",i=this.buildParamMap(e);return this.pathResolver.generatePathExpression(t,i)}generateResourcePathExpr(e,t){let i=this.pathResolver.resolveResourcePath(e),r=this.buildParamMap(e);if(!t){let s=this.resolveIdParamName(e);r[s]="id"}return this.pathResolver.generatePathExpression(i,r)}buildParamMap(e){let t=this.pathResolver.resolveResourcePath(e),i=this.pathResolver.
|
|
412
|
+
}`);break}}let w=this.geoEmitter.emitGeospatialMethods(e,t,i);return w.length>0&&r.push(...w),r}generateCollectionPathExpr(e){let t=this.pathResolver.resolveCollectionPath(e)||"",i=this.buildParamMap(e);return this.pathResolver.generatePathExpression(t,i)}generateResourcePathExpr(e,t){let i=this.pathResolver.resolveResourcePath(e),r=this.buildParamMap(e);if(!t){let s=this.resolveIdParamName(e);r[s]="id"}return this.pathResolver.generatePathExpression(i,r)}buildParamMap(e){let t=this.pathResolver.resolveResourcePath(e),i=this.pathResolver.resolveCollectionPath(e)||"",r=Array.from(new Set([...this.pathResolver.extractPathParameters(t),...this.pathResolver.extractPathParameters(i)])),s={};for(let o of r)s[o]=`this.pathParams['${o}']`;return s}resolveIdParamName(e){let t=this.pathResolver.resolveResourcePath(e),i=this.pathResolver.extractPathParameters(t);return i.length>0?i[i.length-1]:"id"}getResourceName(e,t){if(e.collectionPath){let i=e.collectionPath.split("/").filter(Boolean);if(i.length>0)return ht(i[i.length-1])}return ht(t.getExposedName())}};var Za=class{pathResolver;typeEmitter;actionEmitter;constructor(e=new Gt,t=new ft,i=new Ar(e,t)){this.pathResolver=e,this.typeEmitter=t,this.actionEmitter=i}emitScopedResourceClass(e,t,i,r){let s=[];s.push(`/**
|
|
413
413
|
* Scoped resource for a specific ${e} instance.
|
|
414
414
|
*/`),s.push(`export class Scoped${e}Resource {`),s.push(" constructor("),s.push(" private readonly transport: HttpTransport,"),s.push(" private readonly pathParams: Record<string, string>"),s.push(" ) {}");for(let n of r){let l=this.resolveChildResourceClassName(n,i,t.api),d=this.resolveChildAccessorName(n,i);s.push(""),s.push(` /** Access sub-resource ${d}. */`),s.push(` public get ${d}(): ${l} {`),s.push(` return new ${l}(this.transport, this.pathParams)`),s.push(" }")}let o=this.actionEmitter.getResourceName(t,i);s.push(""),s.push(" /** Retrieves the rate limit state for this resource or a specific action. */"),s.push(" public getRateLimit(action?: string): RateLimitState | undefined {"),s.push(` return this.transport.getRateLimits('${o}', action)`),s.push(" }");let a=this.emitScopedActionMethods(t,i,e);return a.length>0&&(s.push(""),s.push(a.join(`
|
|
415
415
|
|
|
@@ -423,16 +423,16 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
423
423
|
actionName: 'read',
|
|
424
424
|
})
|
|
425
425
|
}`),r.push(` /** Retrieves this ${i} record with conditional ETag caching support. */
|
|
426
|
-
public async readConditional(options
|
|
426
|
+
public async readConditional(options: ConditionalOptions): Promise<ConditionalResult<${d}>> {
|
|
427
427
|
return this.transport.requestConditional<${d}>({
|
|
428
428
|
method: 'GET',
|
|
429
429
|
path: ${p},
|
|
430
430
|
resourceName: '${s}',
|
|
431
431
|
actionName: 'read',
|
|
432
|
-
etag: options
|
|
432
|
+
etag: options.etag,
|
|
433
433
|
})
|
|
434
|
-
}`);else if(m.kind==="update"){let f=
|
|
435
|
-
public async
|
|
434
|
+
}`);else if(m.kind==="update"){let h=m,f=Array.isArray(h.allowedMethods)?h.allowedMethods:[];f.includes("PATCH")&&r.push(` /** Applies partial updates to this ${i}. */
|
|
435
|
+
public async patch(body: ${n}, options?: MutationOptions): Promise<${d}> {
|
|
436
436
|
if (options?.validate !== false) {
|
|
437
437
|
assertPatchInput(body)
|
|
438
438
|
}
|
|
@@ -441,10 +441,10 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
441
441
|
path: ${p},
|
|
442
442
|
body,
|
|
443
443
|
resourceName: '${s}',
|
|
444
|
-
actionName: '
|
|
444
|
+
actionName: 'patch',
|
|
445
445
|
})
|
|
446
|
-
}`),f.includes("PUT")&&r.push(` /**
|
|
447
|
-
public async
|
|
446
|
+
}`),f.includes("PUT")&&r.push(` /** Updates this ${i} with provided payload. */
|
|
447
|
+
public async update(body: ${a}, options?: MutationOptions): Promise<${d}> {
|
|
448
448
|
if (options?.validate !== false) {
|
|
449
449
|
assertUpdateInput(body)
|
|
450
450
|
}
|
|
@@ -453,17 +453,17 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
453
453
|
path: ${p},
|
|
454
454
|
body,
|
|
455
455
|
resourceName: '${s}',
|
|
456
|
-
actionName: '
|
|
456
|
+
actionName: 'update',
|
|
457
457
|
})
|
|
458
458
|
}`)}else m.kind==="delete"&&r.push(` /** Deletes this ${i}. */
|
|
459
459
|
public async delete(): Promise<void> {
|
|
460
|
-
|
|
460
|
+
await this.transport.request({
|
|
461
461
|
method: 'DELETE',
|
|
462
462
|
path: ${p},
|
|
463
463
|
resourceName: '${s}',
|
|
464
464
|
actionName: 'delete',
|
|
465
465
|
})
|
|
466
|
-
}`);return r}};var Qa=class{pathResolver;typeEmitter;geoEmitter;actionEmitter;scopedEmitter;constructor(e=new Gt,t=new ft,i=new Sr(e),r=new Ar(e,t,i),s=new Za(e,t,r)){this.pathResolver=e,this.typeEmitter=t,this.geoEmitter=i,this.actionEmitter=r,this.scopedEmitter=s}emitResource(e,t,i=[],r){let s=t.getExposedName(),o=!!e.parent?.selfRoute,a=ce(s),n=r||(o?`${a}MeResource`:`${a}Resource`),l=i.filter(
|
|
466
|
+
}`);return r}};var Qa=class{pathResolver;typeEmitter;geoEmitter;actionEmitter;scopedEmitter;constructor(e=new Gt,t=new ft,i=new Sr(e),r=new Ar(e,t,i),s=new Za(e,t,r)){this.pathResolver=e,this.typeEmitter=t,this.geoEmitter=i,this.actionEmitter=r,this.scopedEmitter=s}emitResource(e,t,i=[],r){let s=t.getExposedName(),o=!!e.parent?.selfRoute,a=ce(s),n=r||(o?`${a}MeResource`:`${a}Resource`),l=i.filter(S=>!S.parent?.selfRoute),d=i.find(S=>!!S.parent?.selfRoute),p=l.length>0&&!o,m=this.emitResourceClass(n,a,e,t,d,p),h=p?this.scopedEmitter.emitScopedResourceClass(a,e,t,l):"",f=m.includes("path`")||h.includes("path`"),w=[this.resolveResourceImports(e,t,l,d,f),m];return p&&w.push(h),w.filter(Boolean).join(`
|
|
467
467
|
|
|
468
468
|
`)+`
|
|
469
469
|
`}emitBarrel(e){return Array.from(new Set(e.map(({expose:i,entity:r,explicitClassName:s})=>{let o=!!i.parent?.selfRoute,a=ce(r.getExposedName());return`export * from './${s||(o?`${a}MeResource`:`${a}Resource`)}.js'`}))).sort().join(`
|
|
@@ -473,19 +473,19 @@ Active records only are clustered; soft-deleted records are automatically exclud
|
|
|
473
473
|
*/`),a.push(`export class ${e} {`),a.push(" constructor("),a.push(" private readonly transport: HttpTransport,"),a.push(" private readonly pathParams: Record<string, string> = {}"),a.push(" ) {}"),s){let d=`${ce(this.scopedEmitter.resolveEntityExposedName(s,r))}MeResource`;a.push(""),a.push(" /** Navigates to the /me endpoint for current user session. */"),a.push(` public get me(): ${d} {`),a.push(` return new ${d}(this.transport, this.pathParams)`),a.push(" }")}if(o){let d=this.actionEmitter.resolveIdParamName(i);a.push(""),a.push(` /** Returns a scoped instance for a specific ${t} ID to access sub-resources. */`),a.push(` public scoped(id: string): Scoped${t}Resource {`),a.push(` return new Scoped${t}Resource(this.transport, { ...this.pathParams, ${d}: id })`),a.push(" }"),a.push(""),a.push(` /** Alias for \`scoped(id)\`. Returns a scoped instance for a specific ${t} ID. */`),a.push(` public byId(id: string): Scoped${t}Resource {`),a.push(" return this.scoped(id)"),a.push(" }")}let n=this.actionEmitter.getResourceName(i,r);a.push(""),a.push(" /** Retrieves the rate limit state for this resource or a specific action. */"),a.push(" public getRateLimit(action?: string): RateLimitState | undefined {"),a.push(` return this.transport.getRateLimits('${n}', action)`),a.push(" }");let l=this.actionEmitter.emitActionMethods(i,r,t);return l.length>0&&(a.push(""),a.push(l.join(`
|
|
474
474
|
|
|
475
475
|
`))),a.push("}"),a.join(`
|
|
476
|
-
`)}resolveResourceImports(e,t,i,r){let
|
|
477
|
-
`)}};var en=class{typeEmitter;schemaGen;constructor(e=new ft,t){this.typeEmitter=e,this.schemaGen=t??new Bt}emitEntityValidators(e,t){let i=ce(t.getExposedName()),r=this.typeEmitter.hasDifferentiatedInputFields(t),s=this.supportsPatchAction(e),o=[];return
|
|
476
|
+
`)}resolveResourceImports(e,t,i,r,s){let o=ce(t.getExposedName()),a=new Set,n=e.actions.some(I=>I.kind==="create"),l=e.actions.find(I=>I.kind==="update"),d=!!l?.allowedMethods?.includes("PUT"),p=!!l?.allowedMethods?.includes("PATCH");this.typeEmitter.hasDifferentiatedInputFields(t)?(n&&a.add(`${o}CreateInput`),d&&a.add(`${o}UpdateInput`)):(n||d)&&a.add(`${o}Input`),p&&a.add(`${o}PatchInput`);let h=e.actions.find(I=>I.kind==="read");h?.projection?.fields.length&&a.add(`${o}ReadProjected`);let f=e.actions.find(I=>I.kind==="list");f?.projection?.fields.length&&a.add(`${o}ListProjected`);let k=!!h?.projection?.fields.length,w=!!f?.projection?.fields.length;(!k&&(h||n||l!==void 0)||!w&&f)&&a.add(o);let E=[],A=!!h,_=n||l!==void 0,$=["HttpTransport","RateLimitState"];A&&$.push("ConditionalResult","ConditionalOptions"),_&&$.push("MutationOptions"),s?E.push(`import { path, type ${$.join(", type ")} } from '../transport.js'`):E.push(`import type { ${$.join(", ")} } from '../transport.js'`);let P=e.actions.some(I=>I.kind==="list"),j=e.actions.some(I=>I.kind==="search");P?E.push("import { listAll, type Page, type ListOptions, type ListAllOptions } from '../pagination.js'"):j&&E.push("import type { Page } from '../pagination.js'"),j&&E.push("import { SearchBuilder, type SearchRequestBody } from '../search.js'"),a.size>0&&E.push(`import type { ${Array.from(a).sort().join(", ")} } from '../types/${o}.js'`);let L=new Set;n&&L.add("assertCreateInput"),l&&(p&&L.add("assertPatchInput"),d&&L.add("assertUpdateInput")),L.size>0&&E.push(`import { ${Array.from(L).sort().join(", ")} } from '../validators/${o}Validator.js'`);for(let I of i){let R=this.scopedEmitter.resolveChildResourceClassName(I,t,e.api);E.push(`import { ${R} } from './${R}.js'`)}if(r){let I=`${ce(this.scopedEmitter.resolveEntityExposedName(r,t))}MeResource`;E.push(`import { ${I} } from './${I}.js'`)}return E.join(`
|
|
477
|
+
`)}};var en=class{typeEmitter;schemaGen;constructor(e=new ft,t){this.typeEmitter=e,this.schemaGen=t??new Bt}emitEntityValidators(e,t){let i=ce(t.getExposedName()),r=this.typeEmitter.hasDifferentiatedInputFields(t),s=this.supportsPatchAction(e),o=this.supportsUpdateAction(e),a=[];return a.push(this.emitImports(i,r,s,o)),r?(a.push(this.emitActionValidator(t,i,"create",`${i}CreateInput`)),o&&a.push(this.emitActionValidator(t,i,"update",`${i}UpdateInput`))):a.push(this.emitUnifiedValidator(t,i,o)),s&&a.push(this.emitActionValidator(t,i,"patch",`${i}PatchInput`)),a.filter(Boolean).join(`
|
|
478
478
|
|
|
479
479
|
`)+`
|
|
480
480
|
`}emitBarrel(e){let t=[],i=[...e].sort((s,o)=>{let a=ce(s.entity.getExposedName()),n=ce(o.entity.getExposedName());return a.localeCompare(n)}),r=new Set;for(let{entity:s}of i){let o=ce(s.getExposedName());r.has(o)||(r.add(o),t.push(`export * as ${o}Validator from './${o}Validator.js'`))}return t.join(`
|
|
481
481
|
`)+`
|
|
482
|
-
`}emitImports(e,t,i){let
|
|
483
|
-
`)}emitUnifiedValidator(e,t){let
|
|
484
|
-
`);return`${i}
|
|
482
|
+
`}emitImports(e,t,i,r=!0){let s=[];t?(s.push(`${e}CreateInput`),r&&s.push(`${e}UpdateInput`)):(s.push(`${e}Input`,`${e}CreateInput`),r&&s.push(`${e}UpdateInput`)),i&&s.push(`${e}PatchInput`);let o=[];return o.push("import { SdkValidationError, type ValidationResult, type ValidationErrorItem } from '../errors.js'"),o.push(`import type { ${s.sort().join(", ")} } from '../types/${e}.js'`),o.join(`
|
|
483
|
+
`)}emitUnifiedValidator(e,t,i=!0){let r=this.emitActionValidator(e,t,"create",`${t}Input`,"Input"),s=[`export function assertCreateInput(data: unknown): asserts data is ${t}CreateInput {`," assertInput(data)","}","export const validateCreateInput = validateInput"];return i&&s.push(`export function assertUpdateInput(data: unknown): asserts data is ${t}UpdateInput {`," assertInput(data)","}","export const validateUpdateInput = validateInput"),`${r}
|
|
485
484
|
|
|
486
|
-
${
|
|
485
|
+
${s.join(`
|
|
486
|
+
`)}`}emitActionValidator(e,t,i,r,s){let o=s??(i==="create"?"CreateInput":i==="update"?"UpdateInput":"PatchInput"),a=this.getAllowedProperties(e,i),n=this.getAllowedAssociations(e),l=[...a.map(p=>rt(p)),...n.map(p=>$t(p))],d=[];d.push("/**"),d.push(` * Validates data as ${r}. Throws SdkValidationError if invalid.`),d.push(" */"),d.push(`export function assert${o}(data: unknown): asserts data is ${r} {`),d.push(` const result = validate${o}(data)`),d.push(" if (!result.valid) {"),d.push(" throw new SdkValidationError(result.errors)"),d.push(" }"),d.push("}"),d.push(""),d.push("/**"),d.push(` * Validates data against the ${r} schema without throwing.`),d.push(" */"),d.push(`export function validate${o}(data: unknown): ValidationResult {`),d.push(" if (!data || typeof data !== 'object' || Array.isArray(data)) {"),d.push(" return {"),d.push(" valid: false,"),d.push(" errors: [{ field: '', message: 'Payload must be a non-null object', code: 'E_INVALID_PAYLOAD' }],"),d.push(" }"),d.push(" }"),d.push(""),d.push(" const record = data as Record<string, unknown>"),d.push(" const errors: ValidationErrorItem[] = []"),d.push(""),d.push(` const allowedFields = new Set<string>(${JSON.stringify(l)})`),d.push(" for (const key of Object.keys(record)) {"),d.push(" if (!allowedFields.has(key)) {"),d.push(" errors.push({ field: key, message: `Unknown field \"${key}\" is not allowed`, code: 'E_UNKNOWN_FIELD' })"),d.push(" }"),d.push(" }"),d.push("");for(let p of a){let m=rt(p),h=this.emitPropertyChecks(p,m,i);h.length>0&&(d.push(h.join(`
|
|
487
487
|
`)),d.push(""))}if(i!=="patch"){for(let p of n)if(p.required){let m=$t(p);d.push(` if (record['${m}'] === undefined || record['${m}'] === null) {`),d.push(` errors.push({ field: '${m}', message: 'Required association is missing', code: 'E_REQUIRED_FIELD' })`),d.push(" }")}d.push("")}return d.push(" return { valid: errors.length === 0, errors }"),d.push("}"),d.join(`
|
|
488
|
-
`)}emitPropertyChecks(e,t,i){let r=[],s=this.isRequiredOnAction(e,i),o=i==="patch";s&&(r.push(` if (record['${t}'] === undefined || record['${t}'] === null) {`),r.push(` errors.push({ field: '${t}', message: 'Field is required', code: 'E_REQUIRED_FIELD' })`),r.push(" }"));let a=[];if(a.push(...this.emitTypeCheck(e,t)),Array.isArray(e.schema?.enum)&&e.schema.enum.length>0){let n=JSON.stringify(e.schema.enum);a.push(` const allowedEnum = ${n}`),a.push(" if (!allowedEnum.includes(val as never)) {"),a.push(` errors.push({ field: '${t}', message: \`Value must be one of: \${allowedEnum.join(', ')}\`, code: 'E_INVALID_ENUM' })`),a.push(" }")}if(e.schema?.minimum!==void 0){let n=e.schema.minimum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must be at least ${n}', code: 'E_MIN_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must be at least ${n}', code: 'E_MIN_VALUE' })`),a.push(" }"))}if(e.schema?.maximum!==void 0){let n=e.schema.maximum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must not exceed ${n}', code: 'E_MAX_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must not exceed ${n}', code: 'E_MAX_VALUE' })`),a.push(" }"))}if(e.schema?.pattern){let n=JSON.stringify(e.schema.pattern);a.push(` if (typeof val === 'string' && !new RegExp(${n}).test(val)) {`),a.push(` errors.push({ field: '${t}', message: 'Value does not match required pattern', code: 'E_PATTERN_MISMATCH' })`),a.push(" }")}return a.length>0&&(r.push(` if (record['${t}'] !== undefined) {`),r.push(` const val = record['${t}']`),o?(r.push(" if (val !== null) {"),r.push(...a.map(n=>` ${n}`)),r.push(" }")):r.push(...a),r.push(" }")),r}emitTypeCheck(e,t){let i=[];if(e.multiple===!0)return i.push(" if (!Array.isArray(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an array', code: 'E_INVALID_TYPE' })`),i.push(" }"),i;switch(e.type){case"string":case"date":case"time":i.push(" if (typeof val !== 'string') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a string', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"number":i.push(" if (typeof val !== 'number' || Number.isNaN(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a valid number', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"boolean":i.push(" if (typeof val !== 'boolean') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a boolean', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"datetime":i.push(" if (typeof val !== 'string' && !(val instanceof Date)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an ISO date string or Date instance', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"json":i.push(" if (typeof val !== 'object' || val === null) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an object', code: 'E_INVALID_TYPE' })`),i.push(" }");break}return i}isRequiredOnAction(e,t){return!(t==="patch"||!e.required||e.schema?.defaultValue?.value!==void 0||t==="create"&&e.hasSemantic(g.PublicUniqueName))}getAllowedProperties(e,t){return Array.from(e.properties).filter(i=>!(i.readBinding("web")?.hidden||this.schemaGen.isSystemProperty(i)||i.readOnly===!0||t!=="create"&&i.immutable===!0))}getAllowedAssociations(e){return Array.from(e.associations).filter(t=>t.readBinding("web")?.hidden||this.schemaGen.isSystemAssociation(t)||t.readOnly===!0?!1:Array.from(t.listTargets()).length>0)}supportsPatchAction(e){return(Array.isArray(e)?e:[e]).some(i=>{let r=i.actions.find(s=>s.kind==="update");return!!(Array.isArray(r?.allowedMethods)&&r?.allowedMethods.includes("PATCH"))})}};var tn=class{emitClient(e,t){let i=t?.baseUrl,r=!!i,s=this.resolveRootExposures(e),o=this.hasFileUpload(e),a=this.hasVerification(e),n=[];if(n.push("import { HttpTransport } from './transport.js'"),n.push("import { AuthManager } from './auth.js'"),s.length>0){let d=s.map(({resourceClassName:p})=>p).sort().join(", ");n.push(`import { ${d} } from './resources/index.js'`)}o&&n.push("import { FileUploadHelper } from './files.js'"),a&&n.push("import { VerificationHelper } from './verification.js'"),n.push(""),n.push("/**"),n.push(" * Options for configuring the ApiClient instance."),n.push(" */"),n.push("export interface ApiClientOptions {"),n.push(" /**"),n.push(" * Base URL for all API requests."),r&&n.push(` * @default '${i}'`),n.push(" */"),n.push(` baseUrl${r?"?":""}: string`),n.push(" /** Logging verbosity for network activity. */"),n.push(" logLevel?: 'error' | 'warn' | 'info' | 'debug'"),n.push(" /** Retry configuration for transient network errors. */"),n.push(" retry?: {"),n.push(" maxRetries?: number"),n.push(" backoffMs?: number"),n.push(" statusCodes?: number[]"),n.push(" retryNonIdempotent?: boolean"),n.push(" }"),n.push(" /** Custom headers to apply to every outgoing HTTP request. */"),n.push(" headers?: Record<string, string>"),n.push(" /** Initial authentication bearer token. */"),n.push(" token?: string"),n.push(" /** Custom fetch implementation (e.g. for testing or Node environments without global fetch). */"),n.push(" fetch?: typeof fetch"),n.push("}"),n.push(""),n.push("/**"),n.push(" * Main API Client providing typed resource accessors and session management."),n.push(" *"),n.push(" * ### Use when:"),n.push(" * - Initializing the API SDK in your application."),n.push(" * - Accessing REST resources, authenticating, or uploading files."),n.push(" *"),n.push(" * ### Don't use when:"),n.push(" * - Performing direct unformatted HTTP requests."),n.push(" */"),n.push("export class ApiClient {"),n.push(" public readonly transport: HttpTransport"),n.push(" public readonly auth: AuthManager");for(let{propName:d,resourceClassName:p}of s)n.push(` public readonly ${d}: ${p}`);o&&n.push(" public readonly files: FileUploadHelper"),a&&n.push(" public readonly verification: VerificationHelper"),n.push("");let l=r?"options: ApiClientOptions = {}":"options: ApiClientOptions";n.push(` constructor(${l}) {`),n.push(" const transportOptions = {"),n.push(" ...options,"),r&&n.push(` baseUrl: options.baseUrl ?? '${i}',`),n.push(" }"),n.push(" this.transport = new HttpTransport(transportOptions)"),n.push(" this.auth = new AuthManager(this.transport)"),n.push(" this.transport.setAuthManager(this.auth)"),n.push(" if (options.token) {"),n.push(" this.auth.setToken(options.token)"),n.push(" }");for(let{propName:d,resourceClassName:p}of s)n.push(` this.${d} = new ${p}(this.transport)`);return o&&n.push(" this.files = new FileUploadHelper(this.transport)"),a&&n.push(" this.verification = new VerificationHelper(this.transport)"),n.push(" }"),n.push("}"),n.push(""),n.join(`
|
|
488
|
+
`)}emitPropertyChecks(e,t,i){let r=[],s=this.isRequiredOnAction(e,i),o=i==="patch";s&&(r.push(` if (record['${t}'] === undefined || record['${t}'] === null) {`),r.push(` errors.push({ field: '${t}', message: 'Field is required', code: 'E_REQUIRED_FIELD' })`),r.push(" }"));let a=[];if(a.push(...this.emitTypeCheck(e,t)),Array.isArray(e.schema?.enum)&&e.schema.enum.length>0){let n=JSON.stringify(e.schema.enum);a.push(` const allowedEnum = ${n}`),a.push(" if (!allowedEnum.includes(val as never)) {"),a.push(` errors.push({ field: '${t}', message: \`Value must be one of: \${allowedEnum.join(', ')}\`, code: 'E_INVALID_ENUM' })`),a.push(" }")}if(e.schema?.minimum!==void 0){let n=e.schema.minimum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must be at least ${n}', code: 'E_MIN_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must be at least ${n}', code: 'E_MIN_VALUE' })`),a.push(" }"))}if(e.schema?.maximum!==void 0){let n=e.schema.maximum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must not exceed ${n}', code: 'E_MAX_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must not exceed ${n}', code: 'E_MAX_VALUE' })`),a.push(" }"))}if(e.schema?.pattern){let n=JSON.stringify(e.schema.pattern);a.push(` if (typeof val === 'string' && !new RegExp(${n}).test(val)) {`),a.push(` errors.push({ field: '${t}', message: 'Value does not match required pattern', code: 'E_PATTERN_MISMATCH' })`),a.push(" }")}return a.length>0&&(r.push(` if (record['${t}'] !== undefined) {`),r.push(` const val = record['${t}']`),o?(r.push(" if (val !== null) {"),r.push(...a.map(n=>` ${n}`)),r.push(" }")):r.push(...a),r.push(" }")),r}emitTypeCheck(e,t){let i=[];if(e.multiple===!0)return i.push(" if (!Array.isArray(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an array', code: 'E_INVALID_TYPE' })`),i.push(" }"),i;switch(e.type){case"string":case"date":case"time":i.push(" if (typeof val !== 'string') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a string', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"number":i.push(" if (typeof val !== 'number' || Number.isNaN(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a valid number', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"boolean":i.push(" if (typeof val !== 'boolean') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a boolean', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"datetime":i.push(" if (typeof val !== 'string' && !(val instanceof Date)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an ISO date string or Date instance', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"json":i.push(" if (typeof val !== 'object' || val === null) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an object', code: 'E_INVALID_TYPE' })`),i.push(" }");break}return i}isRequiredOnAction(e,t){return!(t==="patch"||!e.required||e.schema?.defaultValue?.value!==void 0||t==="create"&&e.hasSemantic(g.PublicUniqueName))}getAllowedProperties(e,t){return Array.from(e.properties).filter(i=>!(i.readBinding("web")?.hidden||this.schemaGen.isSystemProperty(i)||i.readOnly===!0||t!=="create"&&i.immutable===!0))}getAllowedAssociations(e){return Array.from(e.associations).filter(t=>t.readBinding("web")?.hidden||this.schemaGen.isSystemAssociation(t)||t.readOnly===!0?!1:Array.from(t.listTargets()).length>0)}supportsPatchAction(e){return(Array.isArray(e)?e:[e]).some(i=>{let r=i.actions.find(s=>s.kind==="update");return!!(Array.isArray(r?.allowedMethods)&&r?.allowedMethods.includes("PATCH"))})}supportsUpdateAction(e){return(Array.isArray(e)?e:[e]).some(i=>i.actions.some(r=>r.kind==="update"))}};var tn=class{emitClient(e,t){let i=t?.baseUrl,r=!!i,s=this.resolveRootExposures(e),o=this.hasFileUpload(e),a=this.hasVerification(e),n=[];if(n.push("import { HttpTransport } from './transport.js'"),n.push("import { AuthManager } from './auth.js'"),s.length>0){let d=s.map(({resourceClassName:p})=>p).sort().join(", ");n.push(`import { ${d} } from './resources/index.js'`)}o&&n.push("import { FileUploadHelper } from './files.js'"),a&&n.push("import { VerificationHelper } from './verification.js'"),n.push(""),n.push("/**"),n.push(" * Options for configuring the ApiClient instance."),n.push(" */"),n.push("export interface ApiClientOptions {"),n.push(" /**"),n.push(" * Base URL for all API requests."),r&&n.push(` * @default '${i}'`),n.push(" */"),n.push(` baseUrl${r?"?":""}: string`),n.push(" /** Logging verbosity for network activity. */"),n.push(" logLevel?: 'error' | 'warn' | 'info' | 'debug'"),n.push(" /** Retry configuration for transient network errors. */"),n.push(" retry?: {"),n.push(" maxRetries?: number"),n.push(" backoffMs?: number"),n.push(" statusCodes?: number[]"),n.push(" retryNonIdempotent?: boolean"),n.push(" }"),n.push(" /** Custom headers to apply to every outgoing HTTP request. */"),n.push(" headers?: Record<string, string>"),n.push(" /** Initial authentication bearer token. */"),n.push(" token?: string"),n.push(" /** Custom fetch implementation (e.g. for testing or Node environments without global fetch). */"),n.push(" fetch?: typeof fetch"),n.push("}"),n.push(""),n.push("/**"),n.push(" * Main API Client providing typed resource accessors and session management."),n.push(" *"),n.push(" * ### Use when:"),n.push(" * - Initializing the API SDK in your application."),n.push(" * - Accessing REST resources, authenticating, or uploading files."),n.push(" *"),n.push(" * ### Don't use when:"),n.push(" * - Performing direct unformatted HTTP requests."),n.push(" */"),n.push("export class ApiClient {"),n.push(" public readonly transport: HttpTransport"),n.push(" public readonly auth: AuthManager");for(let{propName:d,resourceClassName:p}of s)n.push(` public readonly ${d}: ${p}`);o&&n.push(" public readonly files: FileUploadHelper"),a&&n.push(" public readonly verification: VerificationHelper"),n.push("");let l=r?"options: ApiClientOptions = {}":"options: ApiClientOptions";n.push(` constructor(${l}) {`),n.push(" const transportOptions = {"),n.push(" ...options,"),r&&n.push(` baseUrl: options.baseUrl ?? '${i}',`),n.push(" }"),n.push(" this.transport = new HttpTransport(transportOptions)"),n.push(" this.auth = new AuthManager(this.transport)"),n.push(" this.transport.setAuthManager(this.auth)"),n.push(" if (options.token) {"),n.push(" this.auth.setToken(options.token)"),n.push(" }");for(let{propName:d,resourceClassName:p}of s)n.push(` this.${d} = new ${p}(this.transport)`);return o&&n.push(" this.files = new FileUploadHelper(this.transport)"),a&&n.push(" this.verification = new VerificationHelper(this.transport)"),n.push(" }"),n.push("}"),n.push(""),n.join(`
|
|
489
489
|
`)}hasFileUpload(e){if(!e.domain)return!1;for(let t of e.exposes.values()){let i=e.domain.findEntity(t.entity.key);if(i){for(let r of i.properties)if(r.semantics.some(s=>s.id===g.FileURL||s.id===g.ImageURL))return!0}}return!1}hasVerification(e){if(!e.domain)return!1;for(let t of e.exposes.values()){let i=e.domain.findEntity(t.entity.key);if(i)for(let r of i.properties){let s=r.semantics.find(a=>a.id===g.Email);if(s&&((s.config||{}).requireVerification??!0))return!0;let o=r.semantics.find(a=>a.id===g.Phone);if(o&&((o.config||{}).requireVerification??!1))return!0}}return!1}resolveRootExposures(e){let t=[];for(let i of e.exposes.values()){if(i.parent)continue;let r=e.domain?.findEntity(i.entity.key);if(!r)continue;let o=`${ce(r.getExposedName())}Resource`,a=this.getClientPropertyName(i,r);t.push({expose:i,entity:r,propName:a,resourceClassName:o})}return t.sort((i,r)=>i.propName.localeCompare(r.propName))}getClientPropertyName(e,t){if(e.collectionPath){let i=e.collectionPath.split("/").filter(Boolean);if(i.length>0)return ht(i[i.length-1])}return ht(t.getExposedName())}};var rn=class{emitAuthManager(e){let t=e.authentication?.strategy==="UsernamePassword",{usernameField:i,passwordField:r}=this.resolveCredentialFields(e),s=[];return s.push("import { HttpTransport } from './transport.js'"),s.push(""),t&&(s.push("/**"),s.push(" * Credentials required to authenticate via username/password."),s.push(" */"),s.push("export interface LoginCredentials {"),s.push(" /** The user identifier. */"),s.push(` ${i}: string`),s.push(" /** The account password. */"),s.push(` ${r}: string`),s.push("}"),s.push("")),s.push("/**"),s.push(" * Response data returned from a successful authentication call."),s.push(" */"),s.push("export interface LoginResponse {"),s.push(" success: boolean"),s.push(" token?: string"),s.push("}"),s.push(""),s.push("/**"),s.push(" * Manages authentication lifecycle, bearer tokens, and session headers for the API client."),s.push(" *"),s.push(" * ### Use when:"),s.push(" * - Logging in, logging out, or inspecting authentication status."),s.push(" * - Providing authorization headers for HTTP requests."),s.push(" * - Restoring existing session tokens from persistent client storage."),s.push(" * ### Don't use when:"),s.push(" * - Managing database user records or hashing passwords."),s.push(" */"),s.push("export class AuthManager {"),s.push(" private token: string | null = null"),s.push(""),s.push(" constructor(private readonly transport: HttpTransport) {}"),s.push(""),t&&(s.push(" /**"),s.push(" * Authenticates with the API and stores the returned session token."),s.push(" *"),s.push(" * @param credentials Login credentials."),s.push(" * @returns Login response payload."),s.push(" */"),s.push(" public async login(credentials: LoginCredentials): Promise<LoginResponse> {"),s.push(" const response = await this.transport.request<{ data: LoginResponse }>("),s.push(" '/auth/login',"),s.push(" {"),s.push(" method: 'POST',"),s.push(" body: JSON.stringify(credentials),"),s.push(" }"),s.push(" )"),s.push(" const data = response?.data ?? { success: true }"),s.push(" if (data.token) {"),s.push(" this.token = data.token"),s.push(" }"),s.push(" return data"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Logs out of the API and removes the stored session token."),s.push(" */"),s.push(" public async logout(): Promise<void> {"),s.push(" try {"),s.push(" await this.transport.request('/auth/logout', { method: 'POST' })"),s.push(" } finally {"),s.push(" this.token = null"),s.push(" }"),s.push(" }"),s.push("")),s.push(" /**"),s.push(" * Checks whether an active authentication token is currently present."),s.push(" */"),s.push(" public isAuthenticated(): boolean {"),s.push(" return Boolean(this.token)"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Returns the current session token or null if not authenticated."),s.push(" */"),s.push(" public getToken(): string | null {"),s.push(" return this.token"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Manually sets or clears the active session token."),s.push(" */"),s.push(" public setToken(token: string | null): void {"),s.push(" this.token = token"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Returns authentication headers to include with outgoing requests."),s.push(" */"),s.push(" public getAuthHeaders(): Record<string, string> {"),s.push(" if (!this.token) {"),s.push(" return {}"),s.push(" }"),s.push(" return {"),s.push(" Authorization: `Bearer ${this.token}`,"),s.push(" }"),s.push(" }"),s.push("}"),s.push(""),s.join(`
|
|
490
490
|
`)}resolveCredentialFields(e){let t="username",i="password";if(e.user&&e.domain){let r=e.domain.findEntity(e.user.key);if(r){let s=Array.from(r.properties),o=s.find(n=>n.semantics.some(l=>l.id===g.Username||l.id===g.Email)),a=s.find(n=>n.semantics.some(l=>l.id===g.Password));o&&(t=rt(o)),a&&(i=rt(a))}}return{usernameField:t,passwordField:i}}};var sn=class{emitPagination(e){return(e&&typeof e=="object"&&"pagination"in e?e.pagination:e)?.kind==="offset"?this.emitOffsetPagination():this.emitCursorPagination()}emitOffsetPagination(){return`/**
|
|
491
491
|
* Envelope for offset/page-number based pagination responses.
|
|
@@ -685,6 +685,17 @@ export async function* listAll<T>(
|
|
|
685
685
|
}
|
|
686
686
|
`}};var on=class{emitTransport(){return`import { createApiError, ApiError } from './errors.js'
|
|
687
687
|
|
|
688
|
+
/**
|
|
689
|
+
* Tagged template literal for safely building URL paths with URL-encoded parameters.
|
|
690
|
+
*/
|
|
691
|
+
export function path(strings: TemplateStringsArray, ...values: unknown[]): string {
|
|
692
|
+
let result = strings[0]
|
|
693
|
+
for (let i = 0; i < values.length; i++) {
|
|
694
|
+
result += encodeURIComponent(String(values[i] ?? '')) + strings[i + 1]
|
|
695
|
+
}
|
|
696
|
+
return result
|
|
697
|
+
}
|
|
698
|
+
|
|
688
699
|
/**
|
|
689
700
|
* Retry policy options for transient network failures and rate limits.
|
|
690
701
|
*/
|
|
@@ -763,6 +774,27 @@ export interface RequestOptions extends Omit<RequestInit, 'body'> {
|
|
|
763
774
|
etag?: string
|
|
764
775
|
}
|
|
765
776
|
|
|
777
|
+
/**
|
|
778
|
+
* Options for mutating API resources (create, update, patch).
|
|
779
|
+
*/
|
|
780
|
+
export interface MutationOptions {
|
|
781
|
+
/**
|
|
782
|
+
* Whether to run client-side schema validation before sending the request.
|
|
783
|
+
* @default true
|
|
784
|
+
*/
|
|
785
|
+
validate?: boolean
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
/**
|
|
789
|
+
* Options for RFC 9110 conditional read requests (If-None-Match).
|
|
790
|
+
*/
|
|
791
|
+
export interface ConditionalOptions {
|
|
792
|
+
/**
|
|
793
|
+
* ETag value to match in the \`If-None-Match\` header.
|
|
794
|
+
*/
|
|
795
|
+
etag: string
|
|
796
|
+
}
|
|
797
|
+
|
|
766
798
|
/**
|
|
767
799
|
* Result of an RFC 9110 conditional HTTP request (ETag / 304 Not Modified).
|
|
768
800
|
*/
|
|
@@ -979,6 +1011,7 @@ export class HttpTransport {
|
|
|
979
1011
|
'read',
|
|
980
1012
|
'create',
|
|
981
1013
|
'update',
|
|
1014
|
+
'patch',
|
|
982
1015
|
'delete',
|
|
983
1016
|
'restore',
|
|
984
1017
|
'link',
|
|
@@ -1820,7 +1853,7 @@ export class SearchBuilder {
|
|
|
1820
1853
|
`}};var dn=class{model;typeEmitter=new ft;resourceEmitter=new Qa;validatorEmitter=new en(this.typeEmitter);clientEmitter=new tn;authEmitter=new rn;paginationEmitter=new sn;transportEmitter=new on;errorEmitter=new an;fileUploadEmitter=new nn;verificationEmitter=new cn;searchEmitter=new ln;constructor(e){this.model=e}generate(e={}){let t=this.model.domain;if(!t)throw new Error("ApiModel must have an attached DataDomain to generate an SDK");let i=new Map,r=[],s=new Map,o=new Map;for(let p of this.model.exposes.values()){if(p.parent?.key){let h=p.parent.key,f=s.get(h)??[];f.push(p),s.set(h,f)}let m=t.findEntity(p.entity.key);if(m){let h;if(p.parent?.key){let w=this.model.exposes.get(p.parent.key);w&&(h=t.findEntity(w.entity.key))}let f=this.resourceEmitter.resolveResourceClassName(p,m,h,this.model);r.push({expose:p,entity:m,explicitClassName:f});let k=o.get(m.key);k?k.exposes.push(p):o.set(m.key,{entity:m,exposes:[p]})}}let n=e.standalone??!1?"src/":"";for(let{entity:p,exposes:m}of o.values()){let h=ce(p.getExposedName()),f=this.typeEmitter.emitEntityTypes(m,p);i.set(`${n}types/${h}.ts`,f);let k=this.validatorEmitter.emitEntityValidators(m,p);i.set(`${n}validators/${h}Validator.ts`,k)}for(let{expose:p,entity:m,explicitClassName:h}of r){let f=s.get(p.key)??[],k=this.resourceEmitter.emitResource(p,m,f,h);i.set(`${n}resources/${h}.ts`,k)}i.set(`${n}types/index.ts`,this.typeEmitter.emitBarrel(r)),i.set(`${n}resources/index.ts`,this.resourceEmitter.emitBarrel(r)),i.set(`${n}validators/index.ts`,this.validatorEmitter.emitBarrel(r)),i.set(`${n}transport.ts`,this.transportEmitter.emitTransport()),i.set(`${n}errors.ts`,this.errorEmitter.emitErrors()),i.set(`${n}pagination.ts`,this.paginationEmitter.emitPagination(this.model.pagination)),i.set(`${n}auth.ts`,this.authEmitter.emitAuthManager(this.model)),i.set(`${n}search.ts`,this.searchEmitter.emitSearch());let l=this.clientEmitter.hasFileUpload(this.model);l&&i.set(`${n}files.ts`,this.fileUploadEmitter.emitFileUpload());let d=this.clientEmitter.hasVerification(this.model);return d&&i.set(`${n}verification.ts`,this.verificationEmitter.emitVerification()),i.set(`${n}client.ts`,this.clientEmitter.emitClient(this.model,{baseUrl:e.baseUrl})),i.set(`${n}index.ts`,this.emitMainIndex(l,d)),i}emitMainIndex(e,t){let i=[];return i.push("export * from './client.js'"),i.push("export * from './auth.js'"),i.push("export * from './transport.js'"),i.push("export * from './errors.js'"),i.push("export * from './pagination.js'"),i.push("export * from './search.js'"),i.push(""),i.push("export * as Types from './types/index.js'"),i.push("export * as Resources from './resources/index.js'"),i.push("export * as Validators from './validators/index.js'"),e&&i.push("export * from './files.js'"),t&&i.push("export * from './verification.js'"),i.push(""),i.join(`
|
|
1821
1854
|
`)}};import*as Gi from"node:fs/promises";import*as _i from"node:path";var pn=class{async write(e,t,i={}){let r=_i.resolve(e);if(await Gi.mkdir(r,{recursive:!0}),i.standalone??!1){let o=this.generatePackageJson(i);await Gi.writeFile(_i.join(r,"package.json"),o,"utf8");let a=this.generateTsConfigJson();await Gi.writeFile(_i.join(r,"tsconfig.json"),a,"utf8")}for(let[o,a]of t){let n=_i.join(r,o);await Gi.mkdir(_i.dirname(n),{recursive:!0}),await Gi.writeFile(n,a,"utf8")}}generatePackageJson(e){let t={};return e.packageName&&(t.name=e.packageName),t.version=e.version||"1.0.0",e.description&&(t.description=e.description),t.type="module",t.main="./dist/index.js",t.types="./dist/index.d.ts",t.exports={".":{types:"./dist/index.d.ts",import:"./dist/index.js"}},t.scripts={build:"tsc"},JSON.stringify(t,null,2)+`
|
|
1822
1855
|
`}generateTsConfigJson(){return JSON.stringify({compilerOptions:{target:"ES2022",module:"NodeNext",moduleResolution:"NodeNext",declaration:!0,declarationMap:!0,sourceMap:!0,strict:!0,skipLibCheck:!0,rootDir:"./src",outDir:"./dist"},include:["src/**/*"]},null,2)+`
|
|
1823
|
-
`}};var mn=class extends et{file;client;deploymentRecord;constructor(e,t,i,r=new Z,s=F()){super(t,i,r),this.file=e,this.client=s}async execute(){y.debug(`[api:sdk] Executing SDK generation. File=${this.file}, stdin=${this.options.stdin}`);try{this.validateInputParameters();let e=await this.loadApiModelSchema(),t=await this.resolveDataDomain(e),i=new Ei(e,t),r=await this.resolveBaseUrl(e),s=this.generateSdkFiles(i,r);await this.writeOutput(s)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}get shouldReadFromStdin(){return!!(this.options.stdin||this.file==="-")}get isLocalFile(){let e=this.file||this.options.file;return e?xi.existsSync(e)||e.includes("/")||e.includes("\\")||e.endsWith(".json"):!1}validateInputParameters(){this.options.deployment&&(this.options.stdin||this.file==="-")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --deployment and STDIN"}),process.exit(1)),this.options.deployment&&this.isLocalFile&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both a local file path and --deployment",detail:"--deployment resolves the API model directly from the cloud deployment."}),process.exit(1)),(this.file||this.options.file||this.options.id)&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),this.file&&(this.file.includes("/")||this.file.includes("\\")||this.file.endsWith(".json"))&&(xi.existsSync(this.file)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${un.resolve(this.file)}`}),process.exit(1))),this.options.standalone&&!this.options.packageName&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Package name is required when generating a standalone SDK package.",detail:"Specify --package-name <name> (e.g. --package-name @my-org/api-sdk)."}),process.exit(1))}async loadApiModelSchema(){return this.options.deployment?this.loadFromDeployment(this.options.deployment):this.shouldReadFromStdin?this.loadFromStdin():this.file&&xi.existsSync(this.file)?this.loadFromLocalFile(this.file):this.loadFromRemote()}async loadFromDeployment(e){let t=this.resolveOrgId();y.debug(`[api:sdk] Fetching deployment '${e}' in org '${t}'...`);let i=await this.client.deployments.read(t,e,{token:this.client.token});return this.deploymentRecord=i,i.apiId||(this.formatter.error({code:"CLI_ERR_API_FAILURE",message:`Deployment '${e}' does not have an attached API file ID.`}),process.exit(1)),this.validateDeploymentFileMatch(i),this.loadRemoteApiSchema(t,i.apiId)}validateDeploymentFileMatch(e){let t=[this.file,this.options.file,this.options.id].filter(Boolean);for(let i of t)i!==e.apiId&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`API file ID mismatch: provided '${i}', but deployment '${e.key}' is attached to API file '${e.apiId}'.`,detail:`Omit the file argument or pass '${e.apiId}'.`}),process.exit(1))}async loadFromStdin(){y.debug("[api:sdk] Reading API model schema from STDIN...");let e=await this.fileManager.readStdin(),t;try{t=JSON.parse(e)}catch(i){let r=i instanceof Error?i.message:String(i);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse schema JSON from STDIN: ${r}`}),process.exit(1)}return this.validateSchemaKind(t),t}loadFromLocalFile(e){let t=un.resolve(e);y.debug(`[api:sdk] Reading local API model file from path: ${t}`);let i;try{i=xi.readFileSync(t,"utf8")}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to read file at ${t}: ${o}`}),process.exit(1)}let r;try{r=JSON.parse(i)}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse JSON file at ${t}: ${o}`}),process.exit(1)}return this.validateSchemaKind(r),r}async loadFromRemote(){let e=this.resolveOrgId(),t=await this.resolveTargetFileId(e);return this.loadRemoteApiSchema(e,t)}async loadRemoteApiSchema(e,t){y.debug(`[api:sdk] Fetching file metadata for ID '${t}' in org '${e}'...`);let i=await this.fileManager.read(e,t);i.kind!==Yt&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File '${t}' is not an API model. The file kind is '${i.kind}', but expected '${Yt}'.`}),process.exit(1)),y.debug(`[api:sdk] Fetching media schema for API model ID '${t}'...`);let r=await this.fileManager.readMedia(e,t);return this.validateSchemaKind(r.media),r.media}async resolveTargetFileId(e){let t=this.options.file||this.options.id||(this.file&&!xi.existsSync(this.file)?this.file:void 0);return t||this.resolveFileId(e,"Select an API model file to generate SDK for:")}validateSchemaKind(e){(!e||typeof e!="object"||Array.isArray(e))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid API model schema. Expected a JSON object."}),process.exit(1));let t=e;t.kind!==ke&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${String(t.kind)}', but expected '${ke}'.`}),process.exit(1))}async resolveDataDomain(e){if(this.options.domain)return this.loadLocalDomain(this.options.domain);let t=e.dependencyList||[];return this.resolveCatalogDomain(t,e.info?.name||e.key)}loadLocalDomain(e){let t=un.resolve(e);y.debug(`[api:sdk] Loading local Data Domain schema from: ${t}`),xi.existsSync(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${t}`}),process.exit(1));let i;try{i=JSON.parse(xi.readFileSync(t,"utf8"))}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${o}`}),process.exit(1)}(!i||typeof i!="object"||Array.isArray(i))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid Data Domain schema. Expected a JSON object."}),process.exit(1));let r=i;return r.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid Data Domain schema. The media kind is '${String(r.kind)}', but expected '${Ee}'.`}),process.exit(1)),new Me(i,[],{readOnly:!0})}async resolveCatalogDomain(e,t){e.length===0&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`API model '${t}' does not have a data domain dependency attached. SDK generation requires an attached data domain.`}),process.exit(1)),y.debug(`[api:sdk] Resolving ${e.length} dependency from data catalog...`);let r=(await this.client.dataCatalog.listDependencies(e,{token:this.client.token})).data||[];r.length===0&&(this.formatter.error({code:"CLI_ERR_API_FAILURE",message:`Could not resolve data domain dependency for API model '${t}' from the data catalog. Ensure the data domain is published in the catalog.`}),process.exit(1));let s=e[0]?.key,o=r.find(a=>a.key===s)??r[0];return new Me(o,r,{readOnly:!0})}async resolveBaseUrl(e){if(this.options.baseUrl)return y.debug(`[api:sdk] Using explicit base URL: ${this.options.baseUrl}`),this.options.baseUrl;if(this.deploymentRecord)return this.extractBaseUri(this.deploymentRecord);if(process.stdout.isTTY&&!this.isLocalOnlyMode())return this.promptBaseUrlStrategy(e);y.debug("[api:sdk] No base URL specified. Consumers must provide baseUrl at SDK initialization.")}isLocalOnlyMode(){return!!(this.options.stdin||this.file&&xi.existsSync(this.file))}async promptBaseUrlStrategy(e){let t=await Ce("How should the SDK resolve the base URL?",[{name:"Select from a deployment",value:"deployment"},{name:"Enter a custom URL",value:"custom"},{name:"Skip \u2014 require at SDK initialization",value:"skip"}]);if(t==="deployment")return this.resolveBaseUrlFromDeploymentSelection(e);if(t==="custom"){let i=await pe("Enter the base URL:");if(!i){y.debug("[api:sdk] Empty base URL entered. SDK will require baseUrl at initialization.");return}return i}}async resolveBaseUrlFromDeploymentSelection(e){let t=this.resolveOrgId(),i=this.options.file||this.options.id||e.key;y.debug(`[api:sdk] Listing deployments for API '${i}' in org '${t}'...`);let s=((await this.client.deployments.apis.listDeployments(t,i,void 0,{token:this.client.token})).data||[]).filter(a=>a.status===Nr.Active&&a.baseUri);if(s.length===0){y.warn("[api:sdk] No active deployments with a base URI found. Skipping base URL injection."),console.error("Warning: No active deployments with a base URI found. Skipping base URL injection.");return}let o=await Ce("Select a deployment to read the base URL from:",s.map(a=>({name:`${a.env} ${a.version?`(${a.version})`:""} \u2014 ${a.baseUri}`,value:a})));return this.extractBaseUri(o)}extractBaseUri(e){if(!e.baseUri){y.warn(`[api:sdk] Deployment '${e.key}' does not have a base URI.`),console.error(`Warning: Deployment '${e.key}' does not have a base URI. SDK will require baseUrl at initialization.`);return}return y.debug(`[api:sdk] Resolved base URL from deployment: ${e.baseUri}`),e.baseUri}generateSdkFiles(e,t){return y.debug("[api:sdk] Generating SDK source files using SdkGenerator..."),new dn(e).generate(t?{baseUrl:t}:void 0)}async writeOutput(e){let t=un.resolve(this.options.output||"."),i=this.options.standalone??!1;y.debug(`[api:sdk] Writing SDK to: ${t} (standalone=${i}, files=${e.size})`),await new pn().write(t,e,{standalone:i,packageName:this.options.packageName}),this.formatter.success(`SDK generated successfully (${e.size} files) at ${t}`)}};function ip(c){let e=c.command("api").description("Manage API models");e.command("list").description("List API model files in an organization").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Filter by parent folder ID").action(async t=>{let i=new K({format:N.resolved.format});await new sa(t,i).execute()}),e.command("search [query]").description("Search API model files by name or keyword").option("--query <query...>","Search query keywords").option("--parent <parent>","Filter by parent folder ID").option("--limit <limit>","Maximum number of results to return",Yi).option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new na(t,i,r).execute()}),e.command("create").description("Create a new API model file record (and optionally upload API model schema media)").option("--name <name>","Name of the API model").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Parent folder ID").option("--media <path>","Local path to the API model schema JSON to upload").option("--stdin","Read API model schema content from STDIN").action(async t=>{let i=new K({format:N.resolved.format});await new oa(t,i).execute()}),e.command("read").description("Read API model file metadata or schema media content").option("--file <fid>","File ID of the API model").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--meta","Read file metadata (default)").option("--media","Read API model schema media content").action(async t=>{let i=new K({format:N.resolved.format});await new aa(t,i).execute()}),e.command("oas [file]").description("Generate an OpenAPI Specification (OAS 3.1) from an API model").option("--file <fid>","File ID of the API model").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--domain <path>","Path to local Data Domain schema file (optional override or for local models)").option("-o, --output <path>","Output file path (defaults to stdout)").option("--stdin","Read API model schema content from STDIN").option("--server <urls...>","Server URL(s) to include in the generated OpenAPI spec").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Ya(t,i,r).execute()}),e.command("sdk [file]").description("Generate a TypeScript client SDK from an API model").option("--file <fid>","File ID of the API model").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--domain <path>","Path to local Data Domain schema file (optional override or for local models)").option("-o, --output <path>","Output directory path (defaults to current working directory)").option("--stdin","Read API model schema content from STDIN").option("--standalone","Generate a standalone npm package with package.json and tsconfig.json").option("--package-name <name>","npm package name (required when --standalone is set)").option("--base-url <url>","Base URL to bake into the generated SDK client").option("--deployment <did>","Deployment ID to resolve the API model and base URL from").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new mn(t,i,r).execute()})}import Nn from"node:fs";import ap from"node:path";var gt=class{model;domain;report=[];cachedUserEntity;cachedOrgEntity;cachedProjectEntity;cachedUserSemantics;cachedOrgSemantics;constructor(e){this.model=e,this.domain=e.domain}addIssue(e){this.report.push(e)}addIssues(e){e.length>0&&this.report.push(...e)}getUserEntity(){return this.cachedUserEntity===void 0&&(this.cachedUserEntity=this.domain?tl(this.domain,this.model.user)??null:null),this.cachedUserEntity??void 0}getOrganizationEntity(){if(this.cachedOrgEntity===void 0)if(!this.domain)this.cachedOrgEntity=null;else{let e=Array.from(this.domain.listEntities({includeForeign:!0})).find(t=>t.hasSemantic(g.Organization));this.cachedOrgEntity=e??null}return this.cachedOrgEntity??void 0}getProjectEntity(){if(this.cachedProjectEntity===void 0)if(!this.domain)this.cachedProjectEntity=null;else{let e=Array.from(this.domain.listEntities({includeForeign:!0})).find(t=>t.hasSemantic(g.Project));this.cachedProjectEntity=e??null}return this.cachedProjectEntity??void 0}getUserSemantics(){if(this.cachedUserSemantics===void 0)if(!this.domain)this.cachedUserSemantics=null;else{let e=this.getUserEntity();this.cachedUserSemantics=As(this.domain,e)}return this.cachedUserSemantics??void 0}getOrganizationSemantics(){return this.cachedOrgSemantics===void 0&&(this.cachedOrgSemantics=this.domain?Es(this.domain):null),this.cachedOrgSemantics??void 0}findEntity(e,t){return this.domain?.findEntity(e,t)}findAssociation(e,t){return this.domain?.findAssociation(e,t)}hasSessionConfigured(){return!!this.model.session}isSessionPropertyConfigured(e){return this.model.session?.properties?this.model.session.properties.some(t=>t.key===e):!1}getConfiguredSessionPropertyKeys(){if(this.model.session)return new Set(this.model.session.properties?.map(e=>e.key).filter(Boolean)??[])}};function v(c,e){return`${c}_${e}`}function hn(c){let e=[];c.children.length===0&&e.push(c);for(let t of c.children)t instanceof qe&&e.push(...hn(t));return e}function Ps(c){return c.children.length===0?!1:c.style==="and"?c.children.some(e=>e instanceof qe?Ps(e):e.isIdentityConstraining):c.children.every(e=>e instanceof qe?Ps(e):e.isIdentityConstraining)}var fn=class{ruleType="matchUserRole";validate(e,t,i,r,s){let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},a=s.domain,n=["allowlist","denylist","minRole","maxRole"],l;if(a){let d=s.getUserSemantics(),p=d?.userEntity??s.getUserEntity();if(!p)s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match user role" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o});else if(!d?.roleProperty)s.addIssue({code:v("RULE","MATCH_USER_ROLE_MISSING_ROLE_PROPERTY"),message:`The User entity "${p.info.getLabel()}" has no property with the UserRole data semantic.`,suggestion:"Add a property with the UserRole semantic to the User entity to use role-based authorization.",severity:"error",context:o});else if(l=d.roleProperty,s.hasSessionConfigured()&&!s.isSessionPropertyConfigured(l.key)){let m=l.info.getLabel()??l.key;s.addIssue({code:v("RULE","USER_ROLE_NOT_IN_SESSION"),message:`The role property "${m}" used in the "Match user role" rule is not included in the session configuration properties.`,suggestion:"Add the role property to the session properties in the API Model session configuration.",severity:"error",context:o})}}if((!e.mode||!n.includes(e.mode))&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_INVALID_MODE"),message:`The "matchUserRole" access rule has an invalid or missing mode "${e.mode??""}". Valid modes are: allowlist, denylist, minRole, maxRole.`,suggestion:"Set the mode to one of: allowlist, denylist, minRole, or maxRole.",severity:"error",context:o}),e.roleMatch!==void 0&&e.roleMatch!=="any"&&e.roleMatch!=="all"&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_INVALID_ROLE_MATCH"),message:`The "matchUserRole" access rule has an invalid roleMatch "${e.roleMatch}". Valid values are: any, all.`,suggestion:'Set roleMatch to either "any" or "all", or omit it to use the default.',severity:"error",context:o}),e.mode==="allowlist")!e.allowed||!Array.isArray(e.allowed)?s.addIssue({code:v("RULE","MATCH_USER_ROLE_ALLOWLIST_MISSING_ALLOWED"),message:'The "matchUserRole" access rule is in allowlist mode, but no "allowed" list is specified.',suggestion:'Add an "allowed" list with the roles that should be permitted access.',severity:"error",context:o}):e.allowed.length===0&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_ALLOWLIST_EMPTY"),message:'The "matchUserRole" access rule has an empty "allowed" list. Access will be denied for all users.',suggestion:"Add at least one role to the allowed list, or remove this rule if all access should be denied.",severity:"warning",context:o});else if(e.mode==="denylist")!e.denied||!Array.isArray(e.denied)?s.addIssue({code:v("RULE","MATCH_USER_ROLE_DENYLIST_MISSING_DENIED"),message:'The "matchUserRole" access rule is in denylist mode, but no "denied" list is specified.',suggestion:'Add a "denied" list with the roles that should be blocked from access.',severity:"error",context:o}):e.denied.length===0&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_DENYLIST_EMPTY"),message:'The "matchUserRole" access rule has an empty "denied" list. All authenticated users will be granted access.',suggestion:"Add at least one role to the denied list to block specific roles, or replace this with an allowAuthenticated rule.",severity:"warning",context:o});else if(e.mode==="minRole"||e.mode==="maxRole"){let d=e.mode==="minRole",p=d?"minimumRole":"maximumRole",m=d?e.minimumRole:e.maximumRole,h=d?"minimum":"maximum";if((!m||typeof m!="string"||m.trim()==="")&&s.addIssue({code:v("RULE",d?"MATCH_USER_ROLE_MIN_ROLE_MISSING":"MATCH_USER_ROLE_MAX_ROLE_MISSING"),message:`The "matchUserRole" access rule is in ${e.mode} mode, but "${p}" is not specified.`,suggestion:`Specify the ${h} required role name in the "${p}" field.`,severity:"error",context:o}),a&&l){let f=l.schema?.enum,k=l.info.getLabel()??l.key;!f||!Array.isArray(f)||f.length===0?s.addIssue({code:v("RULE","MATCH_USER_ROLE_ENUM_REQUIRED"),message:`The role property "${k}" must have an enum defined with at least one role for "${e.mode}" mode.`,suggestion:"Define an enum on the UserRole property schema specifying roles in privilege order.",severity:"error",context:o}):m&&!f.includes(m)&&s.addIssue({code:v("RULE",d?"MATCH_USER_ROLE_MIN_ROLE_NOT_IN_ENUM":"MATCH_USER_ROLE_MAX_ROLE_NOT_IN_ENUM"),message:`The "${p}" value "${m}" does not exist in the UserRole enum. Valid roles are: ${f.join(", ")}.`,suggestion:"Choose a role name that exists in the UserRole enum. Remember that enum order is the privilege order \u2014 index 0 is least privileged.",severity:"error",context:o}),e.mode==="maxRole"&&l.multiple&&e.roleMatch!=="all"&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_MAX_ROLE_ANY_ON_MULTI"),message:`The "matchUserRole" access rule uses "maxRole" mode on a multi-role property without roleMatch: 'all'. Users holding a higher role will still be granted access if any of their other roles is at or below "${m}".`,suggestion:`Set roleMatch to "all" if you want all roles held by the user to be at or below "${m}", or keep roleMatch as "any" if matching any role is intended.`,severity:"warning",context:o})}}if(a&&l&&(e.mode==="allowlist"||e.mode==="denylist")){let d=l.schema?.enum;if(Array.isArray(d)){let p=e.mode==="allowlist"?e.allowed:e.denied,m=e.mode==="allowlist"?"allowed":"denied";if(Array.isArray(p))for(let h of p)d.includes(h)||s.addIssue({code:v("RULE","MATCH_USER_ROLE_INVALID_ROLE_VALUE"),message:`The role "${h}" in the "${m}" list does not exist in the UserRole enum.`,suggestion:`Remove "${h}" or correct it to a valid UserRole enum value: ${d.join(", ")}.`,severity:"warning",context:o})}}}};function Rs(c,e,t){if(!c||!c.parent)return!1;let i=t?.domain??e.domain;if(!i)return!1;let r=c.parent.key,s=new Set([c.key]);for(;r&&!s.has(r);){s.add(r);let o=e.exposes.get(r);if(!o)break;if(o.entity?.key&&(t?t.findEntity(o.entity.key,o.entity.domain):i.findEntity(o.entity.key,o.entity.domain))?.hasSemantic(g.Project))return!0;r=o.parent?.key}return!1}function gn(c,e,t){if(!c)return!1;let i=t?.domain??e.domain;return i?c.entity?.key&&(t?t.findEntity(c.entity.key,c.entity.domain):i.findEntity(c.entity.key,c.entity.domain))?.hasSemantic(g.Project)?!0:Rs(c,e,t):!1}function yn(c,e){let t=Array.from(c.withInheritedAssociations()).filter(i=>i.hasSemantic(g.ProjectMembers));if(e){let i=Array.from(e.withInheritedAssociations()).filter(o=>o.hasSemantic(g.ProjectMembers)),r=t.find(o=>o.targets.some(a=>a.key===e.key)&&!o.getSemantic(g.ProjectMembers)?.link)??t.find(o=>o.targets.some(a=>a.key===e.key));if(r)return r;let s=i.find(o=>o.targets.some(a=>a.key===c.key)&&!o.getSemantic(g.ProjectMembers)?.link)??i.find(o=>o.targets.some(a=>a.key===c.key));return s||void 0}if(t.length>0)return t.find(r=>!r.getSemantic(g.ProjectMembers)?.link)||t[0]}function bn(c,e,t){if(!c||!c.parent)return!1;let i=t?.domain??e.domain;if(!i)return!1;let r=c.parent.key,s=new Set([c.key]);for(;r&&!s.has(r);){s.add(r);let o=e.exposes.get(r);if(!o)break;if(o.entity?.key&&(t?t.findEntity(o.entity.key,o.entity.domain):i.findEntity(o.entity.key,o.entity.domain))?.hasSemantic(g.Organization))return!0;r=o.parent?.key}return!1}function rp(c,e,t){if(!c)return!1;let i=t?.domain??e.domain;return i?c.entity?.key&&(t?t.findEntity(c.entity.key,c.entity.domain):i.findEntity(c.entity.key,c.entity.domain))?.hasSemantic(g.Organization)?!0:bn(c,e,t):!1}function sp(c,e){let t=Array.from(c.withInheritedAssociations()).filter(i=>i.hasSemantic(g.OrganizationMembers));if(e){let i=Array.from(e.withInheritedAssociations()).filter(o=>o.hasSemantic(g.OrganizationMembers)),r=t.find(o=>o.targets.some(a=>a.key===e.key)&&!o.getSemantic(g.OrganizationMembers)?.link)??t.find(o=>o.targets.some(a=>a.key===e.key));if(r)return r;let s=i.find(o=>o.targets.some(a=>a.key===c.key)&&!o.getSemantic(g.OrganizationMembers)?.link)??i.find(o=>o.targets.some(a=>a.key===c.key));return s||void 0}if(t.length>0)return t.find(r=>!r.getSemantic(g.OrganizationMembers)?.link)||t[0]}var kn=class{ruleType="matchOrganizationRole";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},n=s.domain,l=n&&i?.entity?.key?s.findEntity(i.entity.key,i.entity.domain):void 0,d=l?l.info.getLabel():i?i.key:"ApiModel";if(e.roles&&e.roles.some(p=>typeof p!="string"||!p.trim())&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_INVALID_ROLES"),message:`[${d}]: The "matchOrganizationRole" access rule roles list contains invalid or empty role strings.`,suggestion:"Ensure all roles in the roles array are non-empty strings.",severity:"error",context:a}),t==="action"&&o?.kind==="create"&&!bn(i,r,s)&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_INVALID_ACTION_KIND"),message:`[${d}]: The "matchOrganizationRole" access rule cannot be used on a create action because the organization record does not exist yet.`,suggestion:"Remove matchOrganizationRole from create actions, or use allowAuthenticated instead.",severity:"error",context:a}),i&&!rp(i,r,s)&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_MISSING_ORGANIZATION_PATH"),message:`[${d}]: The "matchOrganizationRole" access rule requires the endpoint to be an Organization resource or nested under an Organization in the route hierarchy.`,suggestion:"Apply this rule only to Organization exposures or sub-resources nested under an Organization.",severity:"error",context:a}),n){let p=s.getUserEntity();p||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match organization role access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:a});let m=s.getOrganizationEntity();if(!m)s.addIssue({code:v("RULE","MISSING_ORGANIZATION_MODEL"),message:'The API specifies a "Match organization role access" rule, but no Organization entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the Organization semantic.",severity:"error",context:a});else{m.primaryKey()||s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_MISSING_PRIMARY_KEY"),message:`[${d}]: Organization entity "${m.info.getLabel()}" has no primary key defined. matchOrganizationRole requires the Organization entity to have a primary key.`,suggestion:"Add a primary key property to the Organization entity.",severity:"error",context:a});let f=sp(m,p),k;if(f?(f.multiple!==!0&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_MEMBERS_NOT_MULTIPLE"),message:`[${d}]: The OrganizationMembers association must have "multiple: true" to support many-to-many organization memberships.`,suggestion:"Set the association cardinality to multiple (array) on the OrganizationMembers association.",severity:"error",context:a}),k=Array.from(f.listProperties()).find(w=>w.hasSemantic(g.OrganizationRole)||w.hasSemantic(g.AssociationRole))):s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_NO_MEMBERS_ASSOC"),message:`[${d}]: The "matchOrganizationRole" access rule requires the Organization entity to have a many-to-many association with the OrganizationMembers semantic.`,suggestion:"Configure an OrganizationMembers association between the Organization entity and the User entity.",severity:"error",context:a}),k||(k=Array.from(m.withInheritedProperties()).find(w=>w.hasSemantic(g.OrganizationRole))||(p?Array.from(p.withInheritedProperties()).find(w=>w.hasSemantic(g.OrganizationRole)):void 0)),e.roles&&e.roles.length>0)if(!k)s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_NO_ROLE_PROPERTY"),message:`[${d}]: The "matchOrganizationRole" access rule specifies roles, but no property with the OrganizationRole semantic was found on the OrganizationMembers association.`,suggestion:"Add a property with the OrganizationRole semantic to the OrganizationMembers association.",severity:"error",context:a});else{let w=k.schema?.enum;if(w&&Array.isArray(w))for(let S of e.roles)w.includes(S)||s.addIssue({code:v("RULE","INVALID_ORGANIZATION_ROLE"),message:`Organization role "${S}" is not defined in the Organization role enum list.`,suggestion:`Select a valid role from: [${w.join(", ")}].`,severity:"warning",context:a})}if(l&&l.key!==m.key)if(l.hasSemantic(g.User))f||s.addIssue({code:v("RULE","ORGANIZATION_NOT_LINKED"),message:`[${l.info.getLabel()}]: The access rule is set to "Match organization role access", but the resource is not linked to the Organization entity.`,suggestion:"Establish an association between the Organization entity and this resource entity.",severity:"error",context:a});else{let w=Array.from(m.withInheritedAssociations()).filter(A=>A.targets.some(_=>_.key===l.key)),S=Array.from(l.withInheritedAssociations()).filter(A=>A.targets.some(_=>_.key===m.key));if(!(w.find(A=>A.hasSemantic(g.OrganizationResource))||S.find(A=>A.hasSemantic(g.OrganizationResource)))){let A=w[0]||S[0];if(A){let _=A.info.displayName||(A.info.name&&A.info.name!=="new_association"?A.info.name:A.key);s.addIssue({code:v("RULE","MISSING_ORGANIZATION_RESOURCE_SEMANTIC"),message:`[${l.info.getLabel()}]: Association "${_}" links Organization to "${l.info.getLabel()}", but is missing the OrganizationResource semantic annotation.`,suggestion:"Add the OrganizationResource semantic to the association so the runtime can resolve inherited organization access.",severity:"error",context:a})}else bn(i,r,s)||s.addIssue({code:v("RULE","ORGANIZATION_NOT_LINKED"),message:`[${l.info.getLabel()}]: The access rule is set to "Match organization role access", but the resource is not linked to the Organization entity.`,suggestion:"Establish an association between the Organization entity and this resource entity.",severity:"error",context:a})}}}}}};var vn=class{ruleType="matchProjectRole";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},n=s.domain,l=n&&i?.entity?.key?s.findEntity(i.entity.key,i.entity.domain):void 0,d=l?l.info.getLabel():i?i.key:"ApiModel";if((!e.roles||e.roles.length===0||e.roles.some(p=>typeof p!="string"||!p.trim()))&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MISSING_ROLES"),message:`[${d}]: The "matchProjectRole" access rule requires at least one role to be specified in "roles".`,suggestion:"Specify one or more allowed roles, or use matchProjectStakeholder for role-agnostic membership.",severity:"error",context:a}),t==="action"&&o?.kind==="create"&&!Rs(i,r,s)&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_INVALID_ACTION_KIND"),message:`[${d}]: The "matchProjectRole" access rule cannot be used on a create action because the project record does not exist yet.`,suggestion:"Remove matchProjectRole from create actions, or use allowAuthenticated instead.",severity:"error",context:a}),i&&!gn(i,r,s)&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MISSING_PROJECT_PATH"),message:`[${d}]: The "matchProjectRole" access rule requires the endpoint to be a Project resource or nested under a Project in the route hierarchy.`,suggestion:"Apply this rule only to Project exposures or sub-resources nested under a Project.",severity:"error",context:a}),n){let p=s.getUserEntity();p||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match project role access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:a});let m=s.getProjectEntity();if(!m)s.addIssue({code:v("RULE","MISSING_PROJECT_MODEL"),message:'The API specifies a "Match project role access" rule, but no Project entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the Project semantic.",severity:"error",context:a});else{m.primaryKey()||s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MISSING_PRIMARY_KEY"),message:`[${d}]: Project entity "${m.info.getLabel()}" has no primary key defined. matchProjectRole requires the Project entity to have a primary key.`,suggestion:"Add a primary key property to the Project entity.",severity:"error",context:a});let f=yn(m,p);if(!f)s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_NO_MEMBERS_ASSOC"),message:`[${d}]: The "matchProjectRole" access rule requires the Project entity to have a many-to-many association with the ProjectMembers semantic.`,suggestion:"Configure a ProjectMembers association between the Project entity and the User entity.",severity:"error",context:a});else{f.multiple!==!0&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MEMBERS_NOT_MULTIPLE"),message:`[${d}]: The ProjectMembers association must have "multiple: true" to support many-to-many project memberships.`,suggestion:"Set the association cardinality to multiple (array) on the ProjectMembers association.",severity:"error",context:a});let k=Array.from(f.listProperties()).find(w=>w.hasSemantic(g.ProjectRole));if(!k)s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_NO_ROLE_PROPERTY"),message:`[${d}]: The "matchProjectRole" access rule requires the ProjectMembers association to have a property with the ProjectRole semantic.`,suggestion:"Add a property with the ProjectRole semantic to the ProjectMembers association.",severity:"error",context:a});else if(e.roles&&e.roles.length>0){let w=k.schema?.enum;if(w&&Array.isArray(w))for(let S of e.roles)w.includes(S)||s.addIssue({code:v("RULE","INVALID_PROJECT_ROLE"),message:`Project role "${S}" is not defined in the Project role enum list.`,suggestion:`Select a valid role from: [${w.join(", ")}].`,severity:"warning",context:a})}}}}}};var wn=class{ruleType="matchProjectStakeholder";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},n=s.domain,l=n&&i?.entity?.key?s.findEntity(i.entity.key,i.entity.domain):void 0,d=l?l.info.getLabel():i?i.key:"ApiModel";if(t==="action"&&o?.kind==="create"&&!Rs(i,r,s)&&s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_INVALID_ACTION_KIND"),message:`[${d}]: The "matchProjectStakeholder" access rule cannot be used on a create action because the project record does not exist yet.`,suggestion:"Remove matchProjectStakeholder from create actions, or use allowAuthenticated instead.",severity:"error",context:a}),i&&!gn(i,r,s)&&s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_MISSING_PROJECT_PATH"),message:`[${d}]: The "matchProjectStakeholder" access rule requires the endpoint to be a Project resource or nested under a Project in the route hierarchy.`,suggestion:"Apply this rule only to Project exposures or sub-resources nested under a Project.",severity:"error",context:a}),n){let p=s.getUserEntity();p||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match project stakeholder access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:a});let m=s.getProjectEntity();if(!m)s.addIssue({code:v("RULE","MISSING_PROJECT_MODEL"),message:'The API specifies a "Match project stakeholder access" rule, but no Project entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the Project semantic.",severity:"error",context:a});else{m.primaryKey()||s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_MISSING_PRIMARY_KEY"),message:`[${d}]: Project entity "${m.info.getLabel()}" has no primary key defined. matchProjectStakeholder requires the Project entity to have a primary key.`,suggestion:"Add a primary key property to the Project entity.",severity:"error",context:a});let f=yn(m,p);f?f.multiple!==!0&&s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_MEMBERS_NOT_MULTIPLE"),message:`[${d}]: The ProjectMembers association must have "multiple: true" to support many-to-many project memberships.`,suggestion:"Set the association cardinality to multiple (array) on the ProjectMembers association.",severity:"error",context:a}):s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_NO_MEMBERS_ASSOC"),message:`[${d}]: The "matchProjectStakeholder" access rule requires the Project entity to have a many-to-many association with the ProjectMembers semantic.`,suggestion:"Configure a ProjectMembers association between the Project entity and the User entity.",severity:"error",context:a})}}}};var Sn=class{ruleType="matchEmailDomain";validate(e,t,i,r,s){let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(s.domain){let n=s.getUserEntity();if(!n)s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match email domain" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o});else{let l=Array.from(n.withInheritedProperties()).filter(d=>d.hasSemantic(g.Email));if(l.length===0)s.addIssue({code:v("RULE","MISSING_EMAIL_SEMANTIC"),message:`The access rule is set to "Match email domain", but the User entity "${n.info.getLabel()}" has no property with the Email data semantic.`,suggestion:'Go to the Data Modeler and add the "Email" semantic to the email property on the User entity.',severity:"error",context:o});else if(l.length>1){let d=l.map(p=>`"${p.info.name||p.key}"`).join(", ");s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_MULTIPLE_PROPERTIES"),message:`[${n.info.getLabel()}]: The User entity has multiple properties with the Email semantic (${d}). The "Match email domain" access rule requires exactly one Email property on the User entity to avoid ambiguous resolution.`,suggestion:`Ensure only one property on "${n.info.getLabel()}" carries the Email semantic.`,severity:"error",context:o})}else{let d=l[0];s.hasSessionConfigured()&&!s.isSessionPropertyConfigured(d.key)&&s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_NOT_IN_SESSION"),message:`The email property "${d.info.getLabel()}" required by the "Match email domain" rule is not included in the session configuration properties.`,suggestion:"Add the email property to the session properties in the API Model session configuration.",severity:"error",context:o}),e.requireVerified!==!1&&((d.getSemantic(g.Email)?.config?.requireVerification??va.requireVerification??!0)||s.addIssue({code:v("RULE","EMAIL_VERIFICATION_MISMATCH"),message:`The "Match email domain" access rule requires verified email addresses (requireVerified: true), but the Email data semantic on property "${d.info.getLabel()}" has email verification disabled (requireVerification: false).`,suggestion:"Enable email verification in the Email semantic configuration on the User entity, or set requireVerified to false on the access rule.",severity:"error",context:o}))}}}if(!e.domains||e.domains.length===0)s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_EMPTY_DOMAINS"),message:'The "Match email domain" access rule has no allowed email domains specified.',suggestion:'Specify at least one domain name (e.g., "example.com") in the rule configuration.',severity:"error",context:o});else for(let n of e.domains){if(!n||typeof n!="string"||n.trim()===""){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:'The "Match email domain" access rule contains an empty domain pattern.',suggestion:'Remove the empty domain entry or specify a valid domain (e.g., "example.com").',severity:"error",context:o});continue}let l=n.trim();if(l.startsWith("@")){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Domain pattern "${n}" cannot start with "@". Specify the domain name directly (e.g., "${l.slice(1)}").`,suggestion:`Change "${n}" to "${l.slice(1)}".`,severity:"error",context:o});continue}if(l.startsWith("http://")||l.startsWith("https://")){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Domain pattern "${n}" cannot include a URL protocol. Specify only the domain name.`,suggestion:`Remove the protocol prefix from "${n}".`,severity:"error",context:o});continue}if(/\s/.test(l)){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Domain pattern "${n}" contains invalid whitespace characters.`,suggestion:"Remove spaces from the domain pattern.",severity:"error",context:o});continue}if(l.includes("*")&&(!l.startsWith("*.")||l==="*."||l.slice(2).includes("*"))){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Wildcard domain pattern "${n}" is invalid. Wildcards must strictly follow the prefix format "*.example.com".`,suggestion:'Use the wildcard format "*.example.com" or specify the exact domain name.',severity:"error",context:o});continue}}}};var An=class{ruleType="relationalResourceOwner";validate(e,t,i,r,s,o){if(!i)return;let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!s.domain)return;let l=i.entity.key,d=s.findEntity(l,i.entity.domain),p=d?d.info.getLabel():i.key;if(i.isRoot||!i.parent){s.addIssue({code:v("RULE","RELATIONAL_OWNER_NO_PARENT"),message:`[${p}]: relationalResourceOwner cannot be used on a root endpoint. Either nest this entity under a parent with User or ResourceOwnerIdentifier, or use matchResourceOwner if this entity has a direct owner FK.`,suggestion:"Nest this entity under a parent with User or ResourceOwnerIdentifier, or use matchResourceOwner if this entity has a direct owner FK.",severity:"error",context:a});return}let m=i.parent.key,h=new Set([i.key]),f,k;for(;m&&!h.has(m);){h.add(m);let S=r.exposes.get(m);if(!S)break;let E=s.findEntity(S.entity.key,S.entity.domain);if(E){let A=E.hasSemantic(g.User),_;if(!A){for(let O of E.withInheritedAssociations())if(O.hasSemantic(g.ResourceOwnerIdentifier)){_=O;break}}if(A||_)if(!!!(S.resourcePath?.includes("{")||S.parent?.selfRoute))k||(k={parentExposure:S,parentEntity:E});else{A?f={kind:"user",parentExposure:S,parentEntity:E}:_&&(f={kind:"assoc",parentExposure:S,parentEntity:E,assoc:_});break}}m=S.parent?.key}if(!f){if(k){s.addIssue({code:v("RULE","RELATIONAL_OWNER_PARENT_MISSING_PARAMETER"),message:`[${p}]: Ancestor entity "${k.parentEntity.info.getLabel()}" carries User ownership semantics, but its exposed route "${k.parentExposure.resourcePath}" has no route path parameter (e.g. "{id}"). The relationalResourceOwner rule requires a parent URL parameter.`,suggestion:`Add a path parameter to "${k.parentExposure.resourcePath}" (e.g. "/{id}"), or configure it as a selfRoute.`,severity:"error",context:a});return}s.addIssue({code:v("RULE","RELATIONAL_OWNER_NO_QUALIFYING_PARENT"),message:`[${p}]: relationalResourceOwner found no qualifying parent entity in the exposure hierarchy. A parent entity must have User semantic or a ResourceOwnerIdentifier association.`,suggestion:"Ensure at least one ancestor entity in the exposure hierarchy has the User semantic or an association with the ResourceOwnerIdentifier semantic.",severity:"error",context:a});return}if(f.parentEntity.primaryKey()||s.addIssue({code:v("RULE","RELATIONAL_OWNER_PARENT_MISSING_PRIMARY_KEY"),message:`[${p}]: Qualifying parent entity "${f.parentEntity.info.getLabel()}" has no primary key. relationalResourceOwner requires the qualifying parent entity to have a primary key property.`,suggestion:`Add a primary key property to "${f.parentEntity.info.getLabel()}".`,severity:"error",context:a}),f.kind==="assoc"){let S=f.assoc,E=S.info.displayName||S.info.name||S.key;Array.from(S.listTargets()).some(O=>O.hasSemantic(g.User))||s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NO_USER_TARGET"),message:`[${p}]: Ownership association "${E}" on qualifying parent "${f.parentEntity.info.getLabel()}" has no User-semantic target. ResourceOwnerIdentifier must point to the User entity.`,suggestion:"Ensure the target entity of the association carries the User semantic.",severity:"error",context:a}),(S.multiple||S.isManyToMany())&&s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NOT_SINGLE"),message:`[${p}]: Ownership association "${E}" on qualifying parent "${f.parentEntity.info.getLabel()}" cannot have multiple targets or be many-to-many. The association must be a direct single reference to the User entity.`,suggestion:"Configure the association to be a single direct reference to the User entity (multiple: false).",severity:"error",context:a})}if(f.kind==="user"&&d&&(t==="action"&&o&&(o.kind==="list"||o.kind==="search")||t==="exposure"&&(i.actions?.some(E=>E.kind==="list"||E.kind==="search")??!1))){let E;for(let A of d.withInheritedAssociations())if(A.hasSemantic(g.ResourceOwnerIdentifier)){E=A;break}if(E)Array.from(E.listTargets()).some(O=>O.hasSemantic(g.User))||s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NO_USER_TARGET"),message:`[${p}]: Child ownership association "${E.info.getLabel()}" has no User-semantic target. ResourceOwnerIdentifier must point to the User entity.`,suggestion:"Ensure the target entity of the association carries the User semantic.",severity:"error",context:a}),(E.multiple||E.isManyToMany())&&s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NOT_SINGLE"),message:`[${p}]: Child ownership association "${E.info.getLabel()}" cannot have multiple targets or be many-to-many. The association must be a direct single reference to the User entity.`,suggestion:"Configure the association to be a single direct reference to the User entity (multiple: false).",severity:"error",context:a});else{let A=t==="action"&&o?`action "${o.kind}"`:"collection operations";s.addIssue({code:v("RULE","RELATIONAL_OWNER_USER_PARENT_MISSING_CHILD_OWNER_ASSOC"),message:`[${p}]: relationalResourceOwner on ${A} under a User parent segment requires "${p}" to have an association annotated with SemanticType.ResourceOwnerIdentifier pointing to the User entity.`,suggestion:`Add an association annotated with ResourceOwnerIdentifier pointing to the User entity on "${p}", or use matchResourceOwner.`,severity:"error",context:a})}}}};var En=class{ruleType="matchResourceOwner";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(!s.domain||!i?.entity?.key)return;let l=i.entity.key,d=s.findEntity(l,i.entity.domain);if(!d)return;let p=d.info.getLabel();if(e.target!=="user-entity"&&e.target!=="association"){s.addIssue({code:v("RULE","INVALID_TARGET"),message:`[${p}]: Invalid matchResourceOwner target "${e.target??"(missing)"}". Target must be either "user-entity" or "association".`,suggestion:'Set target to "association" (default) or "user-entity".',severity:"error",context:{...a,property:"target"}});return}d.primaryKey()||s.addIssue({code:v("RULE","RESOURCE_OWNER_MISSING_PRIMARY_KEY"),message:`[${p}]: Entity "${p}" has no primary key defined. The "matchResourceOwner" rule requires the entity to have a primary key.`,suggestion:`Add a primary key property to entity "${p}".`,severity:"error",context:a}),t==="action"&&o?.kind==="create"&&s.addIssue({code:v("RULE","INVALID_ACTION_FOR_OWNERSHIP"),message:`[${p}]: The "matchResourceOwner" access rule cannot be evaluated on a "create" action because the resource does not exist yet at the time of authorization.`,suggestion:"Use relationalResourceOwner to secure create actions via a parent entity, or restrict this rule to read, update, and delete actions only.",severity:"error",context:a});let h=["read","update","delete","link","unlink"],f=t==="action"&&o&&h.includes(o.kind),k=t==="exposure"&&i.actions?.some(w=>h.includes(w.kind));if((f||k)&&!i.resourcePath?.includes("{")&&!i.parent?.selfRoute){let w=f?`action "${o?.kind}"`:"single-resource operations";s.addIssue({code:v("RULE","MISSING_PATH_PARAMETER_FOR_OWNERSHIP"),message:`[${p}]: The "matchResourceOwner" rule on ${w} requires a route path parameter (e.g. "{id}"), but the resource path "${i.resourcePath}" has none.`,suggestion:"Add a path parameter to the resource path, or configure the exposure as a selfRoute if it represents the current user.",severity:"error",context:a})}if(e.target==="user-entity")d.hasSemantic(g.User)||s.addIssue({code:v("RULE","INVALID_USER_ENTITY_TARGET"),message:`[${p}]: Target is set to "user-entity", but the entity itself does not represent the User.`,suggestion:'Change target to "association" or add User semantic to this entity.',severity:"error",context:{...a,property:"target"}});else{if(!e.association||!e.association.key){s.addIssue({code:v("RULE","MISSING_OWNERSHIP_ASSOCIATION"),message:`[${p}]: The access rule is set to "Match resource owner", but no ownership association is specified.`,suggestion:"Select an association on this entity that links to the User entity, or use relationalResourceOwner for inherited parent ownership.",severity:"error",context:{...a,property:"association"}});return}let w=e.association.key,S=e.association.domain,E=s.findAssociation(w,S),A=Array.from(d.withInheritedAssociations()),_=E?A.find(L=>L.key===E.key):A.find(L=>L.key===w);if(!_){s.addIssue({code:v("RULE","INVALID_OWNERSHIP_ASSOCIATION"),message:`[${p}]: The ownership association "${w}" does not exist on this entity.`,suggestion:"Select an association on this entity that links to the User entity, or use relationalResourceOwner for inherited parent ownership.",severity:"error",context:{...a,property:"association"}});return}let O=_.info.displayName||_.info.name||_.key;(_.multiple||_.isManyToMany())&&s.addIssue({code:v("RULE","OWNERSHIP_ASSOCIATION_NOT_SINGLE"),message:`[${p}]: Ownership association "${O}" cannot have multiple targets or be many-to-many. The association must be a direct single reference (N:1 or 1:1) to the User entity.`,suggestion:"Configure the association to be a single direct reference to the User entity (multiple: false).",severity:"error",context:{...a,property:"association"}});let j=Array.from(_.listTargets()).find(L=>L.hasSemantic(g.User));j?j.primaryKey()||s.addIssue({code:v("RULE","RESOURCE_OWNER_USER_MISSING_PRIMARY_KEY"),message:`[${p}]: User entity "${j.info.getLabel()}" referenced by ownership association "${O}" has no primary key.`,suggestion:`Add a primary key property to the User entity "${j.info.getLabel()}".`,severity:"error",context:{...a,property:"association"}}):s.addIssue({code:v("RULE","OWNERSHIP_ASSOCIATION_NO_USER_TARGET"),message:`[${p}]: Ownership association "${O}" has no User-semantic target. ResourceOwnerIdentifier must point to the User entity.`,suggestion:"Ensure the target entity of the association carries the User semantic.",severity:"error",context:{...a,property:"association"}})}}};var _n=class{ruleType="matchResourceAttribute";validate(e,t,i,r,s){if(!i?.entity?.key)return;let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!s.domain)return;let n=s.findEntity(i.entity.key,i.entity.domain);if(!n)return;let l=n.info.getLabel();if(e.attribute&&e.attribute.trim()){let h=Array.from(n.withInheritedProperties()).find(f=>f.key===e.attribute);h?h.multiple===!0&&s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_ARRAY_PROPERTY_UNSUPPORTED"),message:`[${l}]: Property "${h.info.getLabel()}" is multi-valued (array), which is not supported by matchResourceAttribute.`,suggestion:"Use a scalar property on the entity, or evaluate associations via matchAssociation.",severity:"error",context:o}):s.addIssue({code:v("RULE","INVALID_RESOURCE_ATTRIBUTE"),message:`[${l}]: The resource attribute property "${e.attribute}" does not exist.`,suggestion:"Select a valid property on the entity.",severity:"error",context:o})}else s.addIssue({code:v("RULE","MISSING_RESOURCE_ATTRIBUTE"),message:`[${l}]: The access rule is set to "Match resource attribute", but no attribute is specified.`,suggestion:"Specify a property on the entity to match against.",severity:"error",context:o});let d=zi.isArrayOperator(e.operator),p=zi.isScalarOperator(e.operator);e.operator?!d&&!p?s.addIssue({code:v("RULE","INVALID_RESOURCE_ATTRIBUTE_OPERATOR"),message:`[${l}]: The operator "${e.operator}" is not a valid resource attribute operator.`,suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o}):d?Array.isArray(e.values)?e.values.length===0&&s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_EMPTY_ARRAY"),message:`[${l}]: The "${e.operator}" operator requires at least one value in the array.`,suggestion:"Specify at least one value to match against in the array.",severity:"error",context:o}):s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_ARRAY_REQUIRED"),message:`[${l}]: The "${e.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:o}):e.value===void 0||e.value===null?s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_VALUE_REQUIRED"),message:`[${l}]: The "${e.operator}" operator requires a scalar value in "value".`,suggestion:'Provide a scalar value (string, number, or boolean) in the "value" property to match against.',severity:"error",context:o}):(Array.isArray(e.value)||typeof e.value=="object"&&e.value!==null)&&s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_SCALAR_REQUIRED"),message:`[${l}]: The "${e.operator}" operator does not accept array or object values.`,suggestion:'Provide a single scalar value (string, number, or boolean) in the "value" property, or switch to the "in" or "notIn" operator.',severity:"error",context:o}):s.addIssue({code:v("RULE","INVALID_RESOURCE_ATTRIBUTE_OPERATOR"),message:`[${l}]: The access rule is missing a comparison operator.`,suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o})}};var xn=class{ruleType="matchUserProperty";validate(e,t,i,r,s){let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(s.domain){let d=s.getUserEntity();if(!d)s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match user property" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o});else if(!e.property||e.property.trim()==="")s.addIssue({code:v("RULE","MISSING_USER_PROPERTY"),message:'The access rule is set to "Match user property", but no property is specified.',suggestion:"Specify a property on the User entity to match against.",severity:"error",context:o});else{let m=Array.from(d.withInheritedProperties()).find(h=>h.key===e.property);if(!m)s.addIssue({code:v("RULE","INVALID_USER_PROPERTY"),message:`The user property "${e.property}" does not exist on the User entity "${d.info.getLabel()}".`,suggestion:"Select a valid property on the User entity.",severity:"error",context:o});else if(m.multiple&&s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_MULTI_VALUED"),message:`The user property "${m.info.getLabel()}" is multi-valued (an array). The "matchUserProperty" rule only supports single-valued properties.`,suggestion:"Select a scalar user property, or use matchUserRole for multi-valued role properties.",severity:"error",context:o}),s.hasSessionConfigured()&&!s.isSessionPropertyConfigured(e.property)){let h=m.info.getLabel()??e.property;s.addIssue({code:v("RULE","USER_PROPERTY_NOT_IN_SESSION"),message:`The user property "${h}" used in the "Match user property" rule is not included in the session configuration properties.`,suggestion:"Add the property to the session properties in the API Model session configuration.",severity:"error",context:o})}}}let n=Vi.isArrayOperator(e.operator),l=Vi.isScalarOperator(e.operator);e.operator?!n&&!l?s.addIssue({code:v("RULE","INVALID_USER_PROPERTY_OPERATOR"),message:`The operator "${e.operator}" is not a valid user property operator.`,suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o}):n?Array.isArray(e.values)?e.values.length===0&&s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_EMPTY_ARRAY"),message:`The "${e.operator}" operator requires at least one value in the array.`,suggestion:"Specify at least one value to match against in the array.",severity:"error",context:o}):s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_ARRAY_REQUIRED"),message:`The "${e.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:o}):e.value===void 0||e.value===null?s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_VALUE_REQUIRED"),message:`The "${e.operator}" operator requires a scalar value in "value".`,suggestion:'Provide a scalar value (string, number, or boolean) in the "value" property to match against.',severity:"error",context:o}):(Array.isArray(e.value)||typeof e.value=="object"&&e.value!==null)&&s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_SCALAR_REQUIRED"),message:`The "${e.operator}" operator does not accept array or object values.`,suggestion:'Provide a single scalar value (string, number, or boolean) in the "value" property, or switch to the "in" or "notIn" operator.',severity:"error",context:o}):s.addIssue({code:v("RULE","INVALID_USER_PROPERTY_OPERATOR"),message:"The access rule is missing a comparison operator.",suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o})}};var In=class{ruleType="matchAssociation";validate(e,t,i,r,s){if(!i)return;let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(s.domain)if(s.getUserEntity()||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match association access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o}),!e.association||!e.association.key)s.addIssue({code:v("RULE","MISSING_ASSOCIATION_TARGET"),message:'The access rule is set to "Match association access", but no association target is specified.',suggestion:"Specify the target association in the rule configuration.",severity:"error",context:o});else{let l=e.association.key,d=e.association.domain,p=s.findAssociation(l,d),m=i.entity.key,h=s.findEntity(m,i.entity.domain),f=h?Array.from(h.withInheritedAssociations()).find(k=>k.key===l):void 0;if(!p&&!f){let k=h?h.info.getLabel():m;s.addIssue({code:v("RULE","INVALID_ASSOCIATION_TARGET"),message:`[${k}]: The target association "${l}" does not exist in the domain.`,suggestion:"Select a valid association configured in the data domain.",severity:"error",context:o})}}}};var op=["list","create","search","link","restore"],Pn=class{ruleType="matchPathParameter";validate(e,t,i,r,s,o){if(!i)return;let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!e.parameters||!Array.isArray(e.parameters)||e.parameters.length===0){s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_EMPTY_PARAMETERS"),message:'The access rule is set to "Match path parameter", but no parameter mappings are specified.',suggestion:"Specify at least one mapping between a URL path parameter and a session property.",severity:"error",context:a});return}let n;if(t==="action"&&o)if(op.includes(o.kind)){let h=i.getAbsoluteCollectionPath()??"";n=new Set([...h.matchAll(/\{([^}]+)\}/g)].map(f=>f[1]))}else{let h=i.getAbsoluteResourcePath();n=new Set([...h.matchAll(/\{([^}]+)\}/g)].map(f=>f[1]))}else n=new Set(i.getPathParameters({absolute:!0}));let l=s.getUserEntity(),d=new Map;if(l)for(let h of l.withInheritedProperties())d.set(h.key,h);let p=i.entity?s.findEntity(i.entity.key,i.entity.domain)?.info.getLabel()??i.entity.key:i.key,m=new Map;for(let h of e.parameters){if(!h.pathParameter||h.pathParameter.trim()==="")s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_MISSING_PATH_PARAM"),message:'The "Match path parameter" rule has a mapping with no path parameter specified.',suggestion:"Specify a valid URL path parameter name.",severity:"error",context:a});else if(h.pathParameter.includes("{")||h.pathParameter.includes("}")){let f=h.pathParameter.replace(/[{}]/g,"").trim();s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_SYNTAX_ERROR"),message:`Path parameter "${h.pathParameter}" must not contain curly braces.`,suggestion:`Change "${h.pathParameter}" to "${f}".`,severity:"error",context:a})}else if(/\s/.test(h.pathParameter))s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_WHITESPACE"),message:`Path parameter "${h.pathParameter}" contains invalid whitespace.`,suggestion:`Remove whitespace from path parameter name "${h.pathParameter.trim()}".`,severity:"error",context:a});else if(!n.has(h.pathParameter)){let f=n.size>0?`[${Array.from(n).join(", ")}]`:"none";s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_MISSING_ROUTE_PARAM"),message:`[${p}]: Path parameter "${h.pathParameter}" declared in "Match path parameter" rule was not found in the route hierarchy.`,suggestion:`Ensure the route path includes "{${h.pathParameter}}" or select from available parameters: ${f}.`,severity:"error",context:a})}if(h.pathParameter&&h.pathParameter.trim()){let f=h.pathParameter.replace(/[{}]/g,"").trim();if(m.has(f)){let k=m.get(f);k===h.sessionProperty?s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_DUPLICATE_PARAMETER"),message:`Path parameter "${f}" is mapped more than once to session property "${h.sessionProperty}".`,suggestion:`Remove the duplicate mapping for "${f}".`,severity:"error",context:a}):s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_CONFLICTING_PARAMETER"),message:`Path parameter "${f}" is mapped to multiple conflicting session properties ("${k}" and "${h.sessionProperty}").`,suggestion:"Ensure each path parameter is mapped to exactly one session property in the rule.",severity:"error",context:a})}else m.set(f,h.sessionProperty)}if(!h.sessionProperty||h.sessionProperty.trim()==="")s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_MISSING_SESSION_PROP"),message:'The "Match path parameter" rule has a mapping with no session property specified.',suggestion:"Specify a session property to match against.",severity:"error",context:a});else if(/\s/.test(h.sessionProperty))s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_WHITESPACE"),message:`Session property "${h.sessionProperty}" contains invalid whitespace.`,suggestion:`Remove whitespace from session property name "${h.sessionProperty.trim()}".`,severity:"error",context:a});else{if(s.hasSessionConfigured()){if(!s.isSessionPropertyConfigured(h.sessionProperty))if(d.has(h.sessionProperty))s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_NOT_IN_SESSION"),message:`Session property "${h.sessionProperty}" is defined on the User entity but is not included in the session configuration properties.`,suggestion:`Add "${h.sessionProperty}" to the session properties in the API Model session configuration.`,severity:"error",context:a});else{let k=s.getConfiguredSessionPropertyKeys(),w=k&&k.size>0?Array.from(k).join(", "):Array.from(d.keys()).join(", ");s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${h.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:`Select a valid session property from: [${w}].`,severity:"error",context:a})}}else if(d.size>0){if(!d.has(h.sessionProperty)){let k=Array.from(d.keys()).join(", ");s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${h.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:`Select a valid session property from: [${k}].`,severity:"error",context:a})}}else s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${h.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:"Configure session properties in the API Model and ensure a User entity is defined.",severity:"error",context:a});let f=d.get(h.sessionProperty);if(f&&(f.multiple===!0||f.type==="json"||f.type==="binary")){let k=f.multiple?"array":f.type;s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_NON_SCALAR_SESSION_PROP"),message:`[${p}]: Session property "${f.info.getLabel()}" has a non-scalar type (${k}). The "Match path parameter" rule only supports matching scalar string, number, or boolean properties.`,suggestion:"Select a scalar session property, or use an appropriate authorization rule for role/membership arrays.",severity:"error",context:a})}}}if(t==="exposure"&&i.actions&&i.actions.length>0){let h=i.getAbsoluteCollectionPath()??"",f=new Set([...h.matchAll(/\{([^}]+)\}/g)].map(w=>w[1])),k=i.actions.filter(w=>op.includes(w.kind)&&!w.overrideParentScenarios);if(k.length>0)for(let w of e.parameters){let S=w.pathParameter?.replace(/[{}]/g,"").trim();if(S&&!f.has(S)&&n.has(S)){let E=k.map(A=>`"${A.kind}"`).join(", ");s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_COLLECTION_ACTION_MISMATCH"),message:`[${p}]: The exposure-level "Match path parameter" rule uses path parameter "${S}", which is not present in the collection route path ("${h}"). Collection action(s) (${E}) inherit this rule and will fail at runtime.`,suggestion:'Move the "Match path parameter" rule to individual resource actions (read, update, delete), or enable "overrideParentScenarios" on collection actions.',severity:"error",context:a})}}}}};var Rn=class{ruleType="allowAuthenticated";validate(){}};var $n=class{ruleType="lifecycleStatus";validate(e,t,i,r,s){if(!i?.entity?.key)return;let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!s.domain)return;let n=s.findEntity(i.entity.key,i.entity.domain);if(!n)return;let l=n.info.getLabel(),d=Array.from(n.withInheritedProperties()).filter(S=>S.hasSemantic(g.Status));if(d.length===0){s.addIssue({code:v("RULE","LIFECYCLE_STATUS_MISSING_PROPERTY"),message:`[${l}]: The "lifecycleStatus" access rule requires "${l}" to have a property with the Status semantic (SemanticType.Status), but none was found.`,suggestion:`Add the Status semantic to a status/state property on "${l}", or remove the lifecycleStatus rule.`,severity:"error",context:o});return}if(d.length>1){let S=d.map(E=>`"${E.info.name||E.key}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_MULTIPLE_PROPERTIES"),message:`[${l}]: The entity has multiple properties with the Status semantic (${S}). The "lifecycleStatus" access rule requires exactly one Status property on the entity to avoid ambiguous resolution.`,suggestion:`Ensure only one property on "${l}" carries the Status semantic.`,severity:"error",context:o});return}let p=d[0],m=Array.isArray(e.allowedStatuses)?e.allowedStatuses:[],h=Array.isArray(e.deniedStatuses)?e.deniedStatuses:[];if(m.length===0&&h.length===0){s.addIssue({code:v("RULE","LIFECYCLE_STATUS_EMPTY_CONFIG"),message:`[${l}]: The "lifecycleStatus" access rule has neither "allowedStatuses" nor "deniedStatuses" configured. At least one status must be specified.`,suggestion:'Specify at least one status in "allowedStatuses" or "deniedStatuses".',severity:"error",context:o});return}let f=new Set(m),k=h.filter(S=>f.has(S));if(k.length>0){let S=k.map(E=>`"${E}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_CONFLICTING_STATUSES"),message:`[${l}]: The status ${S} is specified in both "allowedStatuses" and "deniedStatuses". A status cannot be simultaneously allowed and denied.`,suggestion:'Remove the conflicting status from either "allowedStatuses" or "deniedStatuses".',severity:"error",context:o})}let w;if(p.schema?.enum&&p.schema.enum.length>0)w=p.schema.enum;else{let S=p.semantics?.find(E=>E.id===g.Status);if(S&&"config"in S&&S.config){let E=S.config;Array.isArray(E.allowedStates)&&E.allowedStates.length>0&&(w=E.allowedStates)}}if(w&&w.length>0){let S=new Set(w),E=m.filter(_=>!S.has(_)),A=h.filter(_=>!S.has(_));if(E.length>0){let _=E.map(I=>`"${I}"`).join(", "),O=w.map(I=>`"${I}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_INVALID_STATUS"),message:`[${l}]: The status ${_} in "allowedStatuses" is not a valid state for property "${p.info.name||p.key}". Valid states are: ${O}.`,suggestion:`Update "allowedStatuses" to only include valid states: ${O}.`,severity:"error",context:o})}if(A.length>0){let _=A.map(I=>`"${I}"`).join(", "),O=w.map(I=>`"${I}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_INVALID_STATUS"),message:`[${l}]: The status ${_} in "deniedStatuses" is not a valid state for property "${p.info.name||p.key}". Valid states are: ${O}.`,suggestion:`Update "deniedStatuses" to only include valid states: ${O}.`,severity:"error",context:o})}}}};var si=class{validators=new Map;constructor(){this.register(new fn),this.register(new kn),this.register(new vn),this.register(new wn),this.register(new Sn),this.register(new An),this.register(new En),this.register(new _n),this.register(new xn),this.register(new In),this.register(new Pn),this.register(new Rn),this.register(new $n)}register(e){this.validators.set(e.ruleType,e)}get(e){return this.validators.get(e)}validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(!e.allowedLevels.includes(t)){if(t==="api")s.addIssue({code:v("RULE","INVALID_LEVEL"),message:`[${r.info.getLabel()}]: The "${e.type}" access rule cannot be used at the API level because it requires an entity or action context.`,suggestion:"Move this access rule to an exposed entity or action scenario.",severity:"error",context:a});else{let l=t==="exposure"?"an exposed entity":"an action",d=e.allowedLevels.join(", ");s.addIssue({code:v("RULE","INVALID_LEVEL"),message:`[${i?.entity?.key??i?.key}]: The "${e.type}" access rule cannot be used at the ${t} level because it is only allowed at: [${d}].`,suggestion:`Move this access rule to ${d.includes("api")?"the API level":l==="an exposed entity"?"an action":"an exposed entity"}.`,severity:"error",context:a})}return}r.authorization?.strategy&&(Xd(r.authorization.strategy,t).includes(e.type)||s.addIssue({code:v("RULE","INCOMPATIBLE_RULE_FOR_STRATEGY"),message:`The "${e.type}" access rule is not compatible with the ${r.authorization.strategy} authorization strategy.`,suggestion:"Switch to a strategy that supports this rule.",severity:"error",context:a}));let n=this.validators.get(e.type);n&&n.validate(e,t,i,r,s,o)}};var $s=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key};e.kind!==ke&&t.addIssue({code:v("API","INVALID_KIND"),message:"The API model type is incorrect.",suggestion:'Set the model type to "ApiModel".',severity:"error",context:{...i,property:"kind"}}),(!e.key||typeof e.key!="string"||e.key.trim()==="")&&t.addIssue({code:v("API","MISSING_KEY"),message:"The API model is missing a unique identifier.",suggestion:"Provide a valid name to use as a unique identifier.",severity:"error",context:{...i,property:"key"}}),(!e.info||!e.info.name||e.info.name.trim()==="")&&t.addIssue({code:v("API","MISSING_NAME"),message:"The API model has no defined name.",suggestion:"Provide a descriptive name for your API.",severity:"error",context:{...i,property:"info.name"}}),(!e.info||!e.info.description||e.info.description.trim()==="")&&t.addIssue({code:v("API","MISSING_DESCRIPTION"),message:"Adding a description helps others understand your API.",suggestion:"Add a description to clarify the purpose of this API.",severity:"warning",context:{...i,property:"info.description"}})}};var Os=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=e.domain;if(!r){t.addIssue({code:v("API","MISSING_DOMAIN"),message:"No Data Domain is attached to the API.",suggestion:"Select a Data Domain from the settings to power your API.",severity:"error",context:i});return}(!r.info||!r.info.version)&&t.addIssue({code:v("API","MISSING_DOMAIN_VERSION"),message:"The selected Data Domain is missing a version number.",suggestion:"Specify a version for the attached Data Domain.",severity:"error",context:i})}};var Ns=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=/^https?:\/\//i,s=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;e.contact?(e.contact.email&&!s.test(e.contact.email)&&t.addIssue({code:v("API","INVALID_CONTACT_EMAIL"),message:"The contact email address looks invalid.",suggestion:"Please double check the email address formatting.",severity:"error",context:{...i,property:"contact.email"}}),e.contact.url&&!r.test(e.contact.url)&&t.addIssue({code:v("API","INVALID_CONTACT_URL"),message:"The contact link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...i,property:"contact.url"}})):t.addIssue({code:v("API","MISSING_CONTACT"),message:"A contact email or link is highly recommended for API consumers.",suggestion:"Add an email or help desk link in the metadata tab.",severity:"info",context:{...i,property:"contact"}}),e.license?e.license.url&&!r.test(e.license.url)&&t.addIssue({code:v("API","INVALID_LICENSE_URL"),message:"The license link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...i,property:"license.url"}}):t.addIssue({code:v("API","MISSING_LICENSE"),message:"Adding a license to your API helps users understand its usage rights.",suggestion:"Add the name and a link to your API license terms.",severity:"info",context:{...i,property:"license"}}),e.termsOfService||t.addIssue({code:v("API","MISSING_TOS"),message:"Terms of Service help legal compliance.",suggestion:"Add a link to the terms of your API service.",severity:"info",context:{...i,property:"termsOfService"}})}};var Ts=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=!1;for(let s of e.exposes.values())if(s.actions.some(o=>Pt.isListAction(o)||Rt.isSearchAction(o))){r=!0;break}r&&(!e.pagination||!e.pagination.kind?t.addIssue({code:v("API","MISSING_PAGINATION"),message:"The API must have a defined pagination strategy when it exposes List or Search actions.",suggestion:"Configure how results are loaded (e.g. by page or by a continuous cursor).",severity:"error",context:{...i,property:"pagination"}}):(e.pagination.defaultLimit===void 0&&t.addIssue({code:v("API","MISSING_PAGINATION_DEFAULT_LIMIT"),message:"The API doesn't have a defined default page limit when it exposes List or Search actions.",suggestion:"Set a default page limit for the pagination otherwise the API will use its default limit.",severity:"info",context:{...i,property:"pagination.defaultLimit"}}),e.pagination.maxLimit===void 0&&t.addIssue({code:v("API","MISSING_PAGINATION_MAX_LIMIT"),message:"The API doesn't have a defined page size max limit when it exposes List or Search actions.",suggestion:"Set a max page size limit for the pagination otherwise the API will use its default max limit.",severity:"info",context:{...i,property:"pagination.maxLimit"}})))}};var js=class{ruleRegistry;constructor(e=new si){this.ruleRegistry=e}validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=t.getUserEntity();if(!e.authentication)t.addIssue({code:v("API","MISSING_AUTHENTICATION"),message:"The API is missing authentication settings.",suggestion:"Go to the security settings and configure how users authenticate.",severity:"error",context:{...i,property:"authentication"}});else if(e.authentication.strategy==="UsernamePassword"&&r){let s;for(let a of r.properties)if(a.hasSemantic(g.Password)){s=a;break}s||t.addIssue({code:v("API","MISSING_PASSWORD_SEMANTIC"),message:"The selected user model requires a property with the Password data semantic for authentication.",suggestion:'Go to the Data Modeler and add the "Password" semantic to the password property.',severity:"error",context:{...i,property:"user"}});let o;for(let a of r.properties)if(a.hasSemantic(g.Username)){o=a;break}o||t.addIssue({code:v("API","MISSING_USERNAME_SEMANTIC"),message:"Username & Password authentication requires a field with the Username data semantic.",suggestion:'Go to the Data Modeler and add the "Username" semantic to the property used for login.',severity:"error",context:{...i,property:"user"}})}if(!e.authorization)t.addIssue({code:v("API","MISSING_AUTHORIZATION"),message:"The API is missing authorization settings.",suggestion:"Go to the security settings and configure how to handle user permissions.",severity:"error",context:{...i,property:"authorization"}});else{let s=e.authorization.strategy;if(s==="RBAC"){if(e.domain){let o=t.getUserSemantics();r&&(!o||!o.hasRole)&&t.addIssue({code:v("API","MISSING_ROLE_SEMANTIC"),message:"Role-based access control requires a property with the User Role data semantic on the user model.",suggestion:'Go to the Data Modeler and add the "User Role" semantic to the property used for roles.',severity:"error",context:{...i,property:"user"}})}}else if(s==="OrganizationRBAC"){if(e.domain){let o=t.getOrganizationSemantics();(!o||!o.hasOrganization)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_SEMANTIC"),message:"Tenant RBAC authorization strategy requires a Data Entity tagged with the Organization semantic.",suggestion:"Go to the Data Modeler and mark your Organization entity with the Organization semantic.",severity:"error",context:{...i,property:"authorization"}}),(!o||!o.hasMembersAssociation)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_MEMBERS_SEMANTIC"),message:"Tenant RBAC authorization strategy requires an association tagged with the Organization Members semantic.",suggestion:"Go to the Data Modeler and add the Organization Members semantic to the pivot association.",severity:"error",context:{...i,property:"authorization"}}),(!o||!o.hasOrganizationRole)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_ROLE_SEMANTIC"),message:"Tenant RBAC authorization strategy requires a property tagged with the Organization Role semantic.",suggestion:"Go to the Data Modeler and add the Organization Role semantic to the role property on Organization Members.",severity:"error",context:{...i,property:"authorization"}})}}else if(s==="EnterpriseRBAC"&&e.domain){let o=t.getUserSemantics();r&&(!o||!o.hasRole)&&t.addIssue({code:v("API","MISSING_ROLE_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires a property with the User Role data semantic on the user model.",suggestion:'Go to the Data Modeler and add the "User Role" semantic to the property used for roles.',severity:"error",context:{...i,property:"user"}});let a=t.getOrganizationSemantics();(!a||!a.hasOrganization)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires a Data Entity tagged with the Organization semantic.",suggestion:"Go to the Data Modeler and mark your Organization entity with the Organization semantic.",severity:"error",context:{...i,property:"authorization"}}),(!a||!a.hasMembersAssociation)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_MEMBERS_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires an association tagged with the Organization Members semantic.",suggestion:"Go to the Data Modeler and add the Organization Members semantic to the pivot association.",severity:"error",context:{...i,property:"authorization"}}),(!a||!a.hasOrganizationRole)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_ROLE_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires a property tagged with the Organization Role semantic.",suggestion:"Go to the Data Modeler and add the Organization Role semantic to the role property.",severity:"error",context:{...i,property:"authorization"}})}}if(!e.session)t.addIssue({code:v("API","MISSING_SESSION"),message:"The API is missing session configuration.",suggestion:"Configure how user sessions will be handled.",severity:"error",context:{...i,property:"session"}});else{if(e.session.secret||t.addIssue({code:v("API","MISSING_SESSION_SECRET"),message:"A secure encryption key is required for sessions.",suggestion:"Provide a strong security key in the session settings.",severity:"error",context:{...i,property:"session.secret"}}),!e.session.properties||e.session.properties.length===0)t.addIssue({code:v("API","MISSING_SESSION_PROPERTIES"),message:"The session token needs to include at least one piece of user information, like an ID.",suggestion:"Select fields that should be stored securely inside the session payload.",severity:"error",context:{...i,property:"session.properties"}});else if(e.authorization&&(e.authorization.strategy==="RBAC"||e.authorization.strategy==="EnterpriseRBAC")&&e.domain){let a=t.getUserSemantics();a?.roleProperty&&!e.session.properties.find(n=>n.key===a.roleProperty?.key)&&t.addIssue({code:v("API","MISSING_RBAC_SESSION_PROPERTY"),message:"The user role must be included in the session data for permissions to work.",suggestion:"Make sure your selected role property is checked in the session settings.",severity:"error",context:{...i,property:"session.properties"}})}let{cookie:s,jwt:o}=e.session;(!s||!s.enabled)&&(!o||!o.enabled)&&t.addIssue({code:v("API","MISSING_SESSION_TRANSPORT"),message:"No delivery method for sessions (like cookies or tokens) is enabled.",suggestion:"Enable at least one session delivery mechanism in the security settings.",severity:"error",context:{...i,property:"session"}})}if(e.user?e.domain&&!e.domain.findEntity(e.user.key,e.user.domain)&&t.addIssue({code:v("API","INVALID_USER_ENTITY"),message:"The selected user model no longer exists in your data domain.",suggestion:"Please navigate to security settings and select a valid user model.",severity:"error",context:{...i,property:"user"}}):t.addIssue({code:v("API","MISSING_USER_ENTITY"),message:"You need to specify what kind of object represents your users.",suggestion:"Select a model from your domain that stores your user accounts.",severity:"error",context:{...i,property:"user"}}),e.accessScenarios&&e.accessScenarios.length>0)for(let s of e.accessScenarios)for(let o of s.predicate.getLeafRules())this.ruleRegistry.validate(o,"api",void 0,e,t)}};var Ji=class{ruleRegistry;constructor(e=new si){this.ruleRegistry=e}validate(e,t,i,r){let s={apiModelKey:i.key,kind:"Action",key:e.kind,parentExposedEntityKey:t.key};if(tt.isDeleteAction(e)&&(e.strategy?e.strategy==="hard"&&r.addIssue({code:v("ACTION","DELETE_HARD_WARNING"),message:"Permanent delete is active. There will be no way to restore deleted data.",suggestion:'Consider switching to "soft delete" if users might need to undo mistakes.',severity:"info",context:{...s,property:"strategy"}}):r.addIssue({code:v("ACTION","DELETE_MISSING_STRATEGY"),message:"A Delete action must know if you want to completely erase the record, or just hide it.",suggestion:"Configure the deletion type (permanent or soft).",severity:"error",context:{...s,property:"strategy"}})),Ki.isUpdateAction(e)&&(!e.allowedMethods||e.allowedMethods.length===0)&&r.addIssue({code:v("ACTION","UPDATE_MISSING_METHODS"),message:"An Update action must define how the data is sent (PUT replaces everything; PATCH applies partial changes).",suggestion:"Select at least one allowed HTTP method.",severity:"error",context:{...s,property:"allowedMethods"}}),Bi.isRestoreAction(e)){let d=t.actions.find(tt.isDeleteAction);(!d||d.strategy!=="soft")&&r.addIssue({code:v("ACTION","RESTORE_REQUIRES_SOFT_DELETE"),message:"The Restore action requires Soft Delete to be configured on this entity.",suggestion:'Enable the Delete action with strategy "soft" before enabling Restore.',severity:"error",context:{...s,property:"kind"}})}if(e.getAllRateLimiters().some(d=>d.rules.length)||r.addIssue({code:v("ACTION","MISSING_RATE_LIMITS"),message:"It is best practice to configure a rate limit so your API is not overwhelmed.",suggestion:"Set a reasonable maximum request speed for this operation.",severity:"warning",context:s}),e.accessScenarios)for(let d of e.accessScenarios)for(let p of d.predicate.getLeafRules())this.ruleRegistry.validate(p,"action",t,i,r,e);e.overrideParentScenarios&&e.accessScenarios.length===0&&r.addIssue({code:v("ACTION","OVERRIDE_BUT_NO_SCENARIOS"),message:`Action "${e.kind}" has "Override parent scenarios" enabled but defines no scenarios of its own. This action will deny all access.`,suggestion:'Add at least one access scenario to this action, or uncheck "Override parent scenarios" to inherit parent policies.',severity:"warning",context:{...s,property:"overrideParentScenarios"}});let n=e.getAllScenarios();if(n.length===0){let d=t.entity?.key??t.key;r.addIssue({code:v("ACTION","MISSING_ACCESS_RULES"),message:`[${d}]: The ${e.kind} action has no security rules attached, making it entirely inaccessible or open.`,suggestion:"Allow specific user roles to access this operation.",severity:"error",context:{...s,kind:"Action",key:e.kind,parentExposedEntityKey:t.key}})}for(let d of n){let p=hn(d.predicate);p.length>0&&r.addIssue({code:v("ACTION","SCENARIO_EMPTY_PREDICATE_GROUP"),message:`Scenario "${d.label||d.key}" on action "${e.kind}" contains ${p.length===1?"an empty predicate group":`${p.length} empty predicate groups`}. Empty predicate groups have no effect and should contain child rules or be removed.`,suggestion:"Add access rules to the predicate group or remove the empty group from the scenario.",severity:"warning",context:{...s,property:"accessScenarios"}})}for(let d of n)Ps(d.predicate)||r.addIssue({code:v("ACTION","SCENARIO_MISSING_IDENTITY_RULE"),message:`Scenario "${d.label||d.key}" on action "${e.kind}" has no identity-constraining rules (e.g. AllowPublic, MatchUserRole). At least one identity rule is required.`,suggestion:"Add an identity rule such as AllowPublic, AllowAuthenticated, or MatchUserRole to this scenario.",severity:"error",context:{...s,property:"accessScenarios"}});let l=null;for(let d of n){let p=d.predicate.getLeafRules().filter(m=>m.isIdentityConstraining);if(p.length>0){if(p.every(h=>h.isBroadIdentityRule))l||(l=d);else if(l){r.addIssue({code:v("ACTION","SCENARIO_BROAD_BEFORE_NARROW"),message:`A broad access scenario ("${l.label||l.key}") appears before more specific scenarios. Broad scenarios match all callers and will cause later scenarios to never be evaluated.`,suggestion:"Move specific scenarios (e.g. admin or role-restricted) above broad scenarios (e.g. public or authenticated).",severity:"warning",context:{...s,property:"accessScenarios"}});break}}}if(e.projection&&(Pt.isListAction(e)||Rt.isSearchAction(e)||qi.isReadAction(e)||r.addIssue({code:v("ACTION","INVALID_PROJECTION_SEVERITY"),message:`Projections are only supported for read actions (List, Search, Read). The action "${e.kind}" does not support projections.`,suggestion:"Remove projection configuration from this write action.",severity:"warning",context:{...s,property:"projection"}}),e.projection.type!=="include"&&e.projection.type!=="exclude"&&r.addIssue({code:v("ACTION","INVALID_PROJECTION_TYPE"),message:'Projection type must be either "include" or "exclude".',suggestion:"Select a valid projection type.",severity:"error",context:{...s,property:"projection"}}),Array.isArray(e.projection.fields))){let p=r.domain??i.domain,m=t.entity?p?.findEntity(t.entity.key,t.entity.domain):void 0;if(m){let h=Array.from(m.withInheritedProperties()),f=new Set(h.map(w=>w.key)),k=new Set(Array.from(m.withInheritedAssociations()).map(w=>w.key));e.projection.fields.forEach((w,S)=>{if(w.invalid===!0){r.addIssue({code:v("ACTION","INVALID_PROJECTION_FIELD"),message:`The projected field "${w.key}" is marked as invalid. It was not found in the entity definition.`,suggestion:"Update or remove this field from the projection configuration.",severity:"error",context:{...s,property:`projection.fields[${S}]`}});return}if(w.type==="association"){let E=w.key.split("."),A=E[0];if(!k.has(A))r.addIssue({code:v("ACTION","INVALID_PROJECTION_ASSOCIATION"),message:`The projected association "${w.key}" does not exist on this entity.`,suggestion:"Select a valid association or remove it.",severity:"error",context:{...s,property:`projection.fields[${S}]`}});else{let _=Array.from(m.withInheritedAssociations()).find(O=>O.key===A);E.length>1&&(!_||_.schema?.embedded!==!0)&&r.addIssue({code:v("ACTION","INVALID_PROJECTION_ASSOCIATION_EMBEDDED"),message:`The projected association "${w.key}" is invalid because association "${A}" is not embedded.`,suggestion:"Ensure the association is marked as embedded to use dot-notation.",severity:"error",context:{...s,property:`projection.fields[${S}]`}})}}else{let E=w.key.split("."),A=E[0];if(!f.has(A))r.addIssue({code:v("ACTION","INVALID_PROJECTION_PROPERTY"),message:`The projected property "${w.key}" does not exist on this entity.`,suggestion:"Select a valid property or remove it.",severity:"error",context:{...s,property:`projection.fields[${S}]`}});else{let _=h.find(O=>O.key===A);E.length>1&&(!_||_.type!=="json"?r.addIssue({code:v("ACTION","INVALID_PROJECTION_JSON_ROOT"),message:`The projected property "${w.key}" is invalid because root property "${A}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...s,property:`projection.fields[${S}]`}}):_.jsonSchema&&(St(_.jsonSchema,E.slice(1))||r.addIssue({code:v("ACTION","INVALID_PROJECTION_JSON_PATH"),message:`The projected property "${w.key}" is invalid according to the JSON Schema of "${A}".`,suggestion:"Configure a valid JSON Schema path or update the projection path.",severity:"error",context:{...s,property:`projection.fields[${S}]`}})))}}})}}}};var Cs=class{actionValidator;ruleRegistry;constructor(e=new Ji,t=new si){this.actionValidator=e,this.ruleRegistry=t}validate(e,t,i){let r={apiModelKey:t.key,kind:Ht,key:e.key},s=i.domain??t.domain,o=e.entity?s?.findEntity(e.entity.key,e.entity.domain):void 0,a=o?.info.getLabel()||o?.key||"unknown";!e.entity||!e.entity.key?i.addIssue({code:v("EXPOSURE","MISSING_ENTITY_REF"),message:"This exposed endpoint does not point to a specific data model.",suggestion:"Select which database entity this endpoint should serve.",severity:"error",context:{...r,property:"entity"}}):o||i.addIssue({code:v("EXPOSURE","INVALID_ENTITY_REF"),message:"This endpoint points to a data model that no longer exists.",suggestion:"Select a new valid database model or delete this endpoint.",severity:"error",context:{...r,property:"entity"}});let n=o?.hasSemantic(g.User);if(e.isRoot&&o&&!n&&s&&s.resolveOwnershipPath(o.key)===null&&i.addIssue({code:v("EXPOSURE","MISSING_OWNER_PATH"),message:`[${a}]: This root endpoint has no ownership path to the User entity. If you want this resource to be user-isolated, add the Relational Resource Owner semantic to the association that defines its owner.`,suggestion:"Ensure the resource has a direct (Resource Owner Identifier) or indirect (Relational Resource Owner) path to the User entity.",severity:"warning",context:r}),e.parent?.selfRoute){let d=t.exposes.get(e.parent.key);d?(!d.hasCollection||!d.collectionPath)&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_REQUIRES_COLLECTION"),message:`[${a}]: selfRoute can only be applied under a parent exposure that has a collection endpoint.`,suggestion:"Enable collection on the parent exposure or remove selfRoute.",severity:"error",context:{...r,property:"parent.key"}}):i.addIssue({code:v("EXPOSURE","SELF_ROUTE_PARENT_NOT_FOUND"),message:`[${a}]: The parent exposed entity "${e.parent.key}" for selfRoute does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...r,property:"parent.key"}}),e.parent.association&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_ASSOCIATION_FORBIDDEN"),message:`[${a}]: A selfRoute exposure must not specify an association on its parent reference.`,suggestion:"Remove the association from the selfRoute parent reference.",severity:"error",context:{...r,property:"parent.association"}}),o&&!o.hasSemantic(g.User)&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_NOT_USER_ENTITY"),message:`[${a}]: selfRoute exposure can only be applied to an entity carrying the User semantic.`,suggestion:"Annotate this entity with the User semantic or remove selfRoute.",severity:"error",context:{...r,property:"entity"}});let p=["read","update","delete","unlink"],m=e.actions.filter(h=>!p.includes(h.kind));m.length>0&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_INVALID_ACTION"),message:`[${a}]: The /me endpoint is a singleton resource. Only 'read', 'update', 'delete', and 'unlink' actions are permitted.`,suggestion:`Remove unsupported actions (${m.map(h=>`'${h.kind}'`).join(", ")}) from this selfRoute exposure.`,severity:"error",context:{...r,property:"actions"}});for(let h of e.actions)h.accessScenarios.some(k=>{let w=k.predicate.getLeafRules(),S=w.some(A=>A.type==="allowAuthenticated"),E=w.some(A=>A.type==="matchResourceOwner"&&A.target==="user-entity");return S&&E})||i.addIssue({code:v("EXPOSURE","SELF_ROUTE_MISSING_PREDEFINED_RULES"),message:`[${a}]: Action "${h.kind}" on a selfRoute exposure must include the invariant security rules (AllowAuthenticated and MatchResourceOwner with target 'user-entity').`,suggestion:"Ensure each action on a selfRoute exposure includes AllowAuthenticated and MatchResourceOwner (target: user-entity) rules.",severity:"error",context:{...r,property:"actions"}});for(let h of t.exposes.values())if(h.key!==e.key&&h.parent?.selfRoute&&h.parent.key===e.parent.key){i.addIssue({code:v("EXPOSURE","SELF_ROUTE_DUPLICATE"),message:`[${a}]: Only one selfRoute exposure may be registered per parent exposure.`,suggestion:"Remove duplicate selfRoute under this parent exposure.",severity:"error",context:{...r,property:"parent.selfRoute"}});break}}if(!e.isRoot&&s){if(!e.parent)i.addIssue({code:v("EXPOSURE","MISSING_PARENT_REF"),message:`[${a}]: A sub-endpoint (non-root exposure) must have a parent endpoint.`,suggestion:"Expose this entity under a parent entity or make it a root endpoint.",severity:"error",context:{...r,property:"parent"}});else if(!e.parent.selfRoute){let d=t.exposes.get(e.parent.key);if(!d)i.addIssue({code:v("EXPOSURE","INVALID_PARENT_EXPOSURE"),message:`[${a}]: The parent exposed entity "${e.parent.key}" does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...r,property:"parent.key"}});else if(!e.parent.association)i.addIssue({code:v("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${a}]: A sub-endpoint must specify a parent association.`,suggestion:"Select a valid association in the data domain connecting parent and child entities.",severity:"error",context:{...r,property:"parent.association"}});else{let p=s.findEntity(d.entity.key,d.entity.domain),m=e.parent.association.key,h=s.findAssociation(m,e.parent.association.domain);if(!h)i.addIssue({code:v("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${a}]: The parent association "${m}" does not exist in the data domain.`,suggestion:"Select a valid association in the data domain that connects the parent and child entities.",severity:"error",context:{...r,property:"parent.association"}});else{let f=p?.key,k=o?.key,w=h.getParentInstance()?.key===f,S=h.getParentInstance()?.key===k,E=h.targets.some(O=>O.key===f),A=h.targets.some(O=>O.key===k);w&&A||S&&E||i.addIssue({code:v("EXPOSURE","INVALID_PARENT_ASSOCIATION"),message:`[${a}]: The parent association "${m}" does not connect the parent entity "${p?.info.name||f}" with the child entity "${o?.info.name||k}".`,suggestion:"Use an association that directly connects the parent and child data entities.",severity:"error",context:{...r,property:"parent.association"}})}}}}if(e.hasCollection){if(!e.collectionPath)i.addIssue({code:v("EXPOSURE","MISSING_COLLECTION_PATH"),message:`[${a}]: When an endpoint exposes a collection, it must define what its base URL path is.`,suggestion:'Add a path (e.g., "/items").',severity:"error",context:{...r,property:"collectionPath"}});else{let d=e.collectionPath.split("/").filter(Boolean);(d.length!==1||!e.collectionPath.startsWith("/"))&&i.addIssue({code:v("EXPOSURE","INVALID_COLLECTION_PATH"),message:`[${a}]: The collection URL should start with "/" and have no extra slashes.`,suggestion:`Ensure the path looks like exactly "/${d[0]||"subresource"}".`,severity:"error",context:{...r,property:"collectionPath"}}),e.isRoot&&/^\/verify[-_].*$/i.test(e.collectionPath)&&i.addIssue({code:v("EXPOSURE","RESERVED_COLLECTION_PATH"),message:`[${a}]: The route "${e.collectionPath}" matches the reserved pattern "/verify-*".`,suggestion:'Root routes starting with "/verify-" are reserved for platform verification endpoints (e.g. /verify-email, /verify-phone).',severity:"error",context:{...r,property:"collectionPath"}})}e.resourcePath?e.collectionPath&&(new RegExp(`^${e.collectionPath}/\\{[a-zA-Z0-9_]+\\}$`).test(e.resourcePath)||i.addIssue({code:v("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${a}]: The single item route should match exactly your collection path plus one identifier variable.`,suggestion:`Make sure the item path is formatted exactly like "${e.collectionPath}/{id}".`,severity:"error",context:{...r,property:"resourcePath"}})):i.addIssue({code:v("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${a}]: You need an identifier to locate single items.`,suggestion:'Specify the identification parameter format, like "{id}".',severity:"error",context:{...r,property:"resourcePath"}})}else e.resourcePath?((e.resourcePath.split("/").filter(Boolean).length!==1||!e.resourcePath.startsWith("/"))&&i.addIssue({code:v("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${a}]: The URL route ${e.resourcePath} must only contain one exact part or level.`,suggestion:"Simplify the endpoint URL to a single segment.",severity:"error",context:{...r,property:"resourcePath"}}),e.isRoot&&/^\/verify[-_].*$/i.test(e.resourcePath)&&i.addIssue({code:v("EXPOSURE","RESERVED_RESOURCE_PATH"),message:`[${a}]: The route "${e.resourcePath}" matches the reserved pattern "/verify-*".`,suggestion:'Root routes starting with "/verify-" are reserved for platform verification endpoints (e.g. /verify-email, /verify-phone).',severity:"error",context:{...r,property:"resourcePath"}})):i.addIssue({code:v("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${a}]: Exposed entity representing a single item must declare their URL route.`,suggestion:'Set the URL path (such as "/profile").',severity:"error",context:{...r,property:"resourcePath"}});e.isRoot&&(e.collectionPath&&t.findCollectionPathCollision(e.collectionPath,e.key)&&i.addIssue({code:v("EXPOSURE","ROOT_COLLECTION_COLLISION"),message:`[${a}]: The route "${e.collectionPath}" is already used by another view.`,suggestion:"Give this resource a different path to avoid conflicts.",severity:"error",context:{...r,property:"collectionPath"}}),e.resourcePath&&t.findResourcePathCollision(e.resourcePath,e.key)&&i.addIssue({code:v("EXPOSURE","ROOT_RESOURCE_COLLISION"),message:`[${a}]: The route "${e.resourcePath}" is already used by another one.`,suggestion:"Give this single-item resource a different path to avoid conflicts.",severity:"error",context:{...r,property:"resourcePath"}}));let l=e.getAbsoluteResourcePath();if(l){let d=[...l.matchAll(/\{([^}]+)\}/g)].map(m=>m[1]);if(new Set(d).size!==d.length){let h=d.filter((f,k)=>d.indexOf(f)!==k)[0];i.addIssue({code:v("EXPOSURE","DUPLICATE_PATH_PARAMETER"),message:`[${a}]: The path parameter "{${h}}" is duplicated in the resource path hierarchy.`,suggestion:"Change the parameter name in either this resource or its ancestor to ensure unique parameter names.",severity:"error",context:{...r,property:"resourcePath"}})}}if(!e.actions||e.actions.length===0)i.addIssue({code:v("EXPOSURE","MISSING_ACTIONS"),message:`[${a}]: This exposed entity does not let users do anything.`,suggestion:"Enable at least one operation like Create, Read, or Update.",severity:"error",context:{...r,property:"actions"}});else{let d=!1,p=!1,m=!1,h=!1;for(let f of e.actions)this.actionValidator.validate(f,e,t,i),Rt.isSearchAction(f)&&(d=!0),Pt.isListAction(f)&&(p=!0),(f.kind==="link"||f.kind==="unlink")&&(m=!0),(f.kind==="create"||f.kind==="delete")&&(h=!0);if(m&&h&&i.addIssue({code:v("EXPOSURE","MUTUALLY_EXCLUSIVE_ACTIONS"),message:`[${a}]: An endpoint cannot mix Many-to-Many actions (Link/Unlink) with standard Create/Delete actions.`,suggestion:"Use Link/Unlink for pivot tables and Create/Delete for standard resources.",severity:"error",context:{...r,property:"actions"}}),p||d){let f=e.paginationContract;if(!f)i.addIssue({code:v("EXPOSURE","MISSING_PAGINATION_CONTRACT"),message:`[${a}]: The List or Search action needs a pagination contract.`,suggestion:"Add a pagination contract to the exposed entity.",severity:"error",context:r});else{if(p&&((!f.filterableFields||f.filterableFields.length===0)&&i.addIssue({code:v("EXPOSURE","LIST_MISSING_FILTERS"),message:`[${a}]: Listing all elements without filters could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow filtering.",severity:"warning",context:r}),(!f.sortableFields||f.sortableFields.length===0)&&i.addIssue({code:v("EXPOSURE","LIST_MISSING_SORTING"),message:`[${a}]: Listing all elements without sorting could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow sorting.",severity:"warning",context:r})),d){let k=[];Array.isArray(f.searchableFields)&&k.push(...f.searchableFields),Array.isArray(f.filterableFields)&&k.push(...f.filterableFields),k.length||i.addIssue({code:v("EXPOSURE","SEARCH_MISSING_FIELDS"),message:`[${a}]: Search action needs to know which text fields to look in.`,suggestion:"Select a few important fields to allow searching or full-text search.",severity:"warning",context:r})}if(o){let k=Array.from(o.withInheritedProperties()),w=new Set(k.map(E=>E.key)),S=(E,A,_,O)=>{if(E&&Array.isArray(E))for(let I of E){let j=I.split("."),L=j[0];if(!w.has(L))i.addIssue({code:v("EXPOSURE",_),message:`[${a}]: The ${O} field "${I}" does not exist on this entity.`,suggestion:`Select a valid property on the entity for ${O}.`,severity:"error",context:{...r,property:`paginationContract.${A}Fields`}});else{let P=k.find(R=>R.key===L);j.length>1&&(!P||P.type!=="json"?i.addIssue({code:v("EXPOSURE",_),message:`[${a}]: The ${O} field "${I}" is invalid because root property "${L}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...r,property:`paginationContract.${A}Fields`}}):P.jsonSchema&&(St(P.jsonSchema,j.slice(1))||i.addIssue({code:v("EXPOSURE",_),message:`[${a}]: The ${O} field "${I}" is invalid according to the JSON Schema of "${L}".`,suggestion:"Configure a valid JSON Schema path or update the field path.",severity:"error",context:{...r,property:`paginationContract.${A}Fields`}})))}}};S(f.filterableFields,"filterable","INVALID_FILTER_FIELD","filterable"),S(f.sortableFields,"sortable","INVALID_SORT_FIELD","sortable"),S(f.searchableFields,"searchable","INVALID_SEARCH_FIELD","searchable")}}}}if(e.accessScenarios)for(let d of e.accessScenarios)for(let p of d.predicate.getLeafRules())this.ruleRegistry.validate(p,"exposure",e,t,i);this.validateTaxonomyOrgScoping(e,t,i)}validateTaxonomyOrgScoping(e,t,i){let r=t.authorization?.strategy;if(!(r==="OrganizationRBAC"||r==="EnterpriseRBAC"))return;let o=i.domain??t.domain;if(!o||!e.entity?.key)return;let a=o.findEntity(e.entity.key,e.entity.domain);if(!a)return;let n=a.info.getLabel()||a.key,l={apiModelKey:t.key,kind:Ht,key:e.key};for(let d of a.withInheritedAssociations()){if(d.hasSemantic(g.Tags)&&!d.isLinked())for(let p of d.targets){let m=o.findEntity(p.key,p.domain);if(m&&!Array.from(m.withInheritedAssociations()).some(f=>f.hasSemantic(g.OrganizationResource))){let f=m.info.getLabel()||m.key,k=d.info.getLabel()||d.key;i.addIssue({code:"tags_target_not_org_scoped_in_org_api",message:`[${n}]: The target entity "${f}" of Tags association "${k}" is not organization-scoped, but the API uses an organization authorization strategy (${r}).`,suggestion:`Add an association with SemanticType.OrganizationResource to the "${f}" entity to scope tags to organizations.`,severity:"error",context:{...l,property:d.key}})}}if(d.hasSemantic(g.Categories)&&!d.isLinked())for(let p of d.targets){let m=o.findEntity(p.key,p.domain);if(m&&!Array.from(m.withInheritedAssociations()).some(f=>f.hasSemantic(g.OrganizationResource))){let f=m.info.getLabel()||m.key,k=d.info.getLabel()||d.key;i.addIssue({code:"categories_target_not_org_scoped_in_org_api",message:`[${n}]: The target entity "${f}" of Categories association "${k}" is not organization-scoped, but the API uses an organization authorization strategy (${r}).`,suggestion:`Add an association with SemanticType.OrganizationResource to the "${f}" entity to scope categories to organizations.`,severity:"error",context:{...l,property:d.key}})}}}}};var On=class{model;report=[];#e=0;#t=0;#i=0;#r=!1;infoValidator=new $s;dependencyValidator=new Os;securityValidator=new js;paginationValidator=new Ts;metadataValidator=new Ns;exposureValidator=new Cs;actionValidator=new Ji;get infoCount(){return this.#r||this.computeIssueCounters(),this.#e}get warningCount(){return this.#r||this.computeIssueCounters(),this.#t}get errorCount(){return this.#r||this.computeIssueCounters(),this.#i}constructor(e){this.model=e}validate(){this.#r=!1,this.report=[];let e=new gt(this.model);if(this.infoValidator.validate(this.model,e),this.dependencyValidator.validate(this.model,e),this.securityValidator.validate(this.model,e),this.paginationValidator.validate(this.model,e),this.metadataValidator.validate(this.model,e),!this.model.exposes||this.model.exposes.size===0)e.addIssue({code:v("API","NO_EXPOSURES"),message:"Your API currently has no exposed data for external clients to request.",suggestion:"Expose a data model so apps can communicate with it.",severity:"warning",context:{apiModelKey:this.model.key,kind:ke,key:this.model.key,property:"exposes"}});else for(let t of this.model.exposes.values())this.exposureValidator.validate(t,this.model,e);return this.report=e.report,this.report}validateInfo(){let e=new gt(this.model);return this.infoValidator.validate(this.model,e),e.report}validateDependency(){let e=new gt(this.model);return this.dependencyValidator.validate(this.model,e),e.report}validateSecurity(){let e=new gt(this.model);return this.securityValidator.validate(this.model,e),e.report}validatePagination(){let e=new gt(this.model);return this.paginationValidator.validate(this.model,e),e.report}validateMetadata(){let e=new gt(this.model);return this.metadataValidator.validate(this.model,e),e.report}validateExposure(e){let t=new gt(this.model);return this.exposureValidator.validate(e,this.model,t),t.report}validateAction(e,t){let i=new gt(this.model);return this.actionValidator.validate(e,t,this.model,i),i.report}computeIssueCounters(){this.#e=this.report.filter(e=>e.severity==="info").length,this.#t=this.report.filter(e=>e.severity==="warning").length,this.#i=this.report.filter(e=>e.severity==="error").length,this.#r=!0}};var Tn=class extends Ae{constructor(t,i,r){super(i,r);this.file=t}file;async execute(){y.debug("[validate] Executing schema validation...");try{this.validateArguments();let t=await this.loadSchema();this.validateSchemaStructure(t);let i=t.kind,r=[];i===Ee?r=await this.validateDataDomain(t):i===ke?r=await this.validateApiModel(t):(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Unsupported schema kind "${i}". Supported kinds: "${Ee}", "${ke}".`}),process.exit(1)),this.reportResults(r,i)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}get isRemoteValidationWithoutOrg(){return!!(this.options.fid&&!this.options.org&&!N.resolved.org)}get shouldReadFromStdin(){return!!(this.options.stdin||!this.file&&!process.stdin.isTTY)}validateArguments(){this.file&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),this.options.org&&!this.options.fid&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID (--fid) is required when using remote validation (--org)."}),process.exit(1)),this.isRemoteValidationWithoutOrg&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Organization ID is required for remote validation. Use --org <oid> or configure a default org."}),process.exit(1))}async loadSchema(){return y.debug(`[validate] Loading schema (remote=${!!this.options.fid})...`),this.options.fid?this.loadRemoteSchema():this.loadLocalSchema()}async loadRemoteSchema(){let t=this.resolveOrgId("Organization ID is required for remote validation.","Use --org <oid> or configure a default org.");y.debug(`[validate] Fetching remote schema file ID '${this.options.fid}' from organization '${t}'...`);let i=F(),{media:r}=await i.files.readMedia(t,this.options.fid,{token:i.token});return y.debug("[validate] Remote schema loaded successfully."),r}async loadLocalSchema(){let t;if(this.shouldReadFromStdin)y.debug("[validate] Reading schema from STDIN..."),t=await this.readStdin();else if(this.file){let i=ap.resolve(this.file);y.debug(`[validate] Reading local schema file from path: ${i}`),Nn.existsSync(i)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${i}`}),process.exit(1)),t=Nn.readFileSync(i,"utf8")}else this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"A file path, --stdin, or remote --org and --fid must be specified."}),process.exit(1);try{let i=JSON.parse(t);return y.debug("[validate] Local schema parsed successfully."),i}catch(i){let r=i instanceof Error?i.message:String(i);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse schema JSON: ${r}`}),process.exit(1)}}isValidSchemaStructure(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&"kind"in t}validateSchemaStructure(t){this.isValidSchemaStructure(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:'Invalid schema. The schema must be a JSON object containing a "kind" property.'}),process.exit(1))}async validateDataDomain(t){y.debug("[validate:domain] Validating schema as Data Domain...");let i=[];if(this.options.fid){let a=F(),n=t.dependencyList||[];n.length>0&&(y.debug(`[validate:domain] Listing ${n.length} dependency data domains from catalog...`),i=(await a.dataCatalog.listDependencies(n,{token:a.token})).data||[])}let r=new Me(t,i,{readOnly:!0}),o=new Zi(r).validate();return y.debug(`[validate:domain] Domain validation rules executed. Issues found: ${o.length}`),o}async validateApiModel(t){y.debug("[validate:api] Validating schema as API Model...");let i;if(this.options.fid){let a=F(),n=t.dependencyList||[];if(n.length>0){y.debug(`[validate:api] Listing ${n.length} dependency data domains from catalog...`);let d=(await a.dataCatalog.listDependencies(n,{token:a.token})).data||[];d.length>0&&(i=new Me(d[0],d,{readOnly:!0}))}}else if(this.options.domain){let a=ap.resolve(this.options.domain);y.debug(`[validate:api] Loading domain dependency from local path: ${a}`),Nn.existsSync(a)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${a}`}),process.exit(1));let n;try{n=JSON.parse(Nn.readFileSync(a,"utf8"))}catch(l){let d=l instanceof Error?l.message:String(l);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${d}`}),process.exit(1)}i=new Me(n,[],{readOnly:!0})}let r=new Ei(t,i),o=new On(r).validate();return y.debug(`[validate:api] API Model validation rules executed. Issues found: ${o.length}`),o}reportResults(t,i){y.debug(`[validate] Reporting results. Found ${t.length} validation issue(s).`);let r=t.some(s=>s.severity==="error");if(N.resolved.format==="json")console.log(JSON.stringify({isValid:!r,validationIssues:t},null,2));else if(t.length===0)this.formatter.success("Validation passed. No issues found!");else{let s=this.formatIssues(t,i);this.formatter.list(s,["severity","code","message","suggestion","context"],{headers:["SEVERITY","CODE","MESSAGE","SUGGESTION","CONTEXT"]});let o=t.filter(l=>l.severity==="error").length,a=t.filter(l=>l.severity==="warning").length,n=t.filter(l=>l.severity==="info").length;console.log(""),o>0?console.error(ie.red(`\u2716 Validation failed: ${o} error(s), ${a} warning(s), ${n} info(s).`)):console.log(ie.yellow(`\u26A0 Validation passed with warnings: ${a} warning(s), ${n} info(s).`))}r&&process.exit(1)}formatIssues(t,i){return t.map(r=>{let s=r.severity||"info",o=r.message||"",a,n,l;if(i===Ee){let d=r;a=d.rule||"unknown",n=d.help||"",l=d.key?`${d.kind||"unknown"}: ${d.key}`:d.field||""}else{let d=r;a=d.code||"unknown",n=d.suggestion||"";let p=d.context||{};l=`${p.kind||"unknown"}: ${p.key||""}${p.property?"."+p.property:""}`}return{severity:s,code:a,message:o,suggestion:n,context:l}})}async readStdin(){return new Promise((t,i)=>{let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{r+=s}),process.stdin.on("end",()=>{t(r)}),process.stdin.on("error",s=>{i(s)})})}};function np(c){c.command("validate [file]").description("Validate a Data Domain or API Model schema").option("--stdin","Read schema content from STDIN").option("--org <oid>","Organization ID (remote validation)").option("--fid <fid>","File ID / schema ID (remote validation)").option("--domain <path>","Path to local Data Domain schema file (only for local API Model validation)").action(async(e,t)=>{let i=new K({format:N.resolved.format});y.debug("[validate] Starting validation process..."),await new Tn(e,t,i).execute()})}var Ke=class extends Ae{client;fileManager;constructor(e,t,i=F(),r=new Z){super(e,t),this.client=i,this.fileManager=r}resolveVersionOption(e){return e.catalogVersion||e.ver}};var jn=class c extends Ke{static ALLOWED_SCOPES=["public","organization","private"];static ALLOWED_LIFECYCLES=["dev","beta","stable"];constructor(e,t,i=F(),r=new Z){super(e,t,i,r)}async execute(){let e=this.resolveOrgId(),t=this.resolveVersionOption(this.options);y.debug(`[catalog:publish] Starting publish flow with options: file=${this.options.file}, name=${this.options.name}, scope=${this.options.scope}, version=${t}, org=${e}, lifecycle=${this.options.lifecycle}`);let i=await this.resolveFileId(e),r=await this.resolveName(),s=await this.resolveDescription(),o=await this.resolveScope(),a=await this.resolveVersion(t),n=this.validateLifecycle(this.options.lifecycle);try{let l=await this.resolveOrCreateCatalogId(i,e,r,s,o),d=await this.publishVersion(l,o,n,a,this.options.changelog);this.formatter.success(`Successfully published version '${a}' to the data catalog!`,d)}catch(l){let d=U(l);this.formatter.error(d),process.exit(1)}}async resolveFileId(e){let t=this.options.file;if(!t&&process.stdout.isTTY){y.debug("[catalog:publish] File ID not provided; listing data domain files for selection...");try{let r=(await this.client.files.list(e,{filter:{field:"kind",operator:"eq",value:ni}},{token:this.client.token})).data||[];r.length>0&&(t=await Ce("Select a data domain file to publish:",r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch{}}return t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1)),t}async resolveName(){let e=this.options.name;return!e&&process.stdout.isTTY&&(e=await pe("Enter catalog entry name:")),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1)),e}async resolveDescription(){let e=this.options.description;return!e&&process.stdout.isTTY&&(e=await pe("Enter catalog entry description:")),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Description is required.",detail:"Specify --description <desc>."}),process.exit(1)),e}async resolveScope(){let e=this.options.scope;return!e&&process.stdout.isTTY&&(e=await Ce("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Scope is required.",detail:"Specify --scope <scope> (allowed: public, organization, private)."}),process.exit(1)),c.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'.`,detail:`Allowed: ${c.ALLOWED_SCOPES.join(", ")}`}),process.exit(1)),e}async resolveVersion(e){let t=e;return!t&&process.stdout.isTTY&&(t=await pe("Enter semantic version:","1.0.0")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Version is required.",detail:"Specify --catalog-version <ver> or --ver <ver>."}),process.exit(1)),t}validateLifecycle(e){return c.ALLOWED_LIFECYCLES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${e}'.`,detail:`Allowed: ${c.ALLOWED_LIFECYCLES.join(", ")}`}),process.exit(1)),e}async resolveOrCreateCatalogId(e,t,i,r,s){y.debug(`[catalog:publish] Checking publication status for file ID '${e}' in organization '${t}'...`);let o=null;try{o=(await this.client.dataCatalog.checkPublicationStatus(e,t,{token:this.client.token})).key,y.debug(`[catalog:publish] Found existing catalog entry key: ${o}`)}catch(a){if(U(a).status!==404)throw a;y.debug("[catalog:publish] Catalog entry does not exist yet.")}if(o)y.debug(`[catalog:publish] Using existing catalog entry key: ${o}`),N.resolved.format!=="json"&&console.log(`Catalog entry already exists (ID: ${o}). Publishing new version...`);else{y.debug("[catalog:publish] Creating a new catalog entry..."),N.resolved.format!=="json"&&console.log("Catalog entry does not exist. Creating new catalog entry...");let a={key:"",kind:wt,organization:t,file:e,scope:s,name:i,description:r,publishedBy:"",publishedAt:0,createdAt:0,updatedAt:0,tags:[]};o=(await this.client.dataCatalog.publish(a,{token:this.client.token})).key,y.debug(`[catalog:publish] Created new catalog entry with key: ${o}`)}return o}async publishVersion(e,t,i,r,s){let o=Li.createSchema({scope:t,lifecycle:i,version:r,changelog:s||void 0});y.debug(`[catalog:publish] Publishing version '${r}' for catalog key '${e}'...`);let a=await this.client.dataCatalog.publishVersion(e,o,{token:this.client.token});return y.debug(`[catalog:publish] Version published successfully. Version key: ${a.key}`),a}};var Cn=class c extends Ke{static ALLOWED_SCOPES=["all","public","organization","private"];constructor(e,t,i=F()){super(e,t,i)}async execute(){let e=this.options.org||N.resolved.org;y.debug(`[catalog:list] Listing catalog with options: scope=${this.options.scope}, org=${e}, key=${this.options.key}`),this.validateScope(this.options.scope),this.ensureOrgIdIfRequired(this.options.scope,e);try{this.options.key?await this.listVersions(this.options.key):await this.listItems(this.options.scope,e)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}validateScope(e){c.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'. Allowed: ${c.ALLOWED_SCOPES.join(", ")}`}),process.exit(1))}ensureOrgIdIfRequired(e,t){["organization","private"].includes(e)&&!t&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:`Organization ID (--org <oid>) is required when filtering by scope '${e}'.`}),process.exit(1))}async listVersions(e){y.debug(`[catalog:list] Fetching versions for catalog entry key '${e}'...`);let i=(await this.client.dataCatalog.listVersions(e,{token:this.client.token})).data||[];y.debug(`[catalog:list] Found ${i.length} versions.`);let r=i.map(s=>({key:s.key,version:s.version,published:new Date(s.published).toLocaleString()}));this.formatter.list(r,["key","version","published"],{headers:["VERSION KEY","VERSION","PUBLISHED AT"]})}async listItems(e,t){let i=await this.fetchEntries(e,t),r=this.deduplicateEntries(i);this.formatItems(r)}async fetchEntries(e,t){let i=[];if(e==="all"){y.debug("[catalog:list] Fetching public catalog entries...");let r=await this.fetchScope("public",t);if(i.push(...r),t){y.debug(`[catalog:list] Fetching organization catalog entries for org '${t}'...`);let s=await this.fetchScope("organization",t);i.push(...s),y.debug(`[catalog:list] Fetching private catalog entries for org '${t}'...`);let o=await this.fetchScope("private",t);i.push(...o)}}else{y.debug(`[catalog:list] Fetching catalog entries for scope '${e}' and org '${t}'...`);let r=await this.fetchScope(e,t);i.push(...r)}return i}async fetchScope(e,t){try{return(await this.client.dataCatalog.list({scope:e,oid:t},{token:this.client.token})).data||[]}catch{return y.debug(`[catalog:list] Failed to fetch catalog entries for scope '${e}'.`),[]}}deduplicateEntries(e){y.debug(`[catalog:list] Total raw catalog entries fetched: ${e.length}`);let t=new Set,i=e.filter(r=>{let s=r.key;return t.has(s)?!1:(t.add(s),!0)});return y.debug(`[catalog:list] Total unique catalog entries: ${i.length}`),i}formatItems(e){let t=e.map(i=>{let r=i.versions&&i.versions[0]?i.versions[0].version:"N/A";return{key:i.key,name:i.name,scope:i.scope,lastVersion:r,organization:i.organization||"N/A"}});this.formatter.list(t,["key","name","scope","lastVersion","organization"],{headers:["KEY","NAME","SCOPE","LAST VERSION","ORGANIZATION"]})}};var Dn=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);y.debug(`[catalog:show] Reading catalog entry key='${this.key}', version='${e||"latest"}'`);try{if(e){let t=await this.client.dataCatalog.readVersion(this.key,e,{token:this.client.token});this.formatter.object(t)}else{let t=await this.client.dataCatalog.read(this.key,{token:this.client.token});this.formatter.object(t)}}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var Ln=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options),t=await this.resolveReason();try{if(e){y.debug(`[catalog:deprecate] Deprecating version '${e}' of catalog entry '${this.key}'...`);let i=await this.client.dataCatalog.deprecateVersion(this.key,e,t,{token:this.client.token});this.formatter.success(`Successfully deprecated version '${e}' of data catalog entry '${this.key}'.`,i)}else{y.debug(`[catalog:deprecate] Deprecating catalog entry '${this.key}'...`);let i=await this.client.dataCatalog.deprecate(this.key,t,{token:this.client.token});this.formatter.success(`Successfully deprecated data catalog entry '${this.key}'.`,i)}}catch(i){let r=U(i);this.formatter.error(r),process.exit(1)}}async resolveReason(){let e=this.options.reason;return!e&&process.stdout.isTTY&&(e=await pe("Enter reason for deprecation:")),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Deprecation reason is required.",detail:"Specify --reason <reason>."}),process.exit(1)),e}};var Mn=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);try{if(e){y.debug(`[catalog:unpublish] Unpublishing version '${e}' of catalog entry '${this.key}'...`);let t=await this.client.dataCatalog.unpublishVersion(this.key,e,{token:this.client.token});this.formatter.success(`Successfully unpublished version '${e}' of data catalog entry '${this.key}'.`,t)}else{y.debug(`[catalog:unpublish] Unpublishing catalog entry '${this.key}'...`);let t=await this.client.dataCatalog.unpublish(this.key,{token:this.client.token});this.formatter.success(`Successfully unpublished data catalog entry '${this.key}'.`,t)}}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var Un=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);try{let i=(await this.fetchUsageFiles(e)).data||[];this.formatUsageRows(i)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}async fetchUsageFiles(e){return e?(y.debug(`[catalog:dependent-apis] Fetching usage files for catalog entry '${this.key}' version '${e}'`),await this.client.dataCatalog.getVersionUsageFiles(this.key,e,{token:this.client.token})):(y.debug(`[catalog:dependent-apis] Fetching usage files for catalog entry '${this.key}'`),await this.client.dataCatalog.getUsageFiles(this.key,{token:this.client.token}))}formatUsageRows(e){let t=e.map(i=>({fileId:i.value.key,name:i.value.info?.name||"Unnamed",version:i.meta?.version||"N/A"}));this.formatter.list(t,["fileId","name","version"],{headers:["FILE ID","NAME","VERSION USED"]})}};var zn=class extends Ke{fid;constructor(e,t,i,r=F()){super(t,i,r),this.fid=e}async execute(){let e=this.options.org||N.resolved.org;try{y.debug(`[catalog:status] Checking publication status for file '${this.fid}' in org '${e||"N/A"}'`);let t=await this.client.dataCatalog.checkPublicationStatus(this.fid,e,{token:this.client.token});this.formatter.object(t)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};function cp(c){let e=c.command("catalog").description("Manage Data Catalog items");e.command("publish").description("Publish a data domain file to the data catalog").option("--file <fid>","File ID of the data domain").option("--name <name>","Name for the catalog entry").option("--description <desc>","Description of the catalog entry").option("--scope <scope>","Publish scope: public, organization, private").option("--catalog-version <ver>","Semantic version (e.g. 1.0.0)").option("--ver <ver>","Semantic version alias (e.g. 1.0.0)").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--lifecycle <lifecycle>","Version lifecycle status (dev, beta, stable)","stable").option("--changelog <changelog>","Changelog description for this version").action(async t=>{let i=new K({format:N.resolved.format});await new jn(t,i).execute()}),e.command("list").description("List published data catalog items or versions of a specific catalog entry").option("--scope <scope>","Filter by scope: all, public, organization, private","all").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--key <key>","Data catalog item key to list all versions of a specific data domain").action(async t=>{let i=new K({format:N.resolved.format});await new Cn(t,i).execute()}),e.command("show <key>").alias("read").description("Show details of a data catalog entry or a specific version").option("--catalog-version <ver>","Semantic version to read").option("--ver <ver>","Semantic version alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Dn(t,i,r).execute()}),e.command("deprecate <key>").description("Mark a data catalog entry or specific version as deprecated").option("--catalog-version <ver>","Version string to deprecate").option("--ver <ver>","Version string alias").option("--reason <reason>","Reason for deprecating this catalog entry or version").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Ln(t,i,r).execute()}),e.command("unpublish <key>").description("Unpublish (mark as private) a data catalog entry or specific version").option("--catalog-version <ver>","Version string to unpublish").option("--ver <ver>","Version string alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Mn(t,i,r).execute()}),e.command("dependent-apis <key>").alias("usage").description("List all APIs referencing a published data catalog item or version").option("--catalog-version <ver>","Filter usage by a specific version").option("--ver <ver>","Filter usage by a specific version alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Un(t,i,r).execute()}),e.command("status <fid>").description("Check the publication status and versions of a data domain file").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new zn(t,i,r).execute()})}var Er=class extends Ae{client;fileManager;constructor(e,t,i=F(),r=new Z){super(e,t),this.client=i,this.fileManager=r}ensureAuth(){return ci(this.client,this.formatter)}async resolveApiId(e,t){let i=this.findProvidedApiId(e);if(i)return i;if(process.stdout.isTTY&&t){let r=await this.selectApiIdInteractively(t);if(r)return r}this.failMissingApiId()}findProvidedApiId(e){return e||this.options.api||this.options.file||this.options.id}async selectApiIdInteractively(e){y.debug("[deployment] API ID not provided; searching API model files for interactive selection...");try{let t=await this.fileManager.search(e,{kind:"api"});if(t.length>0)return await Ce("Select an API model file:",t.map(i=>({name:`${i.info?.name||"Unnamed"} (${i.key})`,value:i.key})));this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"No API models found.",detail:`No API models found in organization '${e}'. Create one first using \`apinow api create\`.`}),process.exit(1)}catch(t){y.debug(`[deployment] Failed to search API files for selection: ${t}`)}}failMissingApiId(){this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"API ID is required.",detail:"Provide an API ID as an argument or specify --api <id> (or --file <fid>, --id <fid>)."}),process.exit(1)}async resolveDeploymentId(e){let t=this.findProvidedDeploymentId(e);if(t)return t;if(process.stdout.isTTY){let i=await this.askDeploymentIdInteractively();if(i)return i}this.failMissingDeploymentId()}findProvidedDeploymentId(e){return e||this.options.id||this.options.deployment}async askDeploymentIdInteractively(){try{return await pe("Enter deployment ID:")||void 0}catch(e){y.debug(`[deployment] Failed to read deployment ID interactively: ${e}`);return}}failMissingDeploymentId(){this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Deployment ID is required.",detail:"Provide a deployment ID as an argument or specify --id <id> (or --deployment <id>)."}),process.exit(1)}};var Vn=class extends Er{api;constructor(e,t,i,r=F(),s=new Z){super(t,i,r,s),this.api=e}async execute(){y.debug("[deployment:list] Listing deployments for an API...");try{this.ensureAuth();let e=this.resolveOrgId("Organization ID is required.","Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."),t=await this.resolveApiId(this.api,e),i=await this.fetchDeployments(e,t);this.formatOutput(i)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}async fetchDeployments(e,t){y.debug(`[deployment:list] Fetching deployments for API '${t}' in org '${e}'...`);let i=this.options.limit?{limit:this.options.limit}:void 0,s=(await this.client.deployments.apis.listDeployments(e,t,i,{token:this.client.token})).data||[];return y.debug(`[deployment:list] Found ${s.length} deployments.`),s}formatOutput(e){let t=e.map(i=>this.toRow(i));this.formatter.list(t,["id","env","version","modelVersion","status","default","baseUri"],{headers:["ID","ENV","VERSION","MODEL VER","STATUS","DEFAULT","BASE URI"]})}toRow(e){return{id:e.key,env:e.env,version:e.version||"-",modelVersion:e.modelVersion,status:e.status,default:e.isDefault?"Yes":"No",baseUri:e.baseUri||"-"}}};var Fn=class extends Er{id;constructor(e,t,i,r=F(),s=new Z){super(t,i,r,s),this.id=e}async execute(){y.debug("[deployment:read] Reading deployment details...");try{this.ensureAuth();let e=this.resolveOrgId("Organization ID is required.","Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."),t=await this.resolveDeploymentId(this.id),i=await this.fetchDeployment(e,t);this.formatter.object(i)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}async fetchDeployment(e,t){y.debug(`[deployment:read] Fetching deployment '${t}' in org '${e}'...`);let i=await this.client.deployments.read(e,t,{token:this.client.token});return y.debug(`[deployment:read] Deployment retrieved successfully: ${i.key}`),i}};function lp(c){let e=c.command("deployment").description("Manage API deployments");e.command("list [api]").description("List deployments for an API").option("--api <apiId>","API model file ID").option("--file <fid>","API model file ID (alias)").option("--id <fid>","API model file ID (alias)").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--limit <limit>","Maximum number of results to return",Yi).action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Vn(t,i,r).execute()}),e.command("read [id]").alias("get").description("Read details of a deployment").option("--id <id>","Deployment ID").option("--deployment <id>","Deployment ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Fn(t,i,r).execute()})}var qn=class extends Ae{async execute(){y.debug("[runtime:update] Executing runtime user update...");try{let e=F();ci(e,this.formatter);let t=this.resolveOrgId("Organization ID is not specified.","Use --org <oid> or configure a default organization.");y.debug(`[runtime:update] Using organization ID: ${t}`),y.debug("[runtime:update] Parsing properties...");let i=this.parseProperties(this.options.property),r={};for(let[o,a]of Object.entries(i)){let n=["token","password","secret","key"].some(l=>o.toLowerCase().includes(l));r[o]=n?"**********":a}y.debug(`[runtime:update] Parsed properties: ${JSON.stringify(r)}`),y.debug(`[runtime:update] Sending request to update runtime user ID '${this.options.userId}' in environment '${this.options.env}' for api '${this.options.api}'...`);let s=await e.deployments.apis.updateRuntimeUser(t,this.options.api,this.options.userId,i,this.options.env,{token:e.token});y.debug("[runtime:update] Runtime user updated successfully."),this.formatter.success(`User '${this.options.userId}' updated successfully!`,s)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}parseProperties(e){let t={};for(let i of e){let r=i.split("=");if(r.length<2)throw new Error(`Invalid property format: '${i}'. Expected 'name=value'.`);let s=r[0].trim(),o=r.slice(1).join("=").trim();o==="true"?t[s]=!0:o==="false"?t[s]=!1:o==="null"?t[s]=null:/^\d+$/.test(o)?t[s]=parseInt(o,10):/^\d*\.\d+$/.test(o)?t[s]=parseFloat(o):t[s]=o}return t}};function dp(c){c.command("runtime").description("Administrative operations for the API runtime").command("users").description("Administrative operations for users").command("update").description("Update properties of a user directly in the runtime database").requiredOption("--api <api>","API file ID or slug").requiredOption("--user-id <userId>","Primary key of the user record to update").requiredOption("--property <name=value...>","Properties to update in the format name=value (can specify multiple)").option("--org <oid>","Organization ID (defaults to configured org)").option("--env <environment>",'Target environment (e.g. "production", "staging")',"production").action(async i=>{let r=new K({format:N.resolved.format});y.debug("[runtime:update] Starting runtime user update process..."),await new qn(i,r).execute()})}import Je from"node:fs/promises";import st from"node:path";import nh from"node:os";var Kn=class{constructor(e){this.rootProgram=e}rootProgram;extractTree(e=this.rootProgram){let i=(e.options||[]).map(o=>({flags:o.flags,long:o.long,short:o.short,description:o.description||"",choices:o.argChoices})),r=(e.commands||[]).map(o=>this.extractTree(o)),s=typeof e.aliases=="function"?e.aliases():[];return{name:e.name(),aliases:s,description:e.description()||"",options:i,subcommands:r}}generateScript(e){let t=this.extractTree(),i=t.name||"apinow";switch(e){case"zsh":return this.generateZsh(i,t);case"bash":return this.generateBash(i,t);case"fish":return this.generateFish(i,t);default:throw new Error(`Unsupported shell: ${e}`)}}escapeZsh(e){return e.replace(/[':\\]/g,"\\$&").replace(/\n/g," ")}getNodeFlags(e){let t=[];for(let i of e.options)i.long&&!t.includes(i.long)&&t.push(i.long),i.short&&!t.includes(i.short)&&t.push(i.short);return t.includes("--help")||t.push("--help"),t.includes("-h")||t.push("-h"),t}getNodeOptionZshDescriptions(e){let t=[],i=new Set;for(let r of e.options){let s=this.escapeZsh(r.description||r.flags);r.long&&!i.has(r.long)&&(i.add(r.long),t.push(`'${r.long}:${s}'`)),r.short&&!i.has(r.short)&&(i.add(r.short),t.push(`'${r.short}:${s}'`))}return i.has("--help")||t.push("'--help:Display help for command'"),i.has("-h")||t.push("'-h:Display help for command'"),t}renderZshCases(e,t){let i=" ".repeat(t),r=[];for(let s of e){let o=[s.name,...s.aliases].join("|"),a=this.getNodeOptionZshDescriptions(s),n=`local -a ${s.name}_options=(
|
|
1856
|
+
`}};var mn=class extends et{file;client;deploymentRecord;constructor(e,t,i,r=new Z,s=F()){super(t,i,r),this.file=e,this.client=s}async execute(){y.debug(`[api:sdk] Executing SDK generation. File=${this.file}, stdin=${this.options.stdin}`);try{this.validateInputParameters();let e=await this.loadApiModelSchema(),t=await this.resolveDataDomain(e),i=new Ei(e,t),r=await this.resolveBaseUrl(e),s=this.generateSdkFiles(i,r);await this.writeOutput(s)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}get shouldReadFromStdin(){return!!(this.options.stdin||this.file==="-")}get isLocalFile(){let e=this.file||this.options.file;return e?xi.existsSync(e)||e.includes("/")||e.includes("\\")||e.endsWith(".json"):!1}validateInputParameters(){this.options.deployment&&(this.options.stdin||this.file==="-")&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --deployment and STDIN"}),process.exit(1)),this.options.deployment&&this.isLocalFile&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both a local file path and --deployment",detail:"--deployment resolves the API model directly from the cloud deployment."}),process.exit(1)),(this.file||this.options.file||this.options.id)&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),this.file&&(this.file.includes("/")||this.file.includes("\\")||this.file.endsWith(".json"))&&(xi.existsSync(this.file)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${un.resolve(this.file)}`}),process.exit(1))),this.options.standalone&&!this.options.packageName&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Package name is required when generating a standalone SDK package.",detail:"Specify --package-name <name> (e.g. --package-name @my-org/api-sdk)."}),process.exit(1))}async loadApiModelSchema(){return this.options.deployment?this.loadFromDeployment(this.options.deployment):this.shouldReadFromStdin?this.loadFromStdin():this.file&&xi.existsSync(this.file)?this.loadFromLocalFile(this.file):this.loadFromRemote()}async loadFromDeployment(e){let t=this.resolveOrgId();y.debug(`[api:sdk] Fetching deployment '${e}' in org '${t}'...`);let i=await this.client.deployments.read(t,e,{token:this.client.token});return this.deploymentRecord=i,i.apiId||(this.formatter.error({code:"CLI_ERR_API_FAILURE",message:`Deployment '${e}' does not have an attached API file ID.`}),process.exit(1)),this.validateDeploymentFileMatch(i),this.loadRemoteApiSchema(t,i.apiId)}validateDeploymentFileMatch(e){let t=[this.file,this.options.file,this.options.id].filter(Boolean);for(let i of t)i!==e.apiId&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`API file ID mismatch: provided '${i}', but deployment '${e.key}' is attached to API file '${e.apiId}'.`,detail:`Omit the file argument or pass '${e.apiId}'.`}),process.exit(1))}async loadFromStdin(){y.debug("[api:sdk] Reading API model schema from STDIN...");let e=await this.fileManager.readStdin(),t;try{t=JSON.parse(e)}catch(i){let r=i instanceof Error?i.message:String(i);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse schema JSON from STDIN: ${r}`}),process.exit(1)}return this.validateSchemaKind(t),t}loadFromLocalFile(e){let t=un.resolve(e);y.debug(`[api:sdk] Reading local API model file from path: ${t}`);let i;try{i=xi.readFileSync(t,"utf8")}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to read file at ${t}: ${o}`}),process.exit(1)}let r;try{r=JSON.parse(i)}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse JSON file at ${t}: ${o}`}),process.exit(1)}return this.validateSchemaKind(r),r}async loadFromRemote(){let e=this.resolveOrgId(),t=await this.resolveTargetFileId(e);return this.loadRemoteApiSchema(e,t)}async loadRemoteApiSchema(e,t){y.debug(`[api:sdk] Fetching file metadata for ID '${t}' in org '${e}'...`);let i=await this.fileManager.read(e,t);i.kind!==Yt&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File '${t}' is not an API model. The file kind is '${i.kind}', but expected '${Yt}'.`}),process.exit(1)),y.debug(`[api:sdk] Fetching media schema for API model ID '${t}'...`);let r=await this.fileManager.readMedia(e,t);return this.validateSchemaKind(r.media),r.media}async resolveTargetFileId(e){let t=this.options.file||this.options.id||(this.file&&!xi.existsSync(this.file)?this.file:void 0);return t||this.resolveFileId(e,"Select an API model file to generate SDK for:")}validateSchemaKind(e){(!e||typeof e!="object"||Array.isArray(e))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid API model schema. Expected a JSON object."}),process.exit(1));let t=e;t.kind!==ke&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${String(t.kind)}', but expected '${ke}'.`}),process.exit(1))}async resolveDataDomain(e){if(this.options.domain)return this.loadLocalDomain(this.options.domain);let t=e.dependencyList||[];return this.resolveCatalogDomain(t,e.info?.name||e.key)}loadLocalDomain(e){let t=un.resolve(e);y.debug(`[api:sdk] Loading local Data Domain schema from: ${t}`),xi.existsSync(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${t}`}),process.exit(1));let i;try{i=JSON.parse(xi.readFileSync(t,"utf8"))}catch(s){let o=s instanceof Error?s.message:String(s);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${o}`}),process.exit(1)}(!i||typeof i!="object"||Array.isArray(i))&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Invalid Data Domain schema. Expected a JSON object."}),process.exit(1));let r=i;return r.kind!==Ee&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid Data Domain schema. The media kind is '${String(r.kind)}', but expected '${Ee}'.`}),process.exit(1)),new Me(i,[],{readOnly:!0})}async resolveCatalogDomain(e,t){e.length===0&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`API model '${t}' does not have a data domain dependency attached. SDK generation requires an attached data domain.`}),process.exit(1)),y.debug(`[api:sdk] Resolving ${e.length} dependency from data catalog...`);let r=(await this.client.dataCatalog.listDependencies(e,{token:this.client.token})).data||[];r.length===0&&(this.formatter.error({code:"CLI_ERR_API_FAILURE",message:`Could not resolve data domain dependency for API model '${t}' from the data catalog. Ensure the data domain is published in the catalog.`}),process.exit(1));let s=e[0]?.key,o=r.find(a=>a.key===s)??r[0];return new Me(o,r,{readOnly:!0})}async resolveBaseUrl(e){if(this.options.baseUrl)return y.debug(`[api:sdk] Using explicit base URL: ${this.options.baseUrl}`),this.options.baseUrl;if(this.deploymentRecord)return this.extractBaseUri(this.deploymentRecord);if(process.stdout.isTTY&&!this.isLocalOnlyMode())return this.promptBaseUrlStrategy(e);y.debug("[api:sdk] No base URL specified. Consumers must provide baseUrl at SDK initialization.")}isLocalOnlyMode(){return!!(this.options.stdin||this.file&&xi.existsSync(this.file))}async promptBaseUrlStrategy(e){let t=await Ce("How should the SDK resolve the base URL?",[{name:"Select from a deployment",value:"deployment"},{name:"Enter a custom URL",value:"custom"},{name:"Skip \u2014 require at SDK initialization",value:"skip"}]);if(t==="deployment")return this.resolveBaseUrlFromDeploymentSelection(e);if(t==="custom"){let i=await pe("Enter the base URL:");if(!i){y.debug("[api:sdk] Empty base URL entered. SDK will require baseUrl at initialization.");return}return i}}async resolveBaseUrlFromDeploymentSelection(e){let t=this.resolveOrgId(),i=this.options.file||this.options.id||e.key;y.debug(`[api:sdk] Listing deployments for API '${i}' in org '${t}'...`);let s=((await this.client.deployments.apis.listDeployments(t,i,void 0,{token:this.client.token})).data||[]).filter(a=>a.status===Nr.Active&&a.baseUri);if(s.length===0){y.warn("[api:sdk] No active deployments with a base URI found. Skipping base URL injection."),console.error("Warning: No active deployments with a base URI found. Skipping base URL injection.");return}let o=await Ce("Select a deployment to read the base URL from:",s.map(a=>({name:`${a.env} ${a.version?`(${a.version})`:""} \u2014 ${a.baseUri}`,value:a})));return this.extractBaseUri(o)}extractBaseUri(e){if(!e.baseUri){y.warn(`[api:sdk] Deployment '${e.key}' does not have a base URI.`),console.error(`Warning: Deployment '${e.key}' does not have a base URI. SDK will require baseUrl at initialization.`);return}return y.debug(`[api:sdk] Resolved base URL from deployment: ${e.baseUri}`),e.baseUri}generateSdkFiles(e,t){return y.debug("[api:sdk] Generating SDK source files using SdkGenerator..."),new dn(e).generate(t?{baseUrl:t}:void 0)}async writeOutput(e){let t=un.resolve(this.options.output||"."),i=this.options.standalone??!1;y.debug(`[api:sdk] Writing SDK to: ${t} (standalone=${i}, files=${e.size})`),await new pn().write(t,e,{standalone:i,packageName:this.options.packageName}),this.formatter.success(`SDK generated successfully (${e.size} files) at ${t}`)}};function ip(c){let e=c.command("api").description("Manage API models");e.command("list").description("List API model files in an organization").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Filter by parent folder ID").action(async t=>{let i=new K({format:N.resolved.format});await new sa(t,i).execute()}),e.command("search [query]").description("Search API model files by name or keyword").option("--query <query...>","Search query keywords").option("--parent <parent>","Filter by parent folder ID").option("--limit <limit>","Maximum number of results to return",Yi).option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new na(t,i,r).execute()}),e.command("create").description("Create a new API model file record (and optionally upload API model schema media)").option("--name <name>","Name of the API model").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--parent <parent>","Parent folder ID").option("--media <path>","Local path to the API model schema JSON to upload").option("--stdin","Read API model schema content from STDIN").action(async t=>{let i=new K({format:N.resolved.format});await new oa(t,i).execute()}),e.command("read").description("Read API model file metadata or schema media content").option("--file <fid>","File ID of the API model").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--meta","Read file metadata (default)").option("--media","Read API model schema media content").action(async t=>{let i=new K({format:N.resolved.format});await new aa(t,i).execute()}),e.command("oas [file]").description("Generate an OpenAPI Specification (OAS 3.1) from an API model").option("--file <fid>","File ID of the API model").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--domain <path>","Path to local Data Domain schema file (optional override or for local models)").option("-o, --output <path>","Output file path (defaults to stdout)").option("--stdin","Read API model schema content from STDIN").option("--server <urls...>","Server URL(s) to include in the generated OpenAPI spec").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Ya(t,i,r).execute()}),e.command("sdk [file]").description("Generate a TypeScript client SDK from an API model").option("--file <fid>","File ID of the API model").option("--id <fid>","File ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--domain <path>","Path to local Data Domain schema file (optional override or for local models)").option("-o, --output <path>","Output directory path (defaults to current working directory)").option("--stdin","Read API model schema content from STDIN").option("--standalone","Generate a standalone npm package with package.json and tsconfig.json").option("--package-name <name>","npm package name (required when --standalone is set)").option("--base-url <url>","Base URL to bake into the generated SDK client").option("--deployment <did>","Deployment ID to resolve the API model and base URL from").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new mn(t,i,r).execute()})}import Nn from"node:fs";import ap from"node:path";var gt=class{model;domain;report=[];cachedUserEntity;cachedOrgEntity;cachedProjectEntity;cachedUserSemantics;cachedOrgSemantics;constructor(e){this.model=e,this.domain=e.domain}addIssue(e){this.report.push(e)}addIssues(e){e.length>0&&this.report.push(...e)}getUserEntity(){return this.cachedUserEntity===void 0&&(this.cachedUserEntity=this.domain?tl(this.domain,this.model.user)??null:null),this.cachedUserEntity??void 0}getOrganizationEntity(){if(this.cachedOrgEntity===void 0)if(!this.domain)this.cachedOrgEntity=null;else{let e=Array.from(this.domain.listEntities({includeForeign:!0})).find(t=>t.hasSemantic(g.Organization));this.cachedOrgEntity=e??null}return this.cachedOrgEntity??void 0}getProjectEntity(){if(this.cachedProjectEntity===void 0)if(!this.domain)this.cachedProjectEntity=null;else{let e=Array.from(this.domain.listEntities({includeForeign:!0})).find(t=>t.hasSemantic(g.Project));this.cachedProjectEntity=e??null}return this.cachedProjectEntity??void 0}getUserSemantics(){if(this.cachedUserSemantics===void 0)if(!this.domain)this.cachedUserSemantics=null;else{let e=this.getUserEntity();this.cachedUserSemantics=As(this.domain,e)}return this.cachedUserSemantics??void 0}getOrganizationSemantics(){return this.cachedOrgSemantics===void 0&&(this.cachedOrgSemantics=this.domain?Es(this.domain):null),this.cachedOrgSemantics??void 0}findEntity(e,t){return this.domain?.findEntity(e,t)}findAssociation(e,t){return this.domain?.findAssociation(e,t)}hasSessionConfigured(){return!!this.model.session}isSessionPropertyConfigured(e){return this.model.session?.properties?this.model.session.properties.some(t=>t.key===e):!1}getConfiguredSessionPropertyKeys(){if(this.model.session)return new Set(this.model.session.properties?.map(e=>e.key).filter(Boolean)??[])}};function v(c,e){return`${c}_${e}`}function hn(c){let e=[];c.children.length===0&&e.push(c);for(let t of c.children)t instanceof qe&&e.push(...hn(t));return e}function Ps(c){return c.children.length===0?!1:c.style==="and"?c.children.some(e=>e instanceof qe?Ps(e):e.isIdentityConstraining):c.children.every(e=>e instanceof qe?Ps(e):e.isIdentityConstraining)}var fn=class{ruleType="matchUserRole";validate(e,t,i,r,s){let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},a=s.domain,n=["allowlist","denylist","minRole","maxRole"],l;if(a){let d=s.getUserSemantics(),p=d?.userEntity??s.getUserEntity();if(!p)s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match user role" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o});else if(!d?.roleProperty)s.addIssue({code:v("RULE","MATCH_USER_ROLE_MISSING_ROLE_PROPERTY"),message:`The User entity "${p.info.getLabel()}" has no property with the UserRole data semantic.`,suggestion:"Add a property with the UserRole semantic to the User entity to use role-based authorization.",severity:"error",context:o});else if(l=d.roleProperty,s.hasSessionConfigured()&&!s.isSessionPropertyConfigured(l.key)){let m=l.info.getLabel()??l.key;s.addIssue({code:v("RULE","USER_ROLE_NOT_IN_SESSION"),message:`The role property "${m}" used in the "Match user role" rule is not included in the session configuration properties.`,suggestion:"Add the role property to the session properties in the API Model session configuration.",severity:"error",context:o})}}if((!e.mode||!n.includes(e.mode))&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_INVALID_MODE"),message:`The "matchUserRole" access rule has an invalid or missing mode "${e.mode??""}". Valid modes are: allowlist, denylist, minRole, maxRole.`,suggestion:"Set the mode to one of: allowlist, denylist, minRole, or maxRole.",severity:"error",context:o}),e.roleMatch!==void 0&&e.roleMatch!=="any"&&e.roleMatch!=="all"&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_INVALID_ROLE_MATCH"),message:`The "matchUserRole" access rule has an invalid roleMatch "${e.roleMatch}". Valid values are: any, all.`,suggestion:'Set roleMatch to either "any" or "all", or omit it to use the default.',severity:"error",context:o}),e.mode==="allowlist")!e.allowed||!Array.isArray(e.allowed)?s.addIssue({code:v("RULE","MATCH_USER_ROLE_ALLOWLIST_MISSING_ALLOWED"),message:'The "matchUserRole" access rule is in allowlist mode, but no "allowed" list is specified.',suggestion:'Add an "allowed" list with the roles that should be permitted access.',severity:"error",context:o}):e.allowed.length===0&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_ALLOWLIST_EMPTY"),message:'The "matchUserRole" access rule has an empty "allowed" list. Access will be denied for all users.',suggestion:"Add at least one role to the allowed list, or remove this rule if all access should be denied.",severity:"warning",context:o});else if(e.mode==="denylist")!e.denied||!Array.isArray(e.denied)?s.addIssue({code:v("RULE","MATCH_USER_ROLE_DENYLIST_MISSING_DENIED"),message:'The "matchUserRole" access rule is in denylist mode, but no "denied" list is specified.',suggestion:'Add a "denied" list with the roles that should be blocked from access.',severity:"error",context:o}):e.denied.length===0&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_DENYLIST_EMPTY"),message:'The "matchUserRole" access rule has an empty "denied" list. All authenticated users will be granted access.',suggestion:"Add at least one role to the denied list to block specific roles, or replace this with an allowAuthenticated rule.",severity:"warning",context:o});else if(e.mode==="minRole"||e.mode==="maxRole"){let d=e.mode==="minRole",p=d?"minimumRole":"maximumRole",m=d?e.minimumRole:e.maximumRole,h=d?"minimum":"maximum";if((!m||typeof m!="string"||m.trim()==="")&&s.addIssue({code:v("RULE",d?"MATCH_USER_ROLE_MIN_ROLE_MISSING":"MATCH_USER_ROLE_MAX_ROLE_MISSING"),message:`The "matchUserRole" access rule is in ${e.mode} mode, but "${p}" is not specified.`,suggestion:`Specify the ${h} required role name in the "${p}" field.`,severity:"error",context:o}),a&&l){let f=l.schema?.enum,k=l.info.getLabel()??l.key;!f||!Array.isArray(f)||f.length===0?s.addIssue({code:v("RULE","MATCH_USER_ROLE_ENUM_REQUIRED"),message:`The role property "${k}" must have an enum defined with at least one role for "${e.mode}" mode.`,suggestion:"Define an enum on the UserRole property schema specifying roles in privilege order.",severity:"error",context:o}):m&&!f.includes(m)&&s.addIssue({code:v("RULE",d?"MATCH_USER_ROLE_MIN_ROLE_NOT_IN_ENUM":"MATCH_USER_ROLE_MAX_ROLE_NOT_IN_ENUM"),message:`The "${p}" value "${m}" does not exist in the UserRole enum. Valid roles are: ${f.join(", ")}.`,suggestion:"Choose a role name that exists in the UserRole enum. Remember that enum order is the privilege order \u2014 index 0 is least privileged.",severity:"error",context:o}),e.mode==="maxRole"&&l.multiple&&e.roleMatch!=="all"&&s.addIssue({code:v("RULE","MATCH_USER_ROLE_MAX_ROLE_ANY_ON_MULTI"),message:`The "matchUserRole" access rule uses "maxRole" mode on a multi-role property without roleMatch: 'all'. Users holding a higher role will still be granted access if any of their other roles is at or below "${m}".`,suggestion:`Set roleMatch to "all" if you want all roles held by the user to be at or below "${m}", or keep roleMatch as "any" if matching any role is intended.`,severity:"warning",context:o})}}if(a&&l&&(e.mode==="allowlist"||e.mode==="denylist")){let d=l.schema?.enum;if(Array.isArray(d)){let p=e.mode==="allowlist"?e.allowed:e.denied,m=e.mode==="allowlist"?"allowed":"denied";if(Array.isArray(p))for(let h of p)d.includes(h)||s.addIssue({code:v("RULE","MATCH_USER_ROLE_INVALID_ROLE_VALUE"),message:`The role "${h}" in the "${m}" list does not exist in the UserRole enum.`,suggestion:`Remove "${h}" or correct it to a valid UserRole enum value: ${d.join(", ")}.`,severity:"warning",context:o})}}}};function Rs(c,e,t){if(!c||!c.parent)return!1;let i=t?.domain??e.domain;if(!i)return!1;let r=c.parent.key,s=new Set([c.key]);for(;r&&!s.has(r);){s.add(r);let o=e.exposes.get(r);if(!o)break;if(o.entity?.key&&(t?t.findEntity(o.entity.key,o.entity.domain):i.findEntity(o.entity.key,o.entity.domain))?.hasSemantic(g.Project))return!0;r=o.parent?.key}return!1}function gn(c,e,t){if(!c)return!1;let i=t?.domain??e.domain;return i?c.entity?.key&&(t?t.findEntity(c.entity.key,c.entity.domain):i.findEntity(c.entity.key,c.entity.domain))?.hasSemantic(g.Project)?!0:Rs(c,e,t):!1}function yn(c,e){let t=Array.from(c.withInheritedAssociations()).filter(i=>i.hasSemantic(g.ProjectMembers));if(e){let i=Array.from(e.withInheritedAssociations()).filter(o=>o.hasSemantic(g.ProjectMembers)),r=t.find(o=>o.targets.some(a=>a.key===e.key)&&!o.getSemantic(g.ProjectMembers)?.link)??t.find(o=>o.targets.some(a=>a.key===e.key));if(r)return r;let s=i.find(o=>o.targets.some(a=>a.key===c.key)&&!o.getSemantic(g.ProjectMembers)?.link)??i.find(o=>o.targets.some(a=>a.key===c.key));return s||void 0}if(t.length>0)return t.find(r=>!r.getSemantic(g.ProjectMembers)?.link)||t[0]}function bn(c,e,t){if(!c||!c.parent)return!1;let i=t?.domain??e.domain;if(!i)return!1;let r=c.parent.key,s=new Set([c.key]);for(;r&&!s.has(r);){s.add(r);let o=e.exposes.get(r);if(!o)break;if(o.entity?.key&&(t?t.findEntity(o.entity.key,o.entity.domain):i.findEntity(o.entity.key,o.entity.domain))?.hasSemantic(g.Organization))return!0;r=o.parent?.key}return!1}function rp(c,e,t){if(!c)return!1;let i=t?.domain??e.domain;return i?c.entity?.key&&(t?t.findEntity(c.entity.key,c.entity.domain):i.findEntity(c.entity.key,c.entity.domain))?.hasSemantic(g.Organization)?!0:bn(c,e,t):!1}function sp(c,e){let t=Array.from(c.withInheritedAssociations()).filter(i=>i.hasSemantic(g.OrganizationMembers));if(e){let i=Array.from(e.withInheritedAssociations()).filter(o=>o.hasSemantic(g.OrganizationMembers)),r=t.find(o=>o.targets.some(a=>a.key===e.key)&&!o.getSemantic(g.OrganizationMembers)?.link)??t.find(o=>o.targets.some(a=>a.key===e.key));if(r)return r;let s=i.find(o=>o.targets.some(a=>a.key===c.key)&&!o.getSemantic(g.OrganizationMembers)?.link)??i.find(o=>o.targets.some(a=>a.key===c.key));return s||void 0}if(t.length>0)return t.find(r=>!r.getSemantic(g.OrganizationMembers)?.link)||t[0]}var kn=class{ruleType="matchOrganizationRole";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},n=s.domain,l=n&&i?.entity?.key?s.findEntity(i.entity.key,i.entity.domain):void 0,d=l?l.info.getLabel():i?i.key:"ApiModel";if(e.roles&&e.roles.some(p=>typeof p!="string"||!p.trim())&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_INVALID_ROLES"),message:`[${d}]: The "matchOrganizationRole" access rule roles list contains invalid or empty role strings.`,suggestion:"Ensure all roles in the roles array are non-empty strings.",severity:"error",context:a}),t==="action"&&o?.kind==="create"&&!bn(i,r,s)&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_INVALID_ACTION_KIND"),message:`[${d}]: The "matchOrganizationRole" access rule cannot be used on a create action because the organization record does not exist yet.`,suggestion:"Remove matchOrganizationRole from create actions, or use allowAuthenticated instead.",severity:"error",context:a}),i&&!rp(i,r,s)&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_MISSING_ORGANIZATION_PATH"),message:`[${d}]: The "matchOrganizationRole" access rule requires the endpoint to be an Organization resource or nested under an Organization in the route hierarchy.`,suggestion:"Apply this rule only to Organization exposures or sub-resources nested under an Organization.",severity:"error",context:a}),n){let p=s.getUserEntity();p||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match organization role access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:a});let m=s.getOrganizationEntity();if(!m)s.addIssue({code:v("RULE","MISSING_ORGANIZATION_MODEL"),message:'The API specifies a "Match organization role access" rule, but no Organization entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the Organization semantic.",severity:"error",context:a});else{m.primaryKey()||s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_MISSING_PRIMARY_KEY"),message:`[${d}]: Organization entity "${m.info.getLabel()}" has no primary key defined. matchOrganizationRole requires the Organization entity to have a primary key.`,suggestion:"Add a primary key property to the Organization entity.",severity:"error",context:a});let f=sp(m,p),k;if(f?(f.multiple!==!0&&s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_MEMBERS_NOT_MULTIPLE"),message:`[${d}]: The OrganizationMembers association must have "multiple: true" to support many-to-many organization memberships.`,suggestion:"Set the association cardinality to multiple (array) on the OrganizationMembers association.",severity:"error",context:a}),k=Array.from(f.listProperties()).find(w=>w.hasSemantic(g.OrganizationRole)||w.hasSemantic(g.AssociationRole))):s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_NO_MEMBERS_ASSOC"),message:`[${d}]: The "matchOrganizationRole" access rule requires the Organization entity to have a many-to-many association with the OrganizationMembers semantic.`,suggestion:"Configure an OrganizationMembers association between the Organization entity and the User entity.",severity:"error",context:a}),k||(k=Array.from(m.withInheritedProperties()).find(w=>w.hasSemantic(g.OrganizationRole))||(p?Array.from(p.withInheritedProperties()).find(w=>w.hasSemantic(g.OrganizationRole)):void 0)),e.roles&&e.roles.length>0)if(!k)s.addIssue({code:v("ACTION_RULE","ORGANIZATION_ROLE_NO_ROLE_PROPERTY"),message:`[${d}]: The "matchOrganizationRole" access rule specifies roles, but no property with the OrganizationRole semantic was found on the OrganizationMembers association.`,suggestion:"Add a property with the OrganizationRole semantic to the OrganizationMembers association.",severity:"error",context:a});else{let w=k.schema?.enum;if(w&&Array.isArray(w))for(let S of e.roles)w.includes(S)||s.addIssue({code:v("RULE","INVALID_ORGANIZATION_ROLE"),message:`Organization role "${S}" is not defined in the Organization role enum list.`,suggestion:`Select a valid role from: [${w.join(", ")}].`,severity:"warning",context:a})}if(l&&l.key!==m.key)if(l.hasSemantic(g.User))f||s.addIssue({code:v("RULE","ORGANIZATION_NOT_LINKED"),message:`[${l.info.getLabel()}]: The access rule is set to "Match organization role access", but the resource is not linked to the Organization entity.`,suggestion:"Establish an association between the Organization entity and this resource entity.",severity:"error",context:a});else{let w=Array.from(m.withInheritedAssociations()).filter(A=>A.targets.some(_=>_.key===l.key)),S=Array.from(l.withInheritedAssociations()).filter(A=>A.targets.some(_=>_.key===m.key));if(!(w.find(A=>A.hasSemantic(g.OrganizationResource))||S.find(A=>A.hasSemantic(g.OrganizationResource)))){let A=w[0]||S[0];if(A){let _=A.info.displayName||(A.info.name&&A.info.name!=="new_association"?A.info.name:A.key);s.addIssue({code:v("RULE","MISSING_ORGANIZATION_RESOURCE_SEMANTIC"),message:`[${l.info.getLabel()}]: Association "${_}" links Organization to "${l.info.getLabel()}", but is missing the OrganizationResource semantic annotation.`,suggestion:"Add the OrganizationResource semantic to the association so the runtime can resolve inherited organization access.",severity:"error",context:a})}else bn(i,r,s)||s.addIssue({code:v("RULE","ORGANIZATION_NOT_LINKED"),message:`[${l.info.getLabel()}]: The access rule is set to "Match organization role access", but the resource is not linked to the Organization entity.`,suggestion:"Establish an association between the Organization entity and this resource entity.",severity:"error",context:a})}}}}}};var vn=class{ruleType="matchProjectRole";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},n=s.domain,l=n&&i?.entity?.key?s.findEntity(i.entity.key,i.entity.domain):void 0,d=l?l.info.getLabel():i?i.key:"ApiModel";if((!e.roles||e.roles.length===0||e.roles.some(p=>typeof p!="string"||!p.trim()))&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MISSING_ROLES"),message:`[${d}]: The "matchProjectRole" access rule requires at least one role to be specified in "roles".`,suggestion:"Specify one or more allowed roles, or use matchProjectStakeholder for role-agnostic membership.",severity:"error",context:a}),t==="action"&&o?.kind==="create"&&!Rs(i,r,s)&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_INVALID_ACTION_KIND"),message:`[${d}]: The "matchProjectRole" access rule cannot be used on a create action because the project record does not exist yet.`,suggestion:"Remove matchProjectRole from create actions, or use allowAuthenticated instead.",severity:"error",context:a}),i&&!gn(i,r,s)&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MISSING_PROJECT_PATH"),message:`[${d}]: The "matchProjectRole" access rule requires the endpoint to be a Project resource or nested under a Project in the route hierarchy.`,suggestion:"Apply this rule only to Project exposures or sub-resources nested under a Project.",severity:"error",context:a}),n){let p=s.getUserEntity();p||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match project role access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:a});let m=s.getProjectEntity();if(!m)s.addIssue({code:v("RULE","MISSING_PROJECT_MODEL"),message:'The API specifies a "Match project role access" rule, but no Project entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the Project semantic.",severity:"error",context:a});else{m.primaryKey()||s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MISSING_PRIMARY_KEY"),message:`[${d}]: Project entity "${m.info.getLabel()}" has no primary key defined. matchProjectRole requires the Project entity to have a primary key.`,suggestion:"Add a primary key property to the Project entity.",severity:"error",context:a});let f=yn(m,p);if(!f)s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_NO_MEMBERS_ASSOC"),message:`[${d}]: The "matchProjectRole" access rule requires the Project entity to have a many-to-many association with the ProjectMembers semantic.`,suggestion:"Configure a ProjectMembers association between the Project entity and the User entity.",severity:"error",context:a});else{f.multiple!==!0&&s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_MEMBERS_NOT_MULTIPLE"),message:`[${d}]: The ProjectMembers association must have "multiple: true" to support many-to-many project memberships.`,suggestion:"Set the association cardinality to multiple (array) on the ProjectMembers association.",severity:"error",context:a});let k=Array.from(f.listProperties()).find(w=>w.hasSemantic(g.ProjectRole));if(!k)s.addIssue({code:v("ACTION_RULE","PROJECT_ROLE_NO_ROLE_PROPERTY"),message:`[${d}]: The "matchProjectRole" access rule requires the ProjectMembers association to have a property with the ProjectRole semantic.`,suggestion:"Add a property with the ProjectRole semantic to the ProjectMembers association.",severity:"error",context:a});else if(e.roles&&e.roles.length>0){let w=k.schema?.enum;if(w&&Array.isArray(w))for(let S of e.roles)w.includes(S)||s.addIssue({code:v("RULE","INVALID_PROJECT_ROLE"),message:`Project role "${S}" is not defined in the Project role enum list.`,suggestion:`Select a valid role from: [${w.join(", ")}].`,severity:"warning",context:a})}}}}}};var wn=class{ruleType="matchProjectStakeholder";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}},n=s.domain,l=n&&i?.entity?.key?s.findEntity(i.entity.key,i.entity.domain):void 0,d=l?l.info.getLabel():i?i.key:"ApiModel";if(t==="action"&&o?.kind==="create"&&!Rs(i,r,s)&&s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_INVALID_ACTION_KIND"),message:`[${d}]: The "matchProjectStakeholder" access rule cannot be used on a create action because the project record does not exist yet.`,suggestion:"Remove matchProjectStakeholder from create actions, or use allowAuthenticated instead.",severity:"error",context:a}),i&&!gn(i,r,s)&&s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_MISSING_PROJECT_PATH"),message:`[${d}]: The "matchProjectStakeholder" access rule requires the endpoint to be a Project resource or nested under a Project in the route hierarchy.`,suggestion:"Apply this rule only to Project exposures or sub-resources nested under a Project.",severity:"error",context:a}),n){let p=s.getUserEntity();p||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match project stakeholder access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:a});let m=s.getProjectEntity();if(!m)s.addIssue({code:v("RULE","MISSING_PROJECT_MODEL"),message:'The API specifies a "Match project stakeholder access" rule, but no Project entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the Project semantic.",severity:"error",context:a});else{m.primaryKey()||s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_MISSING_PRIMARY_KEY"),message:`[${d}]: Project entity "${m.info.getLabel()}" has no primary key defined. matchProjectStakeholder requires the Project entity to have a primary key.`,suggestion:"Add a primary key property to the Project entity.",severity:"error",context:a});let f=yn(m,p);f?f.multiple!==!0&&s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_MEMBERS_NOT_MULTIPLE"),message:`[${d}]: The ProjectMembers association must have "multiple: true" to support many-to-many project memberships.`,suggestion:"Set the association cardinality to multiple (array) on the ProjectMembers association.",severity:"error",context:a}):s.addIssue({code:v("ACTION_RULE","STAKEHOLDER_NO_MEMBERS_ASSOC"),message:`[${d}]: The "matchProjectStakeholder" access rule requires the Project entity to have a many-to-many association with the ProjectMembers semantic.`,suggestion:"Configure a ProjectMembers association between the Project entity and the User entity.",severity:"error",context:a})}}}};var Sn=class{ruleType="matchEmailDomain";validate(e,t,i,r,s){let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(s.domain){let n=s.getUserEntity();if(!n)s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match email domain" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o});else{let l=Array.from(n.withInheritedProperties()).filter(d=>d.hasSemantic(g.Email));if(l.length===0)s.addIssue({code:v("RULE","MISSING_EMAIL_SEMANTIC"),message:`The access rule is set to "Match email domain", but the User entity "${n.info.getLabel()}" has no property with the Email data semantic.`,suggestion:'Go to the Data Modeler and add the "Email" semantic to the email property on the User entity.',severity:"error",context:o});else if(l.length>1){let d=l.map(p=>`"${p.info.name||p.key}"`).join(", ");s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_MULTIPLE_PROPERTIES"),message:`[${n.info.getLabel()}]: The User entity has multiple properties with the Email semantic (${d}). The "Match email domain" access rule requires exactly one Email property on the User entity to avoid ambiguous resolution.`,suggestion:`Ensure only one property on "${n.info.getLabel()}" carries the Email semantic.`,severity:"error",context:o})}else{let d=l[0];s.hasSessionConfigured()&&!s.isSessionPropertyConfigured(d.key)&&s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_NOT_IN_SESSION"),message:`The email property "${d.info.getLabel()}" required by the "Match email domain" rule is not included in the session configuration properties.`,suggestion:"Add the email property to the session properties in the API Model session configuration.",severity:"error",context:o}),e.requireVerified!==!1&&((d.getSemantic(g.Email)?.config?.requireVerification??va.requireVerification??!0)||s.addIssue({code:v("RULE","EMAIL_VERIFICATION_MISMATCH"),message:`The "Match email domain" access rule requires verified email addresses (requireVerified: true), but the Email data semantic on property "${d.info.getLabel()}" has email verification disabled (requireVerification: false).`,suggestion:"Enable email verification in the Email semantic configuration on the User entity, or set requireVerified to false on the access rule.",severity:"error",context:o}))}}}if(!e.domains||e.domains.length===0)s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_EMPTY_DOMAINS"),message:'The "Match email domain" access rule has no allowed email domains specified.',suggestion:'Specify at least one domain name (e.g., "example.com") in the rule configuration.',severity:"error",context:o});else for(let n of e.domains){if(!n||typeof n!="string"||n.trim()===""){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:'The "Match email domain" access rule contains an empty domain pattern.',suggestion:'Remove the empty domain entry or specify a valid domain (e.g., "example.com").',severity:"error",context:o});continue}let l=n.trim();if(l.startsWith("@")){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Domain pattern "${n}" cannot start with "@". Specify the domain name directly (e.g., "${l.slice(1)}").`,suggestion:`Change "${n}" to "${l.slice(1)}".`,severity:"error",context:o});continue}if(l.startsWith("http://")||l.startsWith("https://")){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Domain pattern "${n}" cannot include a URL protocol. Specify only the domain name.`,suggestion:`Remove the protocol prefix from "${n}".`,severity:"error",context:o});continue}if(/\s/.test(l)){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Domain pattern "${n}" contains invalid whitespace characters.`,suggestion:"Remove spaces from the domain pattern.",severity:"error",context:o});continue}if(l.includes("*")&&(!l.startsWith("*.")||l==="*."||l.slice(2).includes("*"))){s.addIssue({code:v("RULE","MATCH_EMAIL_DOMAIN_INVALID_PATTERN"),message:`Wildcard domain pattern "${n}" is invalid. Wildcards must strictly follow the prefix format "*.example.com".`,suggestion:'Use the wildcard format "*.example.com" or specify the exact domain name.',severity:"error",context:o});continue}}}};var An=class{ruleType="relationalResourceOwner";validate(e,t,i,r,s,o){if(!i)return;let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!s.domain)return;let l=i.entity.key,d=s.findEntity(l,i.entity.domain),p=d?d.info.getLabel():i.key;if(i.isRoot||!i.parent){s.addIssue({code:v("RULE","RELATIONAL_OWNER_NO_PARENT"),message:`[${p}]: relationalResourceOwner cannot be used on a root endpoint. Either nest this entity under a parent with User or ResourceOwnerIdentifier, or use matchResourceOwner if this entity has a direct owner FK.`,suggestion:"Nest this entity under a parent with User or ResourceOwnerIdentifier, or use matchResourceOwner if this entity has a direct owner FK.",severity:"error",context:a});return}let m=i.parent.key,h=new Set([i.key]),f,k;for(;m&&!h.has(m);){h.add(m);let S=r.exposes.get(m);if(!S)break;let E=s.findEntity(S.entity.key,S.entity.domain);if(E){let A=E.hasSemantic(g.User),_;if(!A){for(let $ of E.withInheritedAssociations())if($.hasSemantic(g.ResourceOwnerIdentifier)){_=$;break}}if(A||_)if(!!!(S.resourcePath?.includes("{")||S.parent?.selfRoute))k||(k={parentExposure:S,parentEntity:E});else{A?f={kind:"user",parentExposure:S,parentEntity:E}:_&&(f={kind:"assoc",parentExposure:S,parentEntity:E,assoc:_});break}}m=S.parent?.key}if(!f){if(k){s.addIssue({code:v("RULE","RELATIONAL_OWNER_PARENT_MISSING_PARAMETER"),message:`[${p}]: Ancestor entity "${k.parentEntity.info.getLabel()}" carries User ownership semantics, but its exposed route "${k.parentExposure.resourcePath}" has no route path parameter (e.g. "{id}"). The relationalResourceOwner rule requires a parent URL parameter.`,suggestion:`Add a path parameter to "${k.parentExposure.resourcePath}" (e.g. "/{id}"), or configure it as a selfRoute.`,severity:"error",context:a});return}s.addIssue({code:v("RULE","RELATIONAL_OWNER_NO_QUALIFYING_PARENT"),message:`[${p}]: relationalResourceOwner found no qualifying parent entity in the exposure hierarchy. A parent entity must have User semantic or a ResourceOwnerIdentifier association.`,suggestion:"Ensure at least one ancestor entity in the exposure hierarchy has the User semantic or an association with the ResourceOwnerIdentifier semantic.",severity:"error",context:a});return}if(f.parentEntity.primaryKey()||s.addIssue({code:v("RULE","RELATIONAL_OWNER_PARENT_MISSING_PRIMARY_KEY"),message:`[${p}]: Qualifying parent entity "${f.parentEntity.info.getLabel()}" has no primary key. relationalResourceOwner requires the qualifying parent entity to have a primary key property.`,suggestion:`Add a primary key property to "${f.parentEntity.info.getLabel()}".`,severity:"error",context:a}),f.kind==="assoc"){let S=f.assoc,E=S.info.displayName||S.info.name||S.key;Array.from(S.listTargets()).some($=>$.hasSemantic(g.User))||s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NO_USER_TARGET"),message:`[${p}]: Ownership association "${E}" on qualifying parent "${f.parentEntity.info.getLabel()}" has no User-semantic target. ResourceOwnerIdentifier must point to the User entity.`,suggestion:"Ensure the target entity of the association carries the User semantic.",severity:"error",context:a}),(S.multiple||S.isManyToMany())&&s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NOT_SINGLE"),message:`[${p}]: Ownership association "${E}" on qualifying parent "${f.parentEntity.info.getLabel()}" cannot have multiple targets or be many-to-many. The association must be a direct single reference to the User entity.`,suggestion:"Configure the association to be a single direct reference to the User entity (multiple: false).",severity:"error",context:a})}if(f.kind==="user"&&d&&(t==="action"&&o&&(o.kind==="list"||o.kind==="search")||t==="exposure"&&(i.actions?.some(E=>E.kind==="list"||E.kind==="search")??!1))){let E;for(let A of d.withInheritedAssociations())if(A.hasSemantic(g.ResourceOwnerIdentifier)){E=A;break}if(E)Array.from(E.listTargets()).some($=>$.hasSemantic(g.User))||s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NO_USER_TARGET"),message:`[${p}]: Child ownership association "${E.info.getLabel()}" has no User-semantic target. ResourceOwnerIdentifier must point to the User entity.`,suggestion:"Ensure the target entity of the association carries the User semantic.",severity:"error",context:a}),(E.multiple||E.isManyToMany())&&s.addIssue({code:v("RULE","RELATIONAL_OWNER_ASSOCIATION_NOT_SINGLE"),message:`[${p}]: Child ownership association "${E.info.getLabel()}" cannot have multiple targets or be many-to-many. The association must be a direct single reference to the User entity.`,suggestion:"Configure the association to be a single direct reference to the User entity (multiple: false).",severity:"error",context:a});else{let A=t==="action"&&o?`action "${o.kind}"`:"collection operations";s.addIssue({code:v("RULE","RELATIONAL_OWNER_USER_PARENT_MISSING_CHILD_OWNER_ASSOC"),message:`[${p}]: relationalResourceOwner on ${A} under a User parent segment requires "${p}" to have an association annotated with SemanticType.ResourceOwnerIdentifier pointing to the User entity.`,suggestion:`Add an association annotated with ResourceOwnerIdentifier pointing to the User entity on "${p}", or use matchResourceOwner.`,severity:"error",context:a})}}}};var En=class{ruleType="matchResourceOwner";validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(!s.domain||!i?.entity?.key)return;let l=i.entity.key,d=s.findEntity(l,i.entity.domain);if(!d)return;let p=d.info.getLabel();if(e.target!=="user-entity"&&e.target!=="association"){s.addIssue({code:v("RULE","INVALID_TARGET"),message:`[${p}]: Invalid matchResourceOwner target "${e.target??"(missing)"}". Target must be either "user-entity" or "association".`,suggestion:'Set target to "association" (default) or "user-entity".',severity:"error",context:{...a,property:"target"}});return}d.primaryKey()||s.addIssue({code:v("RULE","RESOURCE_OWNER_MISSING_PRIMARY_KEY"),message:`[${p}]: Entity "${p}" has no primary key defined. The "matchResourceOwner" rule requires the entity to have a primary key.`,suggestion:`Add a primary key property to entity "${p}".`,severity:"error",context:a}),t==="action"&&o?.kind==="create"&&s.addIssue({code:v("RULE","INVALID_ACTION_FOR_OWNERSHIP"),message:`[${p}]: The "matchResourceOwner" access rule cannot be evaluated on a "create" action because the resource does not exist yet at the time of authorization.`,suggestion:"Use relationalResourceOwner to secure create actions via a parent entity, or restrict this rule to read, update, and delete actions only.",severity:"error",context:a});let h=["read","update","delete","link","unlink"],f=t==="action"&&o&&h.includes(o.kind),k=t==="exposure"&&i.actions?.some(w=>h.includes(w.kind));if((f||k)&&!i.resourcePath?.includes("{")&&!i.parent?.selfRoute){let w=f?`action "${o?.kind}"`:"single-resource operations";s.addIssue({code:v("RULE","MISSING_PATH_PARAMETER_FOR_OWNERSHIP"),message:`[${p}]: The "matchResourceOwner" rule on ${w} requires a route path parameter (e.g. "{id}"), but the resource path "${i.resourcePath}" has none.`,suggestion:"Add a path parameter to the resource path, or configure the exposure as a selfRoute if it represents the current user.",severity:"error",context:a})}if(e.target==="user-entity")d.hasSemantic(g.User)||s.addIssue({code:v("RULE","INVALID_USER_ENTITY_TARGET"),message:`[${p}]: Target is set to "user-entity", but the entity itself does not represent the User.`,suggestion:'Change target to "association" or add User semantic to this entity.',severity:"error",context:{...a,property:"target"}});else{if(!e.association||!e.association.key){s.addIssue({code:v("RULE","MISSING_OWNERSHIP_ASSOCIATION"),message:`[${p}]: The access rule is set to "Match resource owner", but no ownership association is specified.`,suggestion:"Select an association on this entity that links to the User entity, or use relationalResourceOwner for inherited parent ownership.",severity:"error",context:{...a,property:"association"}});return}let w=e.association.key,S=e.association.domain,E=s.findAssociation(w,S),A=Array.from(d.withInheritedAssociations()),_=E?A.find(L=>L.key===E.key):A.find(L=>L.key===w);if(!_){s.addIssue({code:v("RULE","INVALID_OWNERSHIP_ASSOCIATION"),message:`[${p}]: The ownership association "${w}" does not exist on this entity.`,suggestion:"Select an association on this entity that links to the User entity, or use relationalResourceOwner for inherited parent ownership.",severity:"error",context:{...a,property:"association"}});return}let $=_.info.displayName||_.info.name||_.key;(_.multiple||_.isManyToMany())&&s.addIssue({code:v("RULE","OWNERSHIP_ASSOCIATION_NOT_SINGLE"),message:`[${p}]: Ownership association "${$}" cannot have multiple targets or be many-to-many. The association must be a direct single reference (N:1 or 1:1) to the User entity.`,suggestion:"Configure the association to be a single direct reference to the User entity (multiple: false).",severity:"error",context:{...a,property:"association"}});let j=Array.from(_.listTargets()).find(L=>L.hasSemantic(g.User));j?j.primaryKey()||s.addIssue({code:v("RULE","RESOURCE_OWNER_USER_MISSING_PRIMARY_KEY"),message:`[${p}]: User entity "${j.info.getLabel()}" referenced by ownership association "${$}" has no primary key.`,suggestion:`Add a primary key property to the User entity "${j.info.getLabel()}".`,severity:"error",context:{...a,property:"association"}}):s.addIssue({code:v("RULE","OWNERSHIP_ASSOCIATION_NO_USER_TARGET"),message:`[${p}]: Ownership association "${$}" has no User-semantic target. ResourceOwnerIdentifier must point to the User entity.`,suggestion:"Ensure the target entity of the association carries the User semantic.",severity:"error",context:{...a,property:"association"}})}}};var _n=class{ruleType="matchResourceAttribute";validate(e,t,i,r,s){if(!i?.entity?.key)return;let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!s.domain)return;let n=s.findEntity(i.entity.key,i.entity.domain);if(!n)return;let l=n.info.getLabel();if(e.attribute&&e.attribute.trim()){let h=Array.from(n.withInheritedProperties()).find(f=>f.key===e.attribute);h?h.multiple===!0&&s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_ARRAY_PROPERTY_UNSUPPORTED"),message:`[${l}]: Property "${h.info.getLabel()}" is multi-valued (array), which is not supported by matchResourceAttribute.`,suggestion:"Use a scalar property on the entity, or evaluate associations via matchAssociation.",severity:"error",context:o}):s.addIssue({code:v("RULE","INVALID_RESOURCE_ATTRIBUTE"),message:`[${l}]: The resource attribute property "${e.attribute}" does not exist.`,suggestion:"Select a valid property on the entity.",severity:"error",context:o})}else s.addIssue({code:v("RULE","MISSING_RESOURCE_ATTRIBUTE"),message:`[${l}]: The access rule is set to "Match resource attribute", but no attribute is specified.`,suggestion:"Specify a property on the entity to match against.",severity:"error",context:o});let d=zi.isArrayOperator(e.operator),p=zi.isScalarOperator(e.operator);e.operator?!d&&!p?s.addIssue({code:v("RULE","INVALID_RESOURCE_ATTRIBUTE_OPERATOR"),message:`[${l}]: The operator "${e.operator}" is not a valid resource attribute operator.`,suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o}):d?Array.isArray(e.values)?e.values.length===0&&s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_EMPTY_ARRAY"),message:`[${l}]: The "${e.operator}" operator requires at least one value in the array.`,suggestion:"Specify at least one value to match against in the array.",severity:"error",context:o}):s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_ARRAY_REQUIRED"),message:`[${l}]: The "${e.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:o}):e.value===void 0||e.value===null?s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_VALUE_REQUIRED"),message:`[${l}]: The "${e.operator}" operator requires a scalar value in "value".`,suggestion:'Provide a scalar value (string, number, or boolean) in the "value" property to match against.',severity:"error",context:o}):(Array.isArray(e.value)||typeof e.value=="object"&&e.value!==null)&&s.addIssue({code:v("RULE","MATCH_RESOURCE_ATTRIBUTE_SCALAR_REQUIRED"),message:`[${l}]: The "${e.operator}" operator does not accept array or object values.`,suggestion:'Provide a single scalar value (string, number, or boolean) in the "value" property, or switch to the "in" or "notIn" operator.',severity:"error",context:o}):s.addIssue({code:v("RULE","INVALID_RESOURCE_ATTRIBUTE_OPERATOR"),message:`[${l}]: The access rule is missing a comparison operator.`,suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o})}};var xn=class{ruleType="matchUserProperty";validate(e,t,i,r,s){let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(s.domain){let d=s.getUserEntity();if(!d)s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match user property" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o});else if(!e.property||e.property.trim()==="")s.addIssue({code:v("RULE","MISSING_USER_PROPERTY"),message:'The access rule is set to "Match user property", but no property is specified.',suggestion:"Specify a property on the User entity to match against.",severity:"error",context:o});else{let m=Array.from(d.withInheritedProperties()).find(h=>h.key===e.property);if(!m)s.addIssue({code:v("RULE","INVALID_USER_PROPERTY"),message:`The user property "${e.property}" does not exist on the User entity "${d.info.getLabel()}".`,suggestion:"Select a valid property on the User entity.",severity:"error",context:o});else if(m.multiple&&s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_MULTI_VALUED"),message:`The user property "${m.info.getLabel()}" is multi-valued (an array). The "matchUserProperty" rule only supports single-valued properties.`,suggestion:"Select a scalar user property, or use matchUserRole for multi-valued role properties.",severity:"error",context:o}),s.hasSessionConfigured()&&!s.isSessionPropertyConfigured(e.property)){let h=m.info.getLabel()??e.property;s.addIssue({code:v("RULE","USER_PROPERTY_NOT_IN_SESSION"),message:`The user property "${h}" used in the "Match user property" rule is not included in the session configuration properties.`,suggestion:"Add the property to the session properties in the API Model session configuration.",severity:"error",context:o})}}}let n=Vi.isArrayOperator(e.operator),l=Vi.isScalarOperator(e.operator);e.operator?!n&&!l?s.addIssue({code:v("RULE","INVALID_USER_PROPERTY_OPERATOR"),message:`The operator "${e.operator}" is not a valid user property operator.`,suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o}):n?Array.isArray(e.values)?e.values.length===0&&s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_EMPTY_ARRAY"),message:`The "${e.operator}" operator requires at least one value in the array.`,suggestion:"Specify at least one value to match against in the array.",severity:"error",context:o}):s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_ARRAY_REQUIRED"),message:`The "${e.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:o}):e.value===void 0||e.value===null?s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_VALUE_REQUIRED"),message:`The "${e.operator}" operator requires a scalar value in "value".`,suggestion:'Provide a scalar value (string, number, or boolean) in the "value" property to match against.',severity:"error",context:o}):(Array.isArray(e.value)||typeof e.value=="object"&&e.value!==null)&&s.addIssue({code:v("RULE","MATCH_USER_PROPERTY_SCALAR_REQUIRED"),message:`The "${e.operator}" operator does not accept array or object values.`,suggestion:'Provide a single scalar value (string, number, or boolean) in the "value" property, or switch to the "in" or "notIn" operator.',severity:"error",context:o}):s.addIssue({code:v("RULE","INVALID_USER_PROPERTY_OPERATOR"),message:"The access rule is missing a comparison operator.",suggestion:"Select a valid operator: equal, notEqual, in, notIn, startsWith, endsWith, contains, greaterThan, lessThan, greaterThanOrEqual, or lessThanOrEqual.",severity:"error",context:o})}};var In=class{ruleType="matchAssociation";validate(e,t,i,r,s){if(!i)return;let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(s.domain)if(s.getUserEntity()||s.addIssue({code:v("RULE","MISSING_USER_MODEL"),message:'The API specifies a "Match association access" rule, but no User entity is configured in the domain.',suggestion:"Annotate an entity in the domain with the User semantic.",severity:"error",context:o}),!e.association||!e.association.key)s.addIssue({code:v("RULE","MISSING_ASSOCIATION_TARGET"),message:'The access rule is set to "Match association access", but no association target is specified.',suggestion:"Specify the target association in the rule configuration.",severity:"error",context:o});else{let l=e.association.key,d=e.association.domain,p=s.findAssociation(l,d),m=i.entity.key,h=s.findEntity(m,i.entity.domain),f=h?Array.from(h.withInheritedAssociations()).find(k=>k.key===l):void 0;if(!p&&!f){let k=h?h.info.getLabel():m;s.addIssue({code:v("RULE","INVALID_ASSOCIATION_TARGET"),message:`[${k}]: The target association "${l}" does not exist in the domain.`,suggestion:"Select a valid association configured in the data domain.",severity:"error",context:o})}}}};var op=["list","create","search","link","restore"],Pn=class{ruleType="matchPathParameter";validate(e,t,i,r,s,o){if(!i)return;let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!e.parameters||!Array.isArray(e.parameters)||e.parameters.length===0){s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_EMPTY_PARAMETERS"),message:'The access rule is set to "Match path parameter", but no parameter mappings are specified.',suggestion:"Specify at least one mapping between a URL path parameter and a session property.",severity:"error",context:a});return}let n;if(t==="action"&&o)if(op.includes(o.kind)){let h=i.getAbsoluteCollectionPath()??"";n=new Set([...h.matchAll(/\{([^}]+)\}/g)].map(f=>f[1]))}else{let h=i.getAbsoluteResourcePath();n=new Set([...h.matchAll(/\{([^}]+)\}/g)].map(f=>f[1]))}else n=new Set(i.getPathParameters({absolute:!0}));let l=s.getUserEntity(),d=new Map;if(l)for(let h of l.withInheritedProperties())d.set(h.key,h);let p=i.entity?s.findEntity(i.entity.key,i.entity.domain)?.info.getLabel()??i.entity.key:i.key,m=new Map;for(let h of e.parameters){if(!h.pathParameter||h.pathParameter.trim()==="")s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_MISSING_PATH_PARAM"),message:'The "Match path parameter" rule has a mapping with no path parameter specified.',suggestion:"Specify a valid URL path parameter name.",severity:"error",context:a});else if(h.pathParameter.includes("{")||h.pathParameter.includes("}")){let f=h.pathParameter.replace(/[{}]/g,"").trim();s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_SYNTAX_ERROR"),message:`Path parameter "${h.pathParameter}" must not contain curly braces.`,suggestion:`Change "${h.pathParameter}" to "${f}".`,severity:"error",context:a})}else if(/\s/.test(h.pathParameter))s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_WHITESPACE"),message:`Path parameter "${h.pathParameter}" contains invalid whitespace.`,suggestion:`Remove whitespace from path parameter name "${h.pathParameter.trim()}".`,severity:"error",context:a});else if(!n.has(h.pathParameter)){let f=n.size>0?`[${Array.from(n).join(", ")}]`:"none";s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_MISSING_ROUTE_PARAM"),message:`[${p}]: Path parameter "${h.pathParameter}" declared in "Match path parameter" rule was not found in the route hierarchy.`,suggestion:`Ensure the route path includes "{${h.pathParameter}}" or select from available parameters: ${f}.`,severity:"error",context:a})}if(h.pathParameter&&h.pathParameter.trim()){let f=h.pathParameter.replace(/[{}]/g,"").trim();if(m.has(f)){let k=m.get(f);k===h.sessionProperty?s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_DUPLICATE_PARAMETER"),message:`Path parameter "${f}" is mapped more than once to session property "${h.sessionProperty}".`,suggestion:`Remove the duplicate mapping for "${f}".`,severity:"error",context:a}):s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_CONFLICTING_PARAMETER"),message:`Path parameter "${f}" is mapped to multiple conflicting session properties ("${k}" and "${h.sessionProperty}").`,suggestion:"Ensure each path parameter is mapped to exactly one session property in the rule.",severity:"error",context:a})}else m.set(f,h.sessionProperty)}if(!h.sessionProperty||h.sessionProperty.trim()==="")s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_MISSING_SESSION_PROP"),message:'The "Match path parameter" rule has a mapping with no session property specified.',suggestion:"Specify a session property to match against.",severity:"error",context:a});else if(/\s/.test(h.sessionProperty))s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_WHITESPACE"),message:`Session property "${h.sessionProperty}" contains invalid whitespace.`,suggestion:`Remove whitespace from session property name "${h.sessionProperty.trim()}".`,severity:"error",context:a});else{if(s.hasSessionConfigured()){if(!s.isSessionPropertyConfigured(h.sessionProperty))if(d.has(h.sessionProperty))s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_NOT_IN_SESSION"),message:`Session property "${h.sessionProperty}" is defined on the User entity but is not included in the session configuration properties.`,suggestion:`Add "${h.sessionProperty}" to the session properties in the API Model session configuration.`,severity:"error",context:a});else{let k=s.getConfiguredSessionPropertyKeys(),w=k&&k.size>0?Array.from(k).join(", "):Array.from(d.keys()).join(", ");s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${h.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:`Select a valid session property from: [${w}].`,severity:"error",context:a})}}else if(d.size>0){if(!d.has(h.sessionProperty)){let k=Array.from(d.keys()).join(", ");s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${h.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:`Select a valid session property from: [${k}].`,severity:"error",context:a})}}else s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${h.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:"Configure session properties in the API Model and ensure a User entity is defined.",severity:"error",context:a});let f=d.get(h.sessionProperty);if(f&&(f.multiple===!0||f.type==="json"||f.type==="binary")){let k=f.multiple?"array":f.type;s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_NON_SCALAR_SESSION_PROP"),message:`[${p}]: Session property "${f.info.getLabel()}" has a non-scalar type (${k}). The "Match path parameter" rule only supports matching scalar string, number, or boolean properties.`,suggestion:"Select a scalar session property, or use an appropriate authorization rule for role/membership arrays.",severity:"error",context:a})}}}if(t==="exposure"&&i.actions&&i.actions.length>0){let h=i.getAbsoluteCollectionPath()??"",f=new Set([...h.matchAll(/\{([^}]+)\}/g)].map(w=>w[1])),k=i.actions.filter(w=>op.includes(w.kind)&&!w.overrideParentScenarios);if(k.length>0)for(let w of e.parameters){let S=w.pathParameter?.replace(/[{}]/g,"").trim();if(S&&!f.has(S)&&n.has(S)){let E=k.map(A=>`"${A.kind}"`).join(", ");s.addIssue({code:v("RULE","MATCH_PATH_PARAMETER_COLLECTION_ACTION_MISMATCH"),message:`[${p}]: The exposure-level "Match path parameter" rule uses path parameter "${S}", which is not present in the collection route path ("${h}"). Collection action(s) (${E}) inherit this rule and will fail at runtime.`,suggestion:'Move the "Match path parameter" rule to individual resource actions (read, update, delete), or enable "overrideParentScenarios" on collection actions.',severity:"error",context:a})}}}}};var Rn=class{ruleType="allowAuthenticated";validate(){}};var $n=class{ruleType="lifecycleStatus";validate(e,t,i,r,s){if(!i?.entity?.key)return;let o={apiModelKey:r.key,kind:"AccessRule",key:e.type,parentExposedEntityKey:i.key};if(!s.domain)return;let n=s.findEntity(i.entity.key,i.entity.domain);if(!n)return;let l=n.info.getLabel(),d=Array.from(n.withInheritedProperties()).filter(S=>S.hasSemantic(g.Status));if(d.length===0){s.addIssue({code:v("RULE","LIFECYCLE_STATUS_MISSING_PROPERTY"),message:`[${l}]: The "lifecycleStatus" access rule requires "${l}" to have a property with the Status semantic (SemanticType.Status), but none was found.`,suggestion:`Add the Status semantic to a status/state property on "${l}", or remove the lifecycleStatus rule.`,severity:"error",context:o});return}if(d.length>1){let S=d.map(E=>`"${E.info.name||E.key}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_MULTIPLE_PROPERTIES"),message:`[${l}]: The entity has multiple properties with the Status semantic (${S}). The "lifecycleStatus" access rule requires exactly one Status property on the entity to avoid ambiguous resolution.`,suggestion:`Ensure only one property on "${l}" carries the Status semantic.`,severity:"error",context:o});return}let p=d[0],m=Array.isArray(e.allowedStatuses)?e.allowedStatuses:[],h=Array.isArray(e.deniedStatuses)?e.deniedStatuses:[];if(m.length===0&&h.length===0){s.addIssue({code:v("RULE","LIFECYCLE_STATUS_EMPTY_CONFIG"),message:`[${l}]: The "lifecycleStatus" access rule has neither "allowedStatuses" nor "deniedStatuses" configured. At least one status must be specified.`,suggestion:'Specify at least one status in "allowedStatuses" or "deniedStatuses".',severity:"error",context:o});return}let f=new Set(m),k=h.filter(S=>f.has(S));if(k.length>0){let S=k.map(E=>`"${E}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_CONFLICTING_STATUSES"),message:`[${l}]: The status ${S} is specified in both "allowedStatuses" and "deniedStatuses". A status cannot be simultaneously allowed and denied.`,suggestion:'Remove the conflicting status from either "allowedStatuses" or "deniedStatuses".',severity:"error",context:o})}let w;if(p.schema?.enum&&p.schema.enum.length>0)w=p.schema.enum;else{let S=p.semantics?.find(E=>E.id===g.Status);if(S&&"config"in S&&S.config){let E=S.config;Array.isArray(E.allowedStates)&&E.allowedStates.length>0&&(w=E.allowedStates)}}if(w&&w.length>0){let S=new Set(w),E=m.filter(_=>!S.has(_)),A=h.filter(_=>!S.has(_));if(E.length>0){let _=E.map(P=>`"${P}"`).join(", "),$=w.map(P=>`"${P}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_INVALID_STATUS"),message:`[${l}]: The status ${_} in "allowedStatuses" is not a valid state for property "${p.info.name||p.key}". Valid states are: ${$}.`,suggestion:`Update "allowedStatuses" to only include valid states: ${$}.`,severity:"error",context:o})}if(A.length>0){let _=A.map(P=>`"${P}"`).join(", "),$=w.map(P=>`"${P}"`).join(", ");s.addIssue({code:v("RULE","LIFECYCLE_STATUS_INVALID_STATUS"),message:`[${l}]: The status ${_} in "deniedStatuses" is not a valid state for property "${p.info.name||p.key}". Valid states are: ${$}.`,suggestion:`Update "deniedStatuses" to only include valid states: ${$}.`,severity:"error",context:o})}}}};var si=class{validators=new Map;constructor(){this.register(new fn),this.register(new kn),this.register(new vn),this.register(new wn),this.register(new Sn),this.register(new An),this.register(new En),this.register(new _n),this.register(new xn),this.register(new In),this.register(new Pn),this.register(new Rn),this.register(new $n)}register(e){this.validators.set(e.ruleType,e)}get(e){return this.validators.get(e)}validate(e,t,i,r,s,o){let a={apiModelKey:r.key,kind:"AccessRule",key:e.type,...i?{parentExposedEntityKey:i.key}:{}};if(!e.allowedLevels.includes(t)){if(t==="api")s.addIssue({code:v("RULE","INVALID_LEVEL"),message:`[${r.info.getLabel()}]: The "${e.type}" access rule cannot be used at the API level because it requires an entity or action context.`,suggestion:"Move this access rule to an exposed entity or action scenario.",severity:"error",context:a});else{let l=t==="exposure"?"an exposed entity":"an action",d=e.allowedLevels.join(", ");s.addIssue({code:v("RULE","INVALID_LEVEL"),message:`[${i?.entity?.key??i?.key}]: The "${e.type}" access rule cannot be used at the ${t} level because it is only allowed at: [${d}].`,suggestion:`Move this access rule to ${d.includes("api")?"the API level":l==="an exposed entity"?"an action":"an exposed entity"}.`,severity:"error",context:a})}return}r.authorization?.strategy&&(Xd(r.authorization.strategy,t).includes(e.type)||s.addIssue({code:v("RULE","INCOMPATIBLE_RULE_FOR_STRATEGY"),message:`The "${e.type}" access rule is not compatible with the ${r.authorization.strategy} authorization strategy.`,suggestion:"Switch to a strategy that supports this rule.",severity:"error",context:a}));let n=this.validators.get(e.type);n&&n.validate(e,t,i,r,s,o)}};var $s=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key};e.kind!==ke&&t.addIssue({code:v("API","INVALID_KIND"),message:"The API model type is incorrect.",suggestion:'Set the model type to "ApiModel".',severity:"error",context:{...i,property:"kind"}}),(!e.key||typeof e.key!="string"||e.key.trim()==="")&&t.addIssue({code:v("API","MISSING_KEY"),message:"The API model is missing a unique identifier.",suggestion:"Provide a valid name to use as a unique identifier.",severity:"error",context:{...i,property:"key"}}),(!e.info||!e.info.name||e.info.name.trim()==="")&&t.addIssue({code:v("API","MISSING_NAME"),message:"The API model has no defined name.",suggestion:"Provide a descriptive name for your API.",severity:"error",context:{...i,property:"info.name"}}),(!e.info||!e.info.description||e.info.description.trim()==="")&&t.addIssue({code:v("API","MISSING_DESCRIPTION"),message:"Adding a description helps others understand your API.",suggestion:"Add a description to clarify the purpose of this API.",severity:"warning",context:{...i,property:"info.description"}})}};var Os=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=e.domain;if(!r){t.addIssue({code:v("API","MISSING_DOMAIN"),message:"No Data Domain is attached to the API.",suggestion:"Select a Data Domain from the settings to power your API.",severity:"error",context:i});return}(!r.info||!r.info.version)&&t.addIssue({code:v("API","MISSING_DOMAIN_VERSION"),message:"The selected Data Domain is missing a version number.",suggestion:"Specify a version for the attached Data Domain.",severity:"error",context:i})}};var Ns=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=/^https?:\/\//i,s=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;e.contact?(e.contact.email&&!s.test(e.contact.email)&&t.addIssue({code:v("API","INVALID_CONTACT_EMAIL"),message:"The contact email address looks invalid.",suggestion:"Please double check the email address formatting.",severity:"error",context:{...i,property:"contact.email"}}),e.contact.url&&!r.test(e.contact.url)&&t.addIssue({code:v("API","INVALID_CONTACT_URL"),message:"The contact link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...i,property:"contact.url"}})):t.addIssue({code:v("API","MISSING_CONTACT"),message:"A contact email or link is highly recommended for API consumers.",suggestion:"Add an email or help desk link in the metadata tab.",severity:"info",context:{...i,property:"contact"}}),e.license?e.license.url&&!r.test(e.license.url)&&t.addIssue({code:v("API","INVALID_LICENSE_URL"),message:"The license link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...i,property:"license.url"}}):t.addIssue({code:v("API","MISSING_LICENSE"),message:"Adding a license to your API helps users understand its usage rights.",suggestion:"Add the name and a link to your API license terms.",severity:"info",context:{...i,property:"license"}}),e.termsOfService||t.addIssue({code:v("API","MISSING_TOS"),message:"Terms of Service help legal compliance.",suggestion:"Add a link to the terms of your API service.",severity:"info",context:{...i,property:"termsOfService"}})}};var Ts=class{validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=!1;for(let s of e.exposes.values())if(s.actions.some(o=>Pt.isListAction(o)||Rt.isSearchAction(o))){r=!0;break}r&&(!e.pagination||!e.pagination.kind?t.addIssue({code:v("API","MISSING_PAGINATION"),message:"The API must have a defined pagination strategy when it exposes List or Search actions.",suggestion:"Configure how results are loaded (e.g. by page or by a continuous cursor).",severity:"error",context:{...i,property:"pagination"}}):(e.pagination.defaultLimit===void 0&&t.addIssue({code:v("API","MISSING_PAGINATION_DEFAULT_LIMIT"),message:"The API doesn't have a defined default page limit when it exposes List or Search actions.",suggestion:"Set a default page limit for the pagination otherwise the API will use its default limit.",severity:"info",context:{...i,property:"pagination.defaultLimit"}}),e.pagination.maxLimit===void 0&&t.addIssue({code:v("API","MISSING_PAGINATION_MAX_LIMIT"),message:"The API doesn't have a defined page size max limit when it exposes List or Search actions.",suggestion:"Set a max page size limit for the pagination otherwise the API will use its default max limit.",severity:"info",context:{...i,property:"pagination.maxLimit"}})))}};var js=class{ruleRegistry;constructor(e=new si){this.ruleRegistry=e}validate(e,t){let i={apiModelKey:e.key,kind:ke,key:e.key},r=t.getUserEntity();if(!e.authentication)t.addIssue({code:v("API","MISSING_AUTHENTICATION"),message:"The API is missing authentication settings.",suggestion:"Go to the security settings and configure how users authenticate.",severity:"error",context:{...i,property:"authentication"}});else if(e.authentication.strategy==="UsernamePassword"&&r){let s;for(let a of r.properties)if(a.hasSemantic(g.Password)){s=a;break}s||t.addIssue({code:v("API","MISSING_PASSWORD_SEMANTIC"),message:"The selected user model requires a property with the Password data semantic for authentication.",suggestion:'Go to the Data Modeler and add the "Password" semantic to the password property.',severity:"error",context:{...i,property:"user"}});let o;for(let a of r.properties)if(a.hasSemantic(g.Username)){o=a;break}o||t.addIssue({code:v("API","MISSING_USERNAME_SEMANTIC"),message:"Username & Password authentication requires a field with the Username data semantic.",suggestion:'Go to the Data Modeler and add the "Username" semantic to the property used for login.',severity:"error",context:{...i,property:"user"}})}if(!e.authorization)t.addIssue({code:v("API","MISSING_AUTHORIZATION"),message:"The API is missing authorization settings.",suggestion:"Go to the security settings and configure how to handle user permissions.",severity:"error",context:{...i,property:"authorization"}});else{let s=e.authorization.strategy;if(s==="RBAC"){if(e.domain){let o=t.getUserSemantics();r&&(!o||!o.hasRole)&&t.addIssue({code:v("API","MISSING_ROLE_SEMANTIC"),message:"Role-based access control requires a property with the User Role data semantic on the user model.",suggestion:'Go to the Data Modeler and add the "User Role" semantic to the property used for roles.',severity:"error",context:{...i,property:"user"}})}}else if(s==="OrganizationRBAC"){if(e.domain){let o=t.getOrganizationSemantics();(!o||!o.hasOrganization)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_SEMANTIC"),message:"Tenant RBAC authorization strategy requires a Data Entity tagged with the Organization semantic.",suggestion:"Go to the Data Modeler and mark your Organization entity with the Organization semantic.",severity:"error",context:{...i,property:"authorization"}}),(!o||!o.hasMembersAssociation)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_MEMBERS_SEMANTIC"),message:"Tenant RBAC authorization strategy requires an association tagged with the Organization Members semantic.",suggestion:"Go to the Data Modeler and add the Organization Members semantic to the pivot association.",severity:"error",context:{...i,property:"authorization"}}),(!o||!o.hasOrganizationRole)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_ROLE_SEMANTIC"),message:"Tenant RBAC authorization strategy requires a property tagged with the Organization Role semantic.",suggestion:"Go to the Data Modeler and add the Organization Role semantic to the role property on Organization Members.",severity:"error",context:{...i,property:"authorization"}})}}else if(s==="EnterpriseRBAC"&&e.domain){let o=t.getUserSemantics();r&&(!o||!o.hasRole)&&t.addIssue({code:v("API","MISSING_ROLE_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires a property with the User Role data semantic on the user model.",suggestion:'Go to the Data Modeler and add the "User Role" semantic to the property used for roles.',severity:"error",context:{...i,property:"user"}});let a=t.getOrganizationSemantics();(!a||!a.hasOrganization)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires a Data Entity tagged with the Organization semantic.",suggestion:"Go to the Data Modeler and mark your Organization entity with the Organization semantic.",severity:"error",context:{...i,property:"authorization"}}),(!a||!a.hasMembersAssociation)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_MEMBERS_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires an association tagged with the Organization Members semantic.",suggestion:"Go to the Data Modeler and add the Organization Members semantic to the pivot association.",severity:"error",context:{...i,property:"authorization"}}),(!a||!a.hasOrganizationRole)&&t.addIssue({code:v("API","MISSING_ORGANIZATION_ROLE_SEMANTIC"),message:"Enterprise RBAC authorization strategy requires a property tagged with the Organization Role semantic.",suggestion:"Go to the Data Modeler and add the Organization Role semantic to the role property.",severity:"error",context:{...i,property:"authorization"}})}}if(!e.session)t.addIssue({code:v("API","MISSING_SESSION"),message:"The API is missing session configuration.",suggestion:"Configure how user sessions will be handled.",severity:"error",context:{...i,property:"session"}});else{if(e.session.secret||t.addIssue({code:v("API","MISSING_SESSION_SECRET"),message:"A secure encryption key is required for sessions.",suggestion:"Provide a strong security key in the session settings.",severity:"error",context:{...i,property:"session.secret"}}),!e.session.properties||e.session.properties.length===0)t.addIssue({code:v("API","MISSING_SESSION_PROPERTIES"),message:"The session token needs to include at least one piece of user information, like an ID.",suggestion:"Select fields that should be stored securely inside the session payload.",severity:"error",context:{...i,property:"session.properties"}});else if(e.authorization&&(e.authorization.strategy==="RBAC"||e.authorization.strategy==="EnterpriseRBAC")&&e.domain){let a=t.getUserSemantics();a?.roleProperty&&!e.session.properties.find(n=>n.key===a.roleProperty?.key)&&t.addIssue({code:v("API","MISSING_RBAC_SESSION_PROPERTY"),message:"The user role must be included in the session data for permissions to work.",suggestion:"Make sure your selected role property is checked in the session settings.",severity:"error",context:{...i,property:"session.properties"}})}let{cookie:s,jwt:o}=e.session;(!s||!s.enabled)&&(!o||!o.enabled)&&t.addIssue({code:v("API","MISSING_SESSION_TRANSPORT"),message:"No delivery method for sessions (like cookies or tokens) is enabled.",suggestion:"Enable at least one session delivery mechanism in the security settings.",severity:"error",context:{...i,property:"session"}})}if(e.user?e.domain&&!e.domain.findEntity(e.user.key,e.user.domain)&&t.addIssue({code:v("API","INVALID_USER_ENTITY"),message:"The selected user model no longer exists in your data domain.",suggestion:"Please navigate to security settings and select a valid user model.",severity:"error",context:{...i,property:"user"}}):t.addIssue({code:v("API","MISSING_USER_ENTITY"),message:"You need to specify what kind of object represents your users.",suggestion:"Select a model from your domain that stores your user accounts.",severity:"error",context:{...i,property:"user"}}),e.accessScenarios&&e.accessScenarios.length>0)for(let s of e.accessScenarios)for(let o of s.predicate.getLeafRules())this.ruleRegistry.validate(o,"api",void 0,e,t)}};var Ji=class{ruleRegistry;constructor(e=new si){this.ruleRegistry=e}validate(e,t,i,r){let s={apiModelKey:i.key,kind:"Action",key:e.kind,parentExposedEntityKey:t.key};if(tt.isDeleteAction(e)&&(e.strategy?e.strategy==="hard"&&r.addIssue({code:v("ACTION","DELETE_HARD_WARNING"),message:"Permanent delete is active. There will be no way to restore deleted data.",suggestion:'Consider switching to "soft delete" if users might need to undo mistakes.',severity:"info",context:{...s,property:"strategy"}}):r.addIssue({code:v("ACTION","DELETE_MISSING_STRATEGY"),message:"A Delete action must know if you want to completely erase the record, or just hide it.",suggestion:"Configure the deletion type (permanent or soft).",severity:"error",context:{...s,property:"strategy"}})),Ki.isUpdateAction(e)&&(!e.allowedMethods||e.allowedMethods.length===0)&&r.addIssue({code:v("ACTION","UPDATE_MISSING_METHODS"),message:"An Update action must define how the data is sent (PUT replaces everything; PATCH applies partial changes).",suggestion:"Select at least one allowed HTTP method.",severity:"error",context:{...s,property:"allowedMethods"}}),Bi.isRestoreAction(e)){let d=t.actions.find(tt.isDeleteAction);(!d||d.strategy!=="soft")&&r.addIssue({code:v("ACTION","RESTORE_REQUIRES_SOFT_DELETE"),message:"The Restore action requires Soft Delete to be configured on this entity.",suggestion:'Enable the Delete action with strategy "soft" before enabling Restore.',severity:"error",context:{...s,property:"kind"}})}if(e.getAllRateLimiters().some(d=>d.rules.length)||r.addIssue({code:v("ACTION","MISSING_RATE_LIMITS"),message:"It is best practice to configure a rate limit so your API is not overwhelmed.",suggestion:"Set a reasonable maximum request speed for this operation.",severity:"warning",context:s}),e.accessScenarios)for(let d of e.accessScenarios)for(let p of d.predicate.getLeafRules())this.ruleRegistry.validate(p,"action",t,i,r,e);e.overrideParentScenarios&&e.accessScenarios.length===0&&r.addIssue({code:v("ACTION","OVERRIDE_BUT_NO_SCENARIOS"),message:`Action "${e.kind}" has "Override parent scenarios" enabled but defines no scenarios of its own. This action will deny all access.`,suggestion:'Add at least one access scenario to this action, or uncheck "Override parent scenarios" to inherit parent policies.',severity:"warning",context:{...s,property:"overrideParentScenarios"}});let n=e.getAllScenarios();if(n.length===0){let d=t.entity?.key??t.key;r.addIssue({code:v("ACTION","MISSING_ACCESS_RULES"),message:`[${d}]: The ${e.kind} action has no security rules attached, making it entirely inaccessible or open.`,suggestion:"Allow specific user roles to access this operation.",severity:"error",context:{...s,kind:"Action",key:e.kind,parentExposedEntityKey:t.key}})}for(let d of n){let p=hn(d.predicate);p.length>0&&r.addIssue({code:v("ACTION","SCENARIO_EMPTY_PREDICATE_GROUP"),message:`Scenario "${d.label||d.key}" on action "${e.kind}" contains ${p.length===1?"an empty predicate group":`${p.length} empty predicate groups`}. Empty predicate groups have no effect and should contain child rules or be removed.`,suggestion:"Add access rules to the predicate group or remove the empty group from the scenario.",severity:"warning",context:{...s,property:"accessScenarios"}})}for(let d of n)Ps(d.predicate)||r.addIssue({code:v("ACTION","SCENARIO_MISSING_IDENTITY_RULE"),message:`Scenario "${d.label||d.key}" on action "${e.kind}" has no identity-constraining rules (e.g. AllowPublic, MatchUserRole). At least one identity rule is required.`,suggestion:"Add an identity rule such as AllowPublic, AllowAuthenticated, or MatchUserRole to this scenario.",severity:"error",context:{...s,property:"accessScenarios"}});let l=null;for(let d of n){let p=d.predicate.getLeafRules().filter(m=>m.isIdentityConstraining);if(p.length>0){if(p.every(h=>h.isBroadIdentityRule))l||(l=d);else if(l){r.addIssue({code:v("ACTION","SCENARIO_BROAD_BEFORE_NARROW"),message:`A broad access scenario ("${l.label||l.key}") appears before more specific scenarios. Broad scenarios match all callers and will cause later scenarios to never be evaluated.`,suggestion:"Move specific scenarios (e.g. admin or role-restricted) above broad scenarios (e.g. public or authenticated).",severity:"warning",context:{...s,property:"accessScenarios"}});break}}}if(e.projection&&(Pt.isListAction(e)||Rt.isSearchAction(e)||qi.isReadAction(e)||r.addIssue({code:v("ACTION","INVALID_PROJECTION_SEVERITY"),message:`Projections are only supported for read actions (List, Search, Read). The action "${e.kind}" does not support projections.`,suggestion:"Remove projection configuration from this write action.",severity:"warning",context:{...s,property:"projection"}}),e.projection.type!=="include"&&e.projection.type!=="exclude"&&r.addIssue({code:v("ACTION","INVALID_PROJECTION_TYPE"),message:'Projection type must be either "include" or "exclude".',suggestion:"Select a valid projection type.",severity:"error",context:{...s,property:"projection"}}),Array.isArray(e.projection.fields))){let p=r.domain??i.domain,m=t.entity?p?.findEntity(t.entity.key,t.entity.domain):void 0;if(m){let h=Array.from(m.withInheritedProperties()),f=new Set(h.map(w=>w.key)),k=new Set(Array.from(m.withInheritedAssociations()).map(w=>w.key));e.projection.fields.forEach((w,S)=>{if(w.invalid===!0){r.addIssue({code:v("ACTION","INVALID_PROJECTION_FIELD"),message:`The projected field "${w.key}" is marked as invalid. It was not found in the entity definition.`,suggestion:"Update or remove this field from the projection configuration.",severity:"error",context:{...s,property:`projection.fields[${S}]`}});return}if(w.type==="association"){let E=w.key.split("."),A=E[0];if(!k.has(A))r.addIssue({code:v("ACTION","INVALID_PROJECTION_ASSOCIATION"),message:`The projected association "${w.key}" does not exist on this entity.`,suggestion:"Select a valid association or remove it.",severity:"error",context:{...s,property:`projection.fields[${S}]`}});else{let _=Array.from(m.withInheritedAssociations()).find($=>$.key===A);E.length>1&&(!_||_.schema?.embedded!==!0)&&r.addIssue({code:v("ACTION","INVALID_PROJECTION_ASSOCIATION_EMBEDDED"),message:`The projected association "${w.key}" is invalid because association "${A}" is not embedded.`,suggestion:"Ensure the association is marked as embedded to use dot-notation.",severity:"error",context:{...s,property:`projection.fields[${S}]`}})}}else{let E=w.key.split("."),A=E[0];if(!f.has(A))r.addIssue({code:v("ACTION","INVALID_PROJECTION_PROPERTY"),message:`The projected property "${w.key}" does not exist on this entity.`,suggestion:"Select a valid property or remove it.",severity:"error",context:{...s,property:`projection.fields[${S}]`}});else{let _=h.find($=>$.key===A);E.length>1&&(!_||_.type!=="json"?r.addIssue({code:v("ACTION","INVALID_PROJECTION_JSON_ROOT"),message:`The projected property "${w.key}" is invalid because root property "${A}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...s,property:`projection.fields[${S}]`}}):_.jsonSchema&&(St(_.jsonSchema,E.slice(1))||r.addIssue({code:v("ACTION","INVALID_PROJECTION_JSON_PATH"),message:`The projected property "${w.key}" is invalid according to the JSON Schema of "${A}".`,suggestion:"Configure a valid JSON Schema path or update the projection path.",severity:"error",context:{...s,property:`projection.fields[${S}]`}})))}}})}}}};var Cs=class{actionValidator;ruleRegistry;constructor(e=new Ji,t=new si){this.actionValidator=e,this.ruleRegistry=t}validate(e,t,i){let r={apiModelKey:t.key,kind:Ht,key:e.key},s=i.domain??t.domain,o=e.entity?s?.findEntity(e.entity.key,e.entity.domain):void 0,a=o?.info.getLabel()||o?.key||"unknown";!e.entity||!e.entity.key?i.addIssue({code:v("EXPOSURE","MISSING_ENTITY_REF"),message:"This exposed endpoint does not point to a specific data model.",suggestion:"Select which database entity this endpoint should serve.",severity:"error",context:{...r,property:"entity"}}):o||i.addIssue({code:v("EXPOSURE","INVALID_ENTITY_REF"),message:"This endpoint points to a data model that no longer exists.",suggestion:"Select a new valid database model or delete this endpoint.",severity:"error",context:{...r,property:"entity"}});let n=o?.hasSemantic(g.User);if(e.isRoot&&o&&!n&&s&&s.resolveOwnershipPath(o.key)===null&&i.addIssue({code:v("EXPOSURE","MISSING_OWNER_PATH"),message:`[${a}]: This root endpoint has no ownership path to the User entity. If you want this resource to be user-isolated, add the Relational Resource Owner semantic to the association that defines its owner.`,suggestion:"Ensure the resource has a direct (Resource Owner Identifier) or indirect (Relational Resource Owner) path to the User entity.",severity:"warning",context:r}),e.parent?.selfRoute){let d=t.exposes.get(e.parent.key);d?(!d.hasCollection||!d.collectionPath)&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_REQUIRES_COLLECTION"),message:`[${a}]: selfRoute can only be applied under a parent exposure that has a collection endpoint.`,suggestion:"Enable collection on the parent exposure or remove selfRoute.",severity:"error",context:{...r,property:"parent.key"}}):i.addIssue({code:v("EXPOSURE","SELF_ROUTE_PARENT_NOT_FOUND"),message:`[${a}]: The parent exposed entity "${e.parent.key}" for selfRoute does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...r,property:"parent.key"}}),e.parent.association&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_ASSOCIATION_FORBIDDEN"),message:`[${a}]: A selfRoute exposure must not specify an association on its parent reference.`,suggestion:"Remove the association from the selfRoute parent reference.",severity:"error",context:{...r,property:"parent.association"}}),o&&!o.hasSemantic(g.User)&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_NOT_USER_ENTITY"),message:`[${a}]: selfRoute exposure can only be applied to an entity carrying the User semantic.`,suggestion:"Annotate this entity with the User semantic or remove selfRoute.",severity:"error",context:{...r,property:"entity"}});let p=["read","update","delete","unlink"],m=e.actions.filter(h=>!p.includes(h.kind));m.length>0&&i.addIssue({code:v("EXPOSURE","SELF_ROUTE_INVALID_ACTION"),message:`[${a}]: The /me endpoint is a singleton resource. Only 'read', 'update', 'delete', and 'unlink' actions are permitted.`,suggestion:`Remove unsupported actions (${m.map(h=>`'${h.kind}'`).join(", ")}) from this selfRoute exposure.`,severity:"error",context:{...r,property:"actions"}});for(let h of e.actions)h.accessScenarios.some(k=>{let w=k.predicate.getLeafRules(),S=w.some(A=>A.type==="allowAuthenticated"),E=w.some(A=>A.type==="matchResourceOwner"&&A.target==="user-entity");return S&&E})||i.addIssue({code:v("EXPOSURE","SELF_ROUTE_MISSING_PREDEFINED_RULES"),message:`[${a}]: Action "${h.kind}" on a selfRoute exposure must include the invariant security rules (AllowAuthenticated and MatchResourceOwner with target 'user-entity').`,suggestion:"Ensure each action on a selfRoute exposure includes AllowAuthenticated and MatchResourceOwner (target: user-entity) rules.",severity:"error",context:{...r,property:"actions"}});for(let h of t.exposes.values())if(h.key!==e.key&&h.parent?.selfRoute&&h.parent.key===e.parent.key){i.addIssue({code:v("EXPOSURE","SELF_ROUTE_DUPLICATE"),message:`[${a}]: Only one selfRoute exposure may be registered per parent exposure.`,suggestion:"Remove duplicate selfRoute under this parent exposure.",severity:"error",context:{...r,property:"parent.selfRoute"}});break}}if(!e.isRoot&&s){if(!e.parent)i.addIssue({code:v("EXPOSURE","MISSING_PARENT_REF"),message:`[${a}]: A sub-endpoint (non-root exposure) must have a parent endpoint.`,suggestion:"Expose this entity under a parent entity or make it a root endpoint.",severity:"error",context:{...r,property:"parent"}});else if(!e.parent.selfRoute){let d=t.exposes.get(e.parent.key);if(!d)i.addIssue({code:v("EXPOSURE","INVALID_PARENT_EXPOSURE"),message:`[${a}]: The parent exposed entity "${e.parent.key}" does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...r,property:"parent.key"}});else if(!e.parent.association)i.addIssue({code:v("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${a}]: A sub-endpoint must specify a parent association.`,suggestion:"Select a valid association in the data domain connecting parent and child entities.",severity:"error",context:{...r,property:"parent.association"}});else{let p=s.findEntity(d.entity.key,d.entity.domain),m=e.parent.association.key,h=s.findAssociation(m,e.parent.association.domain);if(!h)i.addIssue({code:v("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${a}]: The parent association "${m}" does not exist in the data domain.`,suggestion:"Select a valid association in the data domain that connects the parent and child entities.",severity:"error",context:{...r,property:"parent.association"}});else{let f=p?.key,k=o?.key,w=h.getParentInstance()?.key===f,S=h.getParentInstance()?.key===k,E=h.targets.some($=>$.key===f),A=h.targets.some($=>$.key===k);w&&A||S&&E||i.addIssue({code:v("EXPOSURE","INVALID_PARENT_ASSOCIATION"),message:`[${a}]: The parent association "${m}" does not connect the parent entity "${p?.info.name||f}" with the child entity "${o?.info.name||k}".`,suggestion:"Use an association that directly connects the parent and child data entities.",severity:"error",context:{...r,property:"parent.association"}})}}}}if(e.hasCollection){if(!e.collectionPath)i.addIssue({code:v("EXPOSURE","MISSING_COLLECTION_PATH"),message:`[${a}]: When an endpoint exposes a collection, it must define what its base URL path is.`,suggestion:'Add a path (e.g., "/items").',severity:"error",context:{...r,property:"collectionPath"}});else{let d=e.collectionPath.split("/").filter(Boolean);(d.length!==1||!e.collectionPath.startsWith("/"))&&i.addIssue({code:v("EXPOSURE","INVALID_COLLECTION_PATH"),message:`[${a}]: The collection URL should start with "/" and have no extra slashes.`,suggestion:`Ensure the path looks like exactly "/${d[0]||"subresource"}".`,severity:"error",context:{...r,property:"collectionPath"}}),e.isRoot&&/^\/verify[-_].*$/i.test(e.collectionPath)&&i.addIssue({code:v("EXPOSURE","RESERVED_COLLECTION_PATH"),message:`[${a}]: The route "${e.collectionPath}" matches the reserved pattern "/verify-*".`,suggestion:'Root routes starting with "/verify-" are reserved for platform verification endpoints (e.g. /verify-email, /verify-phone).',severity:"error",context:{...r,property:"collectionPath"}})}e.resourcePath?e.collectionPath&&(new RegExp(`^${e.collectionPath}/\\{[a-zA-Z0-9_]+\\}$`).test(e.resourcePath)||i.addIssue({code:v("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${a}]: The single item route should match exactly your collection path plus one identifier variable.`,suggestion:`Make sure the item path is formatted exactly like "${e.collectionPath}/{id}".`,severity:"error",context:{...r,property:"resourcePath"}})):i.addIssue({code:v("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${a}]: You need an identifier to locate single items.`,suggestion:'Specify the identification parameter format, like "{id}".',severity:"error",context:{...r,property:"resourcePath"}})}else e.resourcePath?((e.resourcePath.split("/").filter(Boolean).length!==1||!e.resourcePath.startsWith("/"))&&i.addIssue({code:v("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${a}]: The URL route ${e.resourcePath} must only contain one exact part or level.`,suggestion:"Simplify the endpoint URL to a single segment.",severity:"error",context:{...r,property:"resourcePath"}}),e.isRoot&&/^\/verify[-_].*$/i.test(e.resourcePath)&&i.addIssue({code:v("EXPOSURE","RESERVED_RESOURCE_PATH"),message:`[${a}]: The route "${e.resourcePath}" matches the reserved pattern "/verify-*".`,suggestion:'Root routes starting with "/verify-" are reserved for platform verification endpoints (e.g. /verify-email, /verify-phone).',severity:"error",context:{...r,property:"resourcePath"}})):i.addIssue({code:v("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${a}]: Exposed entity representing a single item must declare their URL route.`,suggestion:'Set the URL path (such as "/profile").',severity:"error",context:{...r,property:"resourcePath"}});e.isRoot&&(e.collectionPath&&t.findCollectionPathCollision(e.collectionPath,e.key)&&i.addIssue({code:v("EXPOSURE","ROOT_COLLECTION_COLLISION"),message:`[${a}]: The route "${e.collectionPath}" is already used by another view.`,suggestion:"Give this resource a different path to avoid conflicts.",severity:"error",context:{...r,property:"collectionPath"}}),e.resourcePath&&t.findResourcePathCollision(e.resourcePath,e.key)&&i.addIssue({code:v("EXPOSURE","ROOT_RESOURCE_COLLISION"),message:`[${a}]: The route "${e.resourcePath}" is already used by another one.`,suggestion:"Give this single-item resource a different path to avoid conflicts.",severity:"error",context:{...r,property:"resourcePath"}}));let l=e.getAbsoluteResourcePath();if(l){let d=[...l.matchAll(/\{([^}]+)\}/g)].map(m=>m[1]);if(new Set(d).size!==d.length){let h=d.filter((f,k)=>d.indexOf(f)!==k)[0];i.addIssue({code:v("EXPOSURE","DUPLICATE_PATH_PARAMETER"),message:`[${a}]: The path parameter "{${h}}" is duplicated in the resource path hierarchy.`,suggestion:"Change the parameter name in either this resource or its ancestor to ensure unique parameter names.",severity:"error",context:{...r,property:"resourcePath"}})}}if(!e.actions||e.actions.length===0)i.addIssue({code:v("EXPOSURE","MISSING_ACTIONS"),message:`[${a}]: This exposed entity does not let users do anything.`,suggestion:"Enable at least one operation like Create, Read, or Update.",severity:"error",context:{...r,property:"actions"}});else{let d=!1,p=!1,m=!1,h=!1;for(let f of e.actions)this.actionValidator.validate(f,e,t,i),Rt.isSearchAction(f)&&(d=!0),Pt.isListAction(f)&&(p=!0),(f.kind==="link"||f.kind==="unlink")&&(m=!0),(f.kind==="create"||f.kind==="delete")&&(h=!0);if(m&&h&&i.addIssue({code:v("EXPOSURE","MUTUALLY_EXCLUSIVE_ACTIONS"),message:`[${a}]: An endpoint cannot mix Many-to-Many actions (Link/Unlink) with standard Create/Delete actions.`,suggestion:"Use Link/Unlink for pivot tables and Create/Delete for standard resources.",severity:"error",context:{...r,property:"actions"}}),p||d){let f=e.paginationContract;if(!f)i.addIssue({code:v("EXPOSURE","MISSING_PAGINATION_CONTRACT"),message:`[${a}]: The List or Search action needs a pagination contract.`,suggestion:"Add a pagination contract to the exposed entity.",severity:"error",context:r});else{if(p&&((!f.filterableFields||f.filterableFields.length===0)&&i.addIssue({code:v("EXPOSURE","LIST_MISSING_FILTERS"),message:`[${a}]: Listing all elements without filters could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow filtering.",severity:"warning",context:r}),(!f.sortableFields||f.sortableFields.length===0)&&i.addIssue({code:v("EXPOSURE","LIST_MISSING_SORTING"),message:`[${a}]: Listing all elements without sorting could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow sorting.",severity:"warning",context:r})),d){let k=[];Array.isArray(f.searchableFields)&&k.push(...f.searchableFields),Array.isArray(f.filterableFields)&&k.push(...f.filterableFields),k.length||i.addIssue({code:v("EXPOSURE","SEARCH_MISSING_FIELDS"),message:`[${a}]: Search action needs to know which text fields to look in.`,suggestion:"Select a few important fields to allow searching or full-text search.",severity:"warning",context:r})}if(o){let k=Array.from(o.withInheritedProperties()),w=new Set(k.map(E=>E.key)),S=(E,A,_,$)=>{if(E&&Array.isArray(E))for(let P of E){let j=P.split("."),L=j[0];if(!w.has(L))i.addIssue({code:v("EXPOSURE",_),message:`[${a}]: The ${$} field "${P}" does not exist on this entity.`,suggestion:`Select a valid property on the entity for ${$}.`,severity:"error",context:{...r,property:`paginationContract.${A}Fields`}});else{let I=k.find(R=>R.key===L);j.length>1&&(!I||I.type!=="json"?i.addIssue({code:v("EXPOSURE",_),message:`[${a}]: The ${$} field "${P}" is invalid because root property "${L}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...r,property:`paginationContract.${A}Fields`}}):I.jsonSchema&&(St(I.jsonSchema,j.slice(1))||i.addIssue({code:v("EXPOSURE",_),message:`[${a}]: The ${$} field "${P}" is invalid according to the JSON Schema of "${L}".`,suggestion:"Configure a valid JSON Schema path or update the field path.",severity:"error",context:{...r,property:`paginationContract.${A}Fields`}})))}}};S(f.filterableFields,"filterable","INVALID_FILTER_FIELD","filterable"),S(f.sortableFields,"sortable","INVALID_SORT_FIELD","sortable"),S(f.searchableFields,"searchable","INVALID_SEARCH_FIELD","searchable")}}}}if(e.accessScenarios)for(let d of e.accessScenarios)for(let p of d.predicate.getLeafRules())this.ruleRegistry.validate(p,"exposure",e,t,i);this.validateTaxonomyOrgScoping(e,t,i)}validateTaxonomyOrgScoping(e,t,i){let r=t.authorization?.strategy;if(!(r==="OrganizationRBAC"||r==="EnterpriseRBAC"))return;let o=i.domain??t.domain;if(!o||!e.entity?.key)return;let a=o.findEntity(e.entity.key,e.entity.domain);if(!a)return;let n=a.info.getLabel()||a.key,l={apiModelKey:t.key,kind:Ht,key:e.key};for(let d of a.withInheritedAssociations()){if(d.hasSemantic(g.Tags)&&!d.isLinked())for(let p of d.targets){let m=o.findEntity(p.key,p.domain);if(m&&!Array.from(m.withInheritedAssociations()).some(f=>f.hasSemantic(g.OrganizationResource))){let f=m.info.getLabel()||m.key,k=d.info.getLabel()||d.key;i.addIssue({code:"tags_target_not_org_scoped_in_org_api",message:`[${n}]: The target entity "${f}" of Tags association "${k}" is not organization-scoped, but the API uses an organization authorization strategy (${r}).`,suggestion:`Add an association with SemanticType.OrganizationResource to the "${f}" entity to scope tags to organizations.`,severity:"error",context:{...l,property:d.key}})}}if(d.hasSemantic(g.Categories)&&!d.isLinked())for(let p of d.targets){let m=o.findEntity(p.key,p.domain);if(m&&!Array.from(m.withInheritedAssociations()).some(f=>f.hasSemantic(g.OrganizationResource))){let f=m.info.getLabel()||m.key,k=d.info.getLabel()||d.key;i.addIssue({code:"categories_target_not_org_scoped_in_org_api",message:`[${n}]: The target entity "${f}" of Categories association "${k}" is not organization-scoped, but the API uses an organization authorization strategy (${r}).`,suggestion:`Add an association with SemanticType.OrganizationResource to the "${f}" entity to scope categories to organizations.`,severity:"error",context:{...l,property:d.key}})}}}}};var On=class{model;report=[];#e=0;#t=0;#i=0;#r=!1;infoValidator=new $s;dependencyValidator=new Os;securityValidator=new js;paginationValidator=new Ts;metadataValidator=new Ns;exposureValidator=new Cs;actionValidator=new Ji;get infoCount(){return this.#r||this.computeIssueCounters(),this.#e}get warningCount(){return this.#r||this.computeIssueCounters(),this.#t}get errorCount(){return this.#r||this.computeIssueCounters(),this.#i}constructor(e){this.model=e}validate(){this.#r=!1,this.report=[];let e=new gt(this.model);if(this.infoValidator.validate(this.model,e),this.dependencyValidator.validate(this.model,e),this.securityValidator.validate(this.model,e),this.paginationValidator.validate(this.model,e),this.metadataValidator.validate(this.model,e),!this.model.exposes||this.model.exposes.size===0)e.addIssue({code:v("API","NO_EXPOSURES"),message:"Your API currently has no exposed data for external clients to request.",suggestion:"Expose a data model so apps can communicate with it.",severity:"warning",context:{apiModelKey:this.model.key,kind:ke,key:this.model.key,property:"exposes"}});else for(let t of this.model.exposes.values())this.exposureValidator.validate(t,this.model,e);return this.report=e.report,this.report}validateInfo(){let e=new gt(this.model);return this.infoValidator.validate(this.model,e),e.report}validateDependency(){let e=new gt(this.model);return this.dependencyValidator.validate(this.model,e),e.report}validateSecurity(){let e=new gt(this.model);return this.securityValidator.validate(this.model,e),e.report}validatePagination(){let e=new gt(this.model);return this.paginationValidator.validate(this.model,e),e.report}validateMetadata(){let e=new gt(this.model);return this.metadataValidator.validate(this.model,e),e.report}validateExposure(e){let t=new gt(this.model);return this.exposureValidator.validate(e,this.model,t),t.report}validateAction(e,t){let i=new gt(this.model);return this.actionValidator.validate(e,t,this.model,i),i.report}computeIssueCounters(){this.#e=this.report.filter(e=>e.severity==="info").length,this.#t=this.report.filter(e=>e.severity==="warning").length,this.#i=this.report.filter(e=>e.severity==="error").length,this.#r=!0}};var Tn=class extends Ae{constructor(t,i,r){super(i,r);this.file=t}file;async execute(){y.debug("[validate] Executing schema validation...");try{this.validateArguments();let t=await this.loadSchema();this.validateSchemaStructure(t);let i=t.kind,r=[];i===Ee?r=await this.validateDataDomain(t):i===ke?r=await this.validateApiModel(t):(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Unsupported schema kind "${i}". Supported kinds: "${Ee}", "${ke}".`}),process.exit(1)),this.reportResults(r,i)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}get isRemoteValidationWithoutOrg(){return!!(this.options.fid&&!this.options.org&&!N.resolved.org)}get shouldReadFromStdin(){return!!(this.options.stdin||!this.file&&!process.stdin.isTTY)}validateArguments(){this.file&&this.options.stdin&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both [file] path and --stdin"}),process.exit(1)),this.options.org&&!this.options.fid&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID (--fid) is required when using remote validation (--org)."}),process.exit(1)),this.isRemoteValidationWithoutOrg&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Organization ID is required for remote validation. Use --org <oid> or configure a default org."}),process.exit(1))}async loadSchema(){return y.debug(`[validate] Loading schema (remote=${!!this.options.fid})...`),this.options.fid?this.loadRemoteSchema():this.loadLocalSchema()}async loadRemoteSchema(){let t=this.resolveOrgId("Organization ID is required for remote validation.","Use --org <oid> or configure a default org.");y.debug(`[validate] Fetching remote schema file ID '${this.options.fid}' from organization '${t}'...`);let i=F(),{media:r}=await i.files.readMedia(t,this.options.fid,{token:i.token});return y.debug("[validate] Remote schema loaded successfully."),r}async loadLocalSchema(){let t;if(this.shouldReadFromStdin)y.debug("[validate] Reading schema from STDIN..."),t=await this.readStdin();else if(this.file){let i=ap.resolve(this.file);y.debug(`[validate] Reading local schema file from path: ${i}`),Nn.existsSync(i)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${i}`}),process.exit(1)),t=Nn.readFileSync(i,"utf8")}else this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"A file path, --stdin, or remote --org and --fid must be specified."}),process.exit(1);try{let i=JSON.parse(t);return y.debug("[validate] Local schema parsed successfully."),i}catch(i){let r=i instanceof Error?i.message:String(i);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse schema JSON: ${r}`}),process.exit(1)}}isValidSchemaStructure(t){return!!t&&typeof t=="object"&&!Array.isArray(t)&&"kind"in t}validateSchemaStructure(t){this.isValidSchemaStructure(t)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:'Invalid schema. The schema must be a JSON object containing a "kind" property.'}),process.exit(1))}async validateDataDomain(t){y.debug("[validate:domain] Validating schema as Data Domain...");let i=[];if(this.options.fid){let a=F(),n=t.dependencyList||[];n.length>0&&(y.debug(`[validate:domain] Listing ${n.length} dependency data domains from catalog...`),i=(await a.dataCatalog.listDependencies(n,{token:a.token})).data||[])}let r=new Me(t,i,{readOnly:!0}),o=new Zi(r).validate();return y.debug(`[validate:domain] Domain validation rules executed. Issues found: ${o.length}`),o}async validateApiModel(t){y.debug("[validate:api] Validating schema as API Model...");let i;if(this.options.fid){let a=F(),n=t.dependencyList||[];if(n.length>0){y.debug(`[validate:api] Listing ${n.length} dependency data domains from catalog...`);let d=(await a.dataCatalog.listDependencies(n,{token:a.token})).data||[];d.length>0&&(i=new Me(d[0],d,{readOnly:!0}))}}else if(this.options.domain){let a=ap.resolve(this.options.domain);y.debug(`[validate:api] Loading domain dependency from local path: ${a}`),Nn.existsSync(a)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${a}`}),process.exit(1));let n;try{n=JSON.parse(Nn.readFileSync(a,"utf8"))}catch(l){let d=l instanceof Error?l.message:String(l);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${d}`}),process.exit(1)}i=new Me(n,[],{readOnly:!0})}let r=new Ei(t,i),o=new On(r).validate();return y.debug(`[validate:api] API Model validation rules executed. Issues found: ${o.length}`),o}reportResults(t,i){y.debug(`[validate] Reporting results. Found ${t.length} validation issue(s).`);let r=t.some(s=>s.severity==="error");if(N.resolved.format==="json")console.log(JSON.stringify({isValid:!r,validationIssues:t},null,2));else if(t.length===0)this.formatter.success("Validation passed. No issues found!");else{let s=this.formatIssues(t,i);this.formatter.list(s,["severity","code","message","suggestion","context"],{headers:["SEVERITY","CODE","MESSAGE","SUGGESTION","CONTEXT"]});let o=t.filter(l=>l.severity==="error").length,a=t.filter(l=>l.severity==="warning").length,n=t.filter(l=>l.severity==="info").length;console.log(""),o>0?console.error(ie.red(`\u2716 Validation failed: ${o} error(s), ${a} warning(s), ${n} info(s).`)):console.log(ie.yellow(`\u26A0 Validation passed with warnings: ${a} warning(s), ${n} info(s).`))}r&&process.exit(1)}formatIssues(t,i){return t.map(r=>{let s=r.severity||"info",o=r.message||"",a,n,l;if(i===Ee){let d=r;a=d.rule||"unknown",n=d.help||"",l=d.key?`${d.kind||"unknown"}: ${d.key}`:d.field||""}else{let d=r;a=d.code||"unknown",n=d.suggestion||"";let p=d.context||{};l=`${p.kind||"unknown"}: ${p.key||""}${p.property?"."+p.property:""}`}return{severity:s,code:a,message:o,suggestion:n,context:l}})}async readStdin(){return new Promise((t,i)=>{let r="";process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{r+=s}),process.stdin.on("end",()=>{t(r)}),process.stdin.on("error",s=>{i(s)})})}};function np(c){c.command("validate [file]").description("Validate a Data Domain or API Model schema").option("--stdin","Read schema content from STDIN").option("--org <oid>","Organization ID (remote validation)").option("--fid <fid>","File ID / schema ID (remote validation)").option("--domain <path>","Path to local Data Domain schema file (only for local API Model validation)").action(async(e,t)=>{let i=new K({format:N.resolved.format});y.debug("[validate] Starting validation process..."),await new Tn(e,t,i).execute()})}var Ke=class extends Ae{client;fileManager;constructor(e,t,i=F(),r=new Z){super(e,t),this.client=i,this.fileManager=r}resolveVersionOption(e){return e.catalogVersion||e.ver}};var jn=class c extends Ke{static ALLOWED_SCOPES=["public","organization","private"];static ALLOWED_LIFECYCLES=["dev","beta","stable"];constructor(e,t,i=F(),r=new Z){super(e,t,i,r)}async execute(){let e=this.resolveOrgId(),t=this.resolveVersionOption(this.options);y.debug(`[catalog:publish] Starting publish flow with options: file=${this.options.file}, name=${this.options.name}, scope=${this.options.scope}, version=${t}, org=${e}, lifecycle=${this.options.lifecycle}`);let i=await this.resolveFileId(e),r=await this.resolveName(),s=await this.resolveDescription(),o=await this.resolveScope(),a=await this.resolveVersion(t),n=this.validateLifecycle(this.options.lifecycle);try{let l=await this.resolveOrCreateCatalogId(i,e,r,s,o),d=await this.publishVersion(l,o,n,a,this.options.changelog);this.formatter.success(`Successfully published version '${a}' to the data catalog!`,d)}catch(l){let d=U(l);this.formatter.error(d),process.exit(1)}}async resolveFileId(e){let t=this.options.file;if(!t&&process.stdout.isTTY){y.debug("[catalog:publish] File ID not provided; listing data domain files for selection...");try{let r=(await this.client.files.list(e,{filter:{field:"kind",operator:"eq",value:ni}},{token:this.client.token})).data||[];r.length>0&&(t=await Ce("Select a data domain file to publish:",r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch{}}return t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1)),t}async resolveName(){let e=this.options.name;return!e&&process.stdout.isTTY&&(e=await pe("Enter catalog entry name:")),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1)),e}async resolveDescription(){let e=this.options.description;return!e&&process.stdout.isTTY&&(e=await pe("Enter catalog entry description:")),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Description is required.",detail:"Specify --description <desc>."}),process.exit(1)),e}async resolveScope(){let e=this.options.scope;return!e&&process.stdout.isTTY&&(e=await Ce("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Scope is required.",detail:"Specify --scope <scope> (allowed: public, organization, private)."}),process.exit(1)),c.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'.`,detail:`Allowed: ${c.ALLOWED_SCOPES.join(", ")}`}),process.exit(1)),e}async resolveVersion(e){let t=e;return!t&&process.stdout.isTTY&&(t=await pe("Enter semantic version:","1.0.0")),t||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Version is required.",detail:"Specify --catalog-version <ver> or --ver <ver>."}),process.exit(1)),t}validateLifecycle(e){return c.ALLOWED_LIFECYCLES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${e}'.`,detail:`Allowed: ${c.ALLOWED_LIFECYCLES.join(", ")}`}),process.exit(1)),e}async resolveOrCreateCatalogId(e,t,i,r,s){y.debug(`[catalog:publish] Checking publication status for file ID '${e}' in organization '${t}'...`);let o=null;try{o=(await this.client.dataCatalog.checkPublicationStatus(e,t,{token:this.client.token})).key,y.debug(`[catalog:publish] Found existing catalog entry key: ${o}`)}catch(a){if(U(a).status!==404)throw a;y.debug("[catalog:publish] Catalog entry does not exist yet.")}if(o)y.debug(`[catalog:publish] Using existing catalog entry key: ${o}`),N.resolved.format!=="json"&&console.log(`Catalog entry already exists (ID: ${o}). Publishing new version...`);else{y.debug("[catalog:publish] Creating a new catalog entry..."),N.resolved.format!=="json"&&console.log("Catalog entry does not exist. Creating new catalog entry...");let a={key:"",kind:wt,organization:t,file:e,scope:s,name:i,description:r,publishedBy:"",publishedAt:0,createdAt:0,updatedAt:0,tags:[]};o=(await this.client.dataCatalog.publish(a,{token:this.client.token})).key,y.debug(`[catalog:publish] Created new catalog entry with key: ${o}`)}return o}async publishVersion(e,t,i,r,s){let o=Li.createSchema({scope:t,lifecycle:i,version:r,changelog:s||void 0});y.debug(`[catalog:publish] Publishing version '${r}' for catalog key '${e}'...`);let a=await this.client.dataCatalog.publishVersion(e,o,{token:this.client.token});return y.debug(`[catalog:publish] Version published successfully. Version key: ${a.key}`),a}};var Cn=class c extends Ke{static ALLOWED_SCOPES=["all","public","organization","private"];constructor(e,t,i=F()){super(e,t,i)}async execute(){let e=this.options.org||N.resolved.org;y.debug(`[catalog:list] Listing catalog with options: scope=${this.options.scope}, org=${e}, key=${this.options.key}`),this.validateScope(this.options.scope),this.ensureOrgIdIfRequired(this.options.scope,e);try{this.options.key?await this.listVersions(this.options.key):await this.listItems(this.options.scope,e)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}validateScope(e){c.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'. Allowed: ${c.ALLOWED_SCOPES.join(", ")}`}),process.exit(1))}ensureOrgIdIfRequired(e,t){["organization","private"].includes(e)&&!t&&(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:`Organization ID (--org <oid>) is required when filtering by scope '${e}'.`}),process.exit(1))}async listVersions(e){y.debug(`[catalog:list] Fetching versions for catalog entry key '${e}'...`);let i=(await this.client.dataCatalog.listVersions(e,{token:this.client.token})).data||[];y.debug(`[catalog:list] Found ${i.length} versions.`);let r=i.map(s=>({key:s.key,version:s.version,published:new Date(s.published).toLocaleString()}));this.formatter.list(r,["key","version","published"],{headers:["VERSION KEY","VERSION","PUBLISHED AT"]})}async listItems(e,t){let i=await this.fetchEntries(e,t),r=this.deduplicateEntries(i);this.formatItems(r)}async fetchEntries(e,t){let i=[];if(e==="all"){y.debug("[catalog:list] Fetching public catalog entries...");let r=await this.fetchScope("public",t);if(i.push(...r),t){y.debug(`[catalog:list] Fetching organization catalog entries for org '${t}'...`);let s=await this.fetchScope("organization",t);i.push(...s),y.debug(`[catalog:list] Fetching private catalog entries for org '${t}'...`);let o=await this.fetchScope("private",t);i.push(...o)}}else{y.debug(`[catalog:list] Fetching catalog entries for scope '${e}' and org '${t}'...`);let r=await this.fetchScope(e,t);i.push(...r)}return i}async fetchScope(e,t){try{return(await this.client.dataCatalog.list({scope:e,oid:t},{token:this.client.token})).data||[]}catch{return y.debug(`[catalog:list] Failed to fetch catalog entries for scope '${e}'.`),[]}}deduplicateEntries(e){y.debug(`[catalog:list] Total raw catalog entries fetched: ${e.length}`);let t=new Set,i=e.filter(r=>{let s=r.key;return t.has(s)?!1:(t.add(s),!0)});return y.debug(`[catalog:list] Total unique catalog entries: ${i.length}`),i}formatItems(e){let t=e.map(i=>{let r=i.versions&&i.versions[0]?i.versions[0].version:"N/A";return{key:i.key,name:i.name,scope:i.scope,lastVersion:r,organization:i.organization||"N/A"}});this.formatter.list(t,["key","name","scope","lastVersion","organization"],{headers:["KEY","NAME","SCOPE","LAST VERSION","ORGANIZATION"]})}};var Dn=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);y.debug(`[catalog:show] Reading catalog entry key='${this.key}', version='${e||"latest"}'`);try{if(e){let t=await this.client.dataCatalog.readVersion(this.key,e,{token:this.client.token});this.formatter.object(t)}else{let t=await this.client.dataCatalog.read(this.key,{token:this.client.token});this.formatter.object(t)}}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var Ln=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options),t=await this.resolveReason();try{if(e){y.debug(`[catalog:deprecate] Deprecating version '${e}' of catalog entry '${this.key}'...`);let i=await this.client.dataCatalog.deprecateVersion(this.key,e,t,{token:this.client.token});this.formatter.success(`Successfully deprecated version '${e}' of data catalog entry '${this.key}'.`,i)}else{y.debug(`[catalog:deprecate] Deprecating catalog entry '${this.key}'...`);let i=await this.client.dataCatalog.deprecate(this.key,t,{token:this.client.token});this.formatter.success(`Successfully deprecated data catalog entry '${this.key}'.`,i)}}catch(i){let r=U(i);this.formatter.error(r),process.exit(1)}}async resolveReason(){let e=this.options.reason;return!e&&process.stdout.isTTY&&(e=await pe("Enter reason for deprecation:")),e||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Deprecation reason is required.",detail:"Specify --reason <reason>."}),process.exit(1)),e}};var Mn=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);try{if(e){y.debug(`[catalog:unpublish] Unpublishing version '${e}' of catalog entry '${this.key}'...`);let t=await this.client.dataCatalog.unpublishVersion(this.key,e,{token:this.client.token});this.formatter.success(`Successfully unpublished version '${e}' of data catalog entry '${this.key}'.`,t)}else{y.debug(`[catalog:unpublish] Unpublishing catalog entry '${this.key}'...`);let t=await this.client.dataCatalog.unpublish(this.key,{token:this.client.token});this.formatter.success(`Successfully unpublished data catalog entry '${this.key}'.`,t)}}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};var Un=class extends Ke{key;constructor(e,t,i,r=F()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);try{let i=(await this.fetchUsageFiles(e)).data||[];this.formatUsageRows(i)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}async fetchUsageFiles(e){return e?(y.debug(`[catalog:dependent-apis] Fetching usage files for catalog entry '${this.key}' version '${e}'`),await this.client.dataCatalog.getVersionUsageFiles(this.key,e,{token:this.client.token})):(y.debug(`[catalog:dependent-apis] Fetching usage files for catalog entry '${this.key}'`),await this.client.dataCatalog.getUsageFiles(this.key,{token:this.client.token}))}formatUsageRows(e){let t=e.map(i=>({fileId:i.value.key,name:i.value.info?.name||"Unnamed",version:i.meta?.version||"N/A"}));this.formatter.list(t,["fileId","name","version"],{headers:["FILE ID","NAME","VERSION USED"]})}};var zn=class extends Ke{fid;constructor(e,t,i,r=F()){super(t,i,r),this.fid=e}async execute(){let e=this.options.org||N.resolved.org;try{y.debug(`[catalog:status] Checking publication status for file '${this.fid}' in org '${e||"N/A"}'`);let t=await this.client.dataCatalog.checkPublicationStatus(this.fid,e,{token:this.client.token});this.formatter.object(t)}catch(t){let i=U(t);this.formatter.error(i),process.exit(1)}}};function cp(c){let e=c.command("catalog").description("Manage Data Catalog items");e.command("publish").description("Publish a data domain file to the data catalog").option("--file <fid>","File ID of the data domain").option("--name <name>","Name for the catalog entry").option("--description <desc>","Description of the catalog entry").option("--scope <scope>","Publish scope: public, organization, private").option("--catalog-version <ver>","Semantic version (e.g. 1.0.0)").option("--ver <ver>","Semantic version alias (e.g. 1.0.0)").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--lifecycle <lifecycle>","Version lifecycle status (dev, beta, stable)","stable").option("--changelog <changelog>","Changelog description for this version").action(async t=>{let i=new K({format:N.resolved.format});await new jn(t,i).execute()}),e.command("list").description("List published data catalog items or versions of a specific catalog entry").option("--scope <scope>","Filter by scope: all, public, organization, private","all").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--key <key>","Data catalog item key to list all versions of a specific data domain").action(async t=>{let i=new K({format:N.resolved.format});await new Cn(t,i).execute()}),e.command("show <key>").alias("read").description("Show details of a data catalog entry or a specific version").option("--catalog-version <ver>","Semantic version to read").option("--ver <ver>","Semantic version alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Dn(t,i,r).execute()}),e.command("deprecate <key>").description("Mark a data catalog entry or specific version as deprecated").option("--catalog-version <ver>","Version string to deprecate").option("--ver <ver>","Version string alias").option("--reason <reason>","Reason for deprecating this catalog entry or version").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Ln(t,i,r).execute()}),e.command("unpublish <key>").description("Unpublish (mark as private) a data catalog entry or specific version").option("--catalog-version <ver>","Version string to unpublish").option("--ver <ver>","Version string alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Mn(t,i,r).execute()}),e.command("dependent-apis <key>").alias("usage").description("List all APIs referencing a published data catalog item or version").option("--catalog-version <ver>","Filter usage by a specific version").option("--ver <ver>","Filter usage by a specific version alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Un(t,i,r).execute()}),e.command("status <fid>").description("Check the publication status and versions of a data domain file").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new zn(t,i,r).execute()})}var Er=class extends Ae{client;fileManager;constructor(e,t,i=F(),r=new Z){super(e,t),this.client=i,this.fileManager=r}ensureAuth(){return ci(this.client,this.formatter)}async resolveApiId(e,t){let i=this.findProvidedApiId(e);if(i)return i;if(process.stdout.isTTY&&t){let r=await this.selectApiIdInteractively(t);if(r)return r}this.failMissingApiId()}findProvidedApiId(e){return e||this.options.api||this.options.file||this.options.id}async selectApiIdInteractively(e){y.debug("[deployment] API ID not provided; searching API model files for interactive selection...");try{let t=await this.fileManager.search(e,{kind:"api"});if(t.length>0)return await Ce("Select an API model file:",t.map(i=>({name:`${i.info?.name||"Unnamed"} (${i.key})`,value:i.key})));this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"No API models found.",detail:`No API models found in organization '${e}'. Create one first using \`apinow api create\`.`}),process.exit(1)}catch(t){y.debug(`[deployment] Failed to search API files for selection: ${t}`)}}failMissingApiId(){this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"API ID is required.",detail:"Provide an API ID as an argument or specify --api <id> (or --file <fid>, --id <fid>)."}),process.exit(1)}async resolveDeploymentId(e){let t=this.findProvidedDeploymentId(e);if(t)return t;if(process.stdout.isTTY){let i=await this.askDeploymentIdInteractively();if(i)return i}this.failMissingDeploymentId()}findProvidedDeploymentId(e){return e||this.options.id||this.options.deployment}async askDeploymentIdInteractively(){try{return await pe("Enter deployment ID:")||void 0}catch(e){y.debug(`[deployment] Failed to read deployment ID interactively: ${e}`);return}}failMissingDeploymentId(){this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Deployment ID is required.",detail:"Provide a deployment ID as an argument or specify --id <id> (or --deployment <id>)."}),process.exit(1)}};var Vn=class extends Er{api;constructor(e,t,i,r=F(),s=new Z){super(t,i,r,s),this.api=e}async execute(){y.debug("[deployment:list] Listing deployments for an API...");try{this.ensureAuth();let e=this.resolveOrgId("Organization ID is required.","Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."),t=await this.resolveApiId(this.api,e),i=await this.fetchDeployments(e,t);this.formatOutput(i)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}async fetchDeployments(e,t){y.debug(`[deployment:list] Fetching deployments for API '${t}' in org '${e}'...`);let i=this.options.limit?{limit:this.options.limit}:void 0,s=(await this.client.deployments.apis.listDeployments(e,t,i,{token:this.client.token})).data||[];return y.debug(`[deployment:list] Found ${s.length} deployments.`),s}formatOutput(e){let t=e.map(i=>this.toRow(i));this.formatter.list(t,["id","env","version","modelVersion","status","default","baseUri"],{headers:["ID","ENV","VERSION","MODEL VER","STATUS","DEFAULT","BASE URI"]})}toRow(e){return{id:e.key,env:e.env,version:e.version||"-",modelVersion:e.modelVersion,status:e.status,default:e.isDefault?"Yes":"No",baseUri:e.baseUri||"-"}}};var Fn=class extends Er{id;constructor(e,t,i,r=F(),s=new Z){super(t,i,r,s),this.id=e}async execute(){y.debug("[deployment:read] Reading deployment details...");try{this.ensureAuth();let e=this.resolveOrgId("Organization ID is required.","Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."),t=await this.resolveDeploymentId(this.id),i=await this.fetchDeployment(e,t);this.formatter.object(i)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}async fetchDeployment(e,t){y.debug(`[deployment:read] Fetching deployment '${t}' in org '${e}'...`);let i=await this.client.deployments.read(e,t,{token:this.client.token});return y.debug(`[deployment:read] Deployment retrieved successfully: ${i.key}`),i}};function lp(c){let e=c.command("deployment").description("Manage API deployments");e.command("list [api]").description("List deployments for an API").option("--api <apiId>","API model file ID").option("--file <fid>","API model file ID (alias)").option("--id <fid>","API model file ID (alias)").option("--org <oid>","Organization ID (optional, defaults to configured default org)").option("--limit <limit>","Maximum number of results to return",Yi).action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Vn(t,i,r).execute()}),e.command("read [id]").alias("get").description("Read details of a deployment").option("--id <id>","Deployment ID").option("--deployment <id>","Deployment ID alias").option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new K({format:N.resolved.format});await new Fn(t,i,r).execute()})}var qn=class extends Ae{async execute(){y.debug("[runtime:update] Executing runtime user update...");try{let e=F();ci(e,this.formatter);let t=this.resolveOrgId("Organization ID is not specified.","Use --org <oid> or configure a default organization.");y.debug(`[runtime:update] Using organization ID: ${t}`),y.debug("[runtime:update] Parsing properties...");let i=this.parseProperties(this.options.property),r={};for(let[o,a]of Object.entries(i)){let n=["token","password","secret","key"].some(l=>o.toLowerCase().includes(l));r[o]=n?"**********":a}y.debug(`[runtime:update] Parsed properties: ${JSON.stringify(r)}`),y.debug(`[runtime:update] Sending request to update runtime user ID '${this.options.userId}' in environment '${this.options.env}' for api '${this.options.api}'...`);let s=await e.deployments.apis.updateRuntimeUser(t,this.options.api,this.options.userId,i,this.options.env,{token:e.token});y.debug("[runtime:update] Runtime user updated successfully."),this.formatter.success(`User '${this.options.userId}' updated successfully!`,s)}catch(e){let t=U(e);this.formatter.error(t),process.exit(1)}}parseProperties(e){let t={};for(let i of e){let r=i.split("=");if(r.length<2)throw new Error(`Invalid property format: '${i}'. Expected 'name=value'.`);let s=r[0].trim(),o=r.slice(1).join("=").trim();o==="true"?t[s]=!0:o==="false"?t[s]=!1:o==="null"?t[s]=null:/^\d+$/.test(o)?t[s]=parseInt(o,10):/^\d*\.\d+$/.test(o)?t[s]=parseFloat(o):t[s]=o}return t}};function dp(c){c.command("runtime").description("Administrative operations for the API runtime").command("users").description("Administrative operations for users").command("update").description("Update properties of a user directly in the runtime database").requiredOption("--api <api>","API file ID or slug").requiredOption("--user-id <userId>","Primary key of the user record to update").requiredOption("--property <name=value...>","Properties to update in the format name=value (can specify multiple)").option("--org <oid>","Organization ID (defaults to configured org)").option("--env <environment>",'Target environment (e.g. "production", "staging")',"production").action(async i=>{let r=new K({format:N.resolved.format});y.debug("[runtime:update] Starting runtime user update process..."),await new qn(i,r).execute()})}import Je from"node:fs/promises";import st from"node:path";import nh from"node:os";var Kn=class{constructor(e){this.rootProgram=e}rootProgram;extractTree(e=this.rootProgram){let i=(e.options||[]).map(o=>({flags:o.flags,long:o.long,short:o.short,description:o.description||"",choices:o.argChoices})),r=(e.commands||[]).map(o=>this.extractTree(o)),s=typeof e.aliases=="function"?e.aliases():[];return{name:e.name(),aliases:s,description:e.description()||"",options:i,subcommands:r}}generateScript(e){let t=this.extractTree(),i=t.name||"apinow";switch(e){case"zsh":return this.generateZsh(i,t);case"bash":return this.generateBash(i,t);case"fish":return this.generateFish(i,t);default:throw new Error(`Unsupported shell: ${e}`)}}escapeZsh(e){return e.replace(/[':\\]/g,"\\$&").replace(/\n/g," ")}getNodeFlags(e){let t=[];for(let i of e.options)i.long&&!t.includes(i.long)&&t.push(i.long),i.short&&!t.includes(i.short)&&t.push(i.short);return t.includes("--help")||t.push("--help"),t.includes("-h")||t.push("-h"),t}getNodeOptionZshDescriptions(e){let t=[],i=new Set;for(let r of e.options){let s=this.escapeZsh(r.description||r.flags);r.long&&!i.has(r.long)&&(i.add(r.long),t.push(`'${r.long}:${s}'`)),r.short&&!i.has(r.short)&&(i.add(r.short),t.push(`'${r.short}:${s}'`))}return i.has("--help")||t.push("'--help:Display help for command'"),i.has("-h")||t.push("'-h:Display help for command'"),t}renderZshCases(e,t){let i=" ".repeat(t),r=[];for(let s of e){let o=[s.name,...s.aliases].join("|"),a=this.getNodeOptionZshDescriptions(s),n=`local -a ${s.name}_options=(
|
|
1824
1857
|
${i} ${a.join(`
|
|
1825
1858
|
${i} `)}
|
|
1826
1859
|
${i} )
|