@api-now/cli 1.11.0 → 1.12.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.
Files changed (3) hide show
  1. package/README.md +71 -6
  2. package/dist/index.js +36 -36
  3. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- var Dl=Object.create;var va=Object.defineProperty;var Ml=Object.getOwnPropertyDescriptor;var Ll=Object.getOwnPropertyNames;var Ul=Object.getPrototypeOf,zl=Object.prototype.hasOwnProperty;var Vl=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},Ro=(n,e)=>{for(var t in e)va(n,t,{get:e[t],enumerable:!0})},Fl=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Ll(e))!zl.call(n,r)&&r!==t&&va(n,r,{get:()=>e[r],enumerable:!(i=Ml(e,r))||i.enumerable});return n};var Kl=(n,e,t)=>(t=n!=null?Dl(Ul(n)):{},Fl(e||!n||!n.__esModule?va(t,"default",{value:n,enumerable:!0}):t,n));var Kn=Vl((__,Fn)=>{var ho=Object.defineProperty,Jd=Object.getOwnPropertyDescriptor,Bd=Object.getOwnPropertyNames,Gd=Object.prototype.hasOwnProperty,Hd=(n,e)=>{for(var t in e)ho(n,t,{get:e[t],enumerable:!0})},Wd=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Bd(e))!Gd.call(n,r)&&r!==t&&ho(n,r,{get:()=>e[r],enumerable:!(i=Jd(e,r))||i.enumerable});return n},Xd=n=>Wd(ho({},"__esModule",{value:!0}),n),Ln={};Hd(Ln,{AmfModelExpander:()=>Qd,JsonLd:()=>Qt,JsonLdOptions:()=>zn});Fn.exports=Xd(Ln);var Yd=class Un{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 Un}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}},Ds=class{static targetOrLink(n,e){let t=e[n["@id"]];return t!==void 0?t:n}static isLinkObject(n){let e=typeof n=="object",t=!Array.isArray(n),i=n["@id"]!==void 0,r=Object.keys(n).length===1;return e&&t&&i&&r}static isArrayOfLinks(n){return n.every(e=>this.isLinkObject(e))}},Zd=class{static embedNodeLinks(n,e,t){let r=t||(()=>!0);return Object.entries(n).filter(([s,a])=>r(s,a)).forEach(([s,a])=>{typeof a=="object"&&(Ds.isLinkObject(a)?n[s]=Ds.targetOrLink(a,e):Array.isArray(a)&&Ds.isArrayOfLinks(a)&&(n[s]=a.map(o=>Ds.targetOrLink(o,e))))}),n}},Dn=class mo{static expandIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=mo.expandIri(i,t);e[s]=r})}static compactIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=mo.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,a])=>e.startsWith(a));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,a])=>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}},Mn=class{static expandStructure(n){return Object.entries(n).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.expandType(n,t);break;default:this.expandValue(n,e,t);break}}),n}static expandType(n,e){typeof e=="string"?n["@type"]=[e]:n["@type"]=e}static expandValue(n,e,t){switch(typeof t){case"string":case"number":case"boolean":n[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}}):n[e]=[t]}}static compactStructure(n){if(Array.isArray(n)){let[e]=n;return this.compactStructure(e)}else return Object.entries(n).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.compactType(n,t);break;default:this.compactValue(n,e,t);break}}),n}static compactType(n,e){Array.isArray(e)&&e.length===1&&(n["@type"]=e[0])}static compactValue(n,e,t){if(t.length===1){let[i]=t;this.isWrappedScalar(i)?n[e]=i["@value"]:n[e]=i}else t.map(i=>this.isWrappedScalar(i)?i["@value"]:i)}static isWrappedScalar(n){return n["@value"]!==void 0}},Qt=class{static process(n,e){let t=this.getGraph(n),i=this.getContext(n),r=Yd.empty().withNodes(t);t.forEach(a=>{e.embeddedLinks&&Zd.embedNodeLinks(a,r,e.linkEmbeddingFilter),i!==void 0&&(e.expandedIris?Dn.expandIris(a,i):e.compactedIris&&Dn.compactIris(a,i)),e.expandedStructure?Mn.expandStructure(a):e.compactedStructure&&Mn.compactStructure(a)});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(n){return n["@context"]}static getGraph(n){return n["@graph"]}static findNode(n,e){return n.find(t=>t["@id"]===e)}static stringify(n,e=!1){return JSON.stringify(n,null,e?2:0)}},zn=class Vn{expandedIris;expandedStructure;embeddedLinks;compactedIris;compactedStructure;rootNodeId;linkEmbeddingFilter;static apply(){return new Vn}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}},Qd=class{static expand(n){if(this.isInExpandedForm(n))return n;{let e=(r,s)=>!r.endsWith("fixPoint");this.preprocessLegacyRootNodeId(n);let t=this.resolveRootNodeId(n),i=zn.apply().withEmbeddedLinks(e).withCompactedIris().withExpandedStructure().withRootNode(t);return Qt.process(n,i)}}static isInExpandedForm(n){return n["@graph"]===void 0}static preprocessLegacyRootNodeId(n){let e=Qt.getGraph(n);if(e!=null){let t=Qt.findNode(e,"./");t!=null&&(t["@id"]="")}}static resolveRootNodeId(n){let e=Qt.getGraph(n);if(e==null||Qt.findNode(e,"")!=null)return"";let t=Qt.getContext(n);if(t!=null&&t["@base"]!=null){let r=t["@base"];if(Qt.findNode(e,r)!=null)return r}let i=e.find(r=>Object.entries(r).some(([s,a])=>(s==="doc:root"||s==="http://a.ml/vocabularies/document#root")&&a===!0));return i!=null?i["@id"]:""}}});import xp from"update-notifier";import{Command as Pp}from"commander";var Ki={name:"@api-now/cli",description:"API Now! CLI",version:"1.11.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.10.0","@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 wa from"node:os";import $t from"node:path";import ze from"node:fs";var qi="https://api.apinow.app",Sa="apinow-cli",Jl="config.json",_a=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=$t.join(this.configDir,Jl);#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||qi}},activeProfile:"default"};return t&&this.#a(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,a=process.env.APINOW_API_URL||r?.apiUrl||qi,o=r?.org||"";this._resolved={token:s,apiUrl:a,org:o,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.#a(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||qi},i.profiles=r,this.#a(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.#a(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.#a(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.#a(t),this.load()}#t(){if(process.platform==="win32"){let e=process.env.APPDATA||$t.join(wa.homedir(),"AppData","Roaming");if(!e)throw new Error("Could not determine the configuration directory.");return $t.join(e,Sa)}return process.platform==="darwin"?$t.join(wa.homedir(),"Library","Preferences",Sa):$t.join(process.env.XDG_CONFIG_HOME||$t.join(wa.homedir(),".config"),Sa)}#i(){let e=process.cwd();for(;;){let t=$t.join(e,"apinow.json");if(ze.existsSync(t))try{if(ze.statSync(t).isFile())return t}catch{}let i=$t.join(e,".apinowrc.json");if(ze.existsSync(i))try{if(ze.statSync(i).isFile())return i}catch{}let r=$t.dirname(e);if(r===e)break;e=r}return null}#r(){let e=this.#i();if(!e)return null;try{let t=ze.readFileSync(e,"utf8"),i=JSON.parse(t);return this.#e(i,!1)}catch{return null}}#s(){try{if(!ze.existsSync(this.configPath))return{};let e=ze.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.#a(i),this.load()}#a(e){try{ze.existsSync(this.configDir)||ze.mkdirSync(this.configDir,{recursive:!0}),ze.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.#a(t),this.load()}catch(t){console.error(`Failed to clear key ${e} from configuration:`,t)}}reset(){try{ze.existsSync(this.configPath)&&ze.unlinkSync(this.configPath),ze.existsSync(this.configDir)&&ze.readdirSync(this.configDir).length===0&&ze.rmdirSync(this.configDir),this._resolved=null}catch(e){console.error("Failed to reset configuration:",e)}}},A=new _a;import{styleText as Si}from"node:util";import Bl from"node:path";import Gl from"node:os";import Hl from"node:crypto";import lt from"winston";var Wl=Hl.randomBytes(4).toString("hex"),Xl=Date.now(),Sr=Bl.join(Gl.tmpdir(),`apinow-cli-${Xl}-${Wl}.log`),Co=new lt.transports.Console({stderrLevels:Object.keys(lt.config.cli.levels),level:"info",format:lt.format.combine(lt.format.colorize(),lt.format.simple())}),Yl=new lt.transports.File({filename:Sr,level:"debug",format:lt.format.combine(lt.format.timestamp(),lt.format.printf(({timestamp:n,level:e,message:t})=>{let i=typeof t=="string"?t.replace(/\u001b\[\d+m/g,""):t;return`${n} [${e.toUpperCase()}]: ${i}`}))}),b=lt.createLogger({levels:lt.config.cli.levels,level:"debug",transports:[Co,Yl]});function To(n){Co.level=n}var Aa=Ki.version;var ee={green:n=>Si("green",n),red:n=>Si("red",n),yellow:n=>Si("yellow",n),cyan:n=>Si("cyan",n),dim:n=>Si("dim",n),bold:n=>Si("bold",n)};function Zl(n,e,t){if(n.length===0)return"No data available.";let i={},r=t||e;for(let l=0;l<e.length;l++){let c=e[l],p=r[l]||c;i[c]=p.length}for(let l of n)for(let c of e){let p=typeof l[c]=="object"&&l[c]!==null?JSON.stringify(l[c]):String(l[c]??"");p.length>(i[c]||0)&&(i[c]=p.length)}let s=e.map((l,c)=>(r[c]||l).toUpperCase().padEnd(i[l])).join(" "),a=e.map(l=>"-".repeat(i[l])).join(" "),o=n.map(l=>e.map(c=>(typeof l[c]=="object"&&l[c]!==null?JSON.stringify(l[c]):String(l[c]??"")).padEnd(i[c])).join(" "));return[s,a,...o].join(`
3
- `)}var Z=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(ee.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:Aa,logFile:Sr,...e},null,2));else{if(console.error(ee.red(`\u2716 Error [${t}]: ${e.message}`)),e.detail&&console.error(ee.dim(e.detail)),e.errors&&e.errors.length>0){console.error(`
4
- Validation errors:`);for(let i of e.errors)console.error(` - ${ee.yellow(i.field)}: ${i.message}`)}if(console.error(ee.dim(`(cli v${Aa})`)),console.error(ee.dim(`Log file: ${Sr}`)),t==="CLI_ERR_UNKNOWN"){let i="https://github.com/api-now/cli",r=encodeURIComponent(`[BUG] CLI Crash: ${e.message}`),s=encodeURIComponent(`**CLI Version:** ${Aa}
2
+ var Jl=Object.create;var Io=Object.defineProperty;var Bl=Object.getOwnPropertyDescriptor;var Gl=Object.getOwnPropertyNames;var Hl=Object.getPrototypeOf,Wl=Object.prototype.hasOwnProperty;var Xl=(n,e)=>()=>{try{return e||n((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},za=(n,e)=>{for(var t in e)Io(n,t,{get:e[t],enumerable:!0})},Yl=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Gl(e))!Wl.call(n,r)&&r!==t&&Io(n,r,{get:()=>e[r],enumerable:!(i=Bl(e,r))||i.enumerable});return n};var Zl=(n,e,t)=>(t=n!=null?Jl(Hl(n)):{},Yl(e||!n||!n.__esModule?Io(t,"default",{value:n,enumerable:!0}):t,n));var Xn=Xl((RA,Wn)=>{var Sa=Object.defineProperty,ep=Object.getOwnPropertyDescriptor,tp=Object.getOwnPropertyNames,ip=Object.prototype.hasOwnProperty,rp=(n,e)=>{for(var t in e)Sa(n,t,{get:e[t],enumerable:!0})},sp=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of tp(e))!ip.call(n,r)&&r!==t&&Sa(n,r,{get:()=>e[r],enumerable:!(i=ep(e,r))||i.enumerable});return n},op=n=>sp(Sa({},"__esModule",{value:!0}),n),Jn={};rp(Jn,{AmfModelExpander:()=>lp,JsonLd:()=>ti,JsonLdOptions:()=>Gn});Wn.exports=op(Jn);var ap=class Bn{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 Bn}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}},Us=class{static targetOrLink(n,e){let t=e[n["@id"]];return t!==void 0?t:n}static isLinkObject(n){let e=typeof n=="object",t=!Array.isArray(n),i=n["@id"]!==void 0,r=Object.keys(n).length===1;return e&&t&&i&&r}static isArrayOfLinks(n){return n.every(e=>this.isLinkObject(e))}},np=class{static embedNodeLinks(n,e,t){let r=t||(()=>!0);return Object.entries(n).filter(([s,o])=>r(s,o)).forEach(([s,o])=>{typeof o=="object"&&(Us.isLinkObject(o)?n[s]=Us.targetOrLink(o,e):Array.isArray(o)&&Us.isArrayOfLinks(o)&&(n[s]=o.map(a=>Us.targetOrLink(a,e))))}),n}},Kn=class wa{static expandIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=wa.expandIri(i,t);e[s]=r})}static compactIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=wa.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}},qn=class{static expandStructure(n){return Object.entries(n).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.expandType(n,t);break;default:this.expandValue(n,e,t);break}}),n}static expandType(n,e){typeof e=="string"?n["@type"]=[e]:n["@type"]=e}static expandValue(n,e,t){switch(typeof t){case"string":case"number":case"boolean":n[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}}):n[e]=[t]}}static compactStructure(n){if(Array.isArray(n)){let[e]=n;return this.compactStructure(e)}else return Object.entries(n).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.compactType(n,t);break;default:this.compactValue(n,e,t);break}}),n}static compactType(n,e){Array.isArray(e)&&e.length===1&&(n["@type"]=e[0])}static compactValue(n,e,t){if(t.length===1){let[i]=t;this.isWrappedScalar(i)?n[e]=i["@value"]:n[e]=i}else t.map(i=>this.isWrappedScalar(i)?i["@value"]:i)}static isWrappedScalar(n){return n["@value"]!==void 0}},ti=class{static process(n,e){let t=this.getGraph(n),i=this.getContext(n),r=ap.empty().withNodes(t);t.forEach(o=>{e.embeddedLinks&&np.embedNodeLinks(o,r,e.linkEmbeddingFilter),i!==void 0&&(e.expandedIris?Kn.expandIris(o,i):e.compactedIris&&Kn.compactIris(o,i)),e.expandedStructure?qn.expandStructure(o):e.compactedStructure&&qn.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(n){return n["@context"]}static getGraph(n){return n["@graph"]}static findNode(n,e){return n.find(t=>t["@id"]===e)}static stringify(n,e=!1){return JSON.stringify(n,null,e?2:0)}},Gn=class Hn{expandedIris;expandedStructure;embeddedLinks;compactedIris;compactedStructure;rootNodeId;linkEmbeddingFilter;static apply(){return new Hn}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}},lp=class{static expand(n){if(this.isInExpandedForm(n))return n;{let e=(r,s)=>!r.endsWith("fixPoint");this.preprocessLegacyRootNodeId(n);let t=this.resolveRootNodeId(n),i=Gn.apply().withEmbeddedLinks(e).withCompactedIris().withExpandedStructure().withRootNode(t);return ti.process(n,i)}}static isInExpandedForm(n){return n["@graph"]===void 0}static preprocessLegacyRootNodeId(n){let e=ti.getGraph(n);if(e!=null){let t=ti.findNode(e,"./");t!=null&&(t["@id"]="")}}static resolveRootNodeId(n){let e=ti.getGraph(n);if(e==null||ti.findNode(e,"")!=null)return"";let t=ti.getContext(n);if(t!=null&&t["@base"]!=null){let r=t["@base"];if(ti.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 Tp from"update-notifier";import{Command as Dp}from"commander";var Gi={name:"@api-now/cli",description:"API Now! CLI",version:"1.12.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.10.0","@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 No from"node:os";import Rt from"node:path";import Fe from"node:fs";var Hi="https://api.apinow.app",$o="apinow-cli",ec="config.json",Ro=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=Rt.join(this.configDir,ec);#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||Hi}},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||Hi,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||Hi},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||Rt.join(No.homedir(),"AppData","Roaming");if(!e)throw new Error("Could not determine the configuration directory.");return Rt.join(e,$o)}return process.platform==="darwin"?Rt.join(No.homedir(),"Library","Preferences",$o):Rt.join(process.env.XDG_CONFIG_HOME||Rt.join(No.homedir(),".config"),$o)}#i(){let e=process.cwd();for(;;){let t=Rt.join(e,"apinow.json");if(Fe.existsSync(t))try{if(Fe.statSync(t).isFile())return t}catch{}let i=Rt.join(e,".apinowrc.json");if(Fe.existsSync(i))try{if(Fe.statSync(i).isFile())return i}catch{}let r=Rt.dirname(e);if(r===e)break;e=r}return null}#r(){let e=this.#i();if(!e)return null;try{let t=Fe.readFileSync(e,"utf8"),i=JSON.parse(t);return this.#e(i,!1)}catch{return null}}#s(){try{if(!Fe.existsSync(this.configPath))return{};let e=Fe.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{Fe.existsSync(this.configDir)||Fe.mkdirSync(this.configDir,{recursive:!0}),Fe.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{Fe.existsSync(this.configPath)&&Fe.unlinkSync(this.configPath),Fe.existsSync(this.configDir)&&Fe.readdirSync(this.configDir).length===0&&Fe.rmdirSync(this.configDir),this._resolved=null}catch(e){console.error("Failed to reset configuration:",e)}}},_=new Ro;import{styleText as Ei}from"node:util";import tc from"node:path";import ic from"node:os";import rc from"node:crypto";import lt from"winston";var sc=rc.randomBytes(4).toString("hex"),oc=Date.now(),Er=tc.join(ic.tmpdir(),`apinow-cli-${oc}-${sc}.log`),Va=new lt.transports.Console({stderrLevels:Object.keys(lt.config.cli.levels),level:"info",format:lt.format.combine(lt.format.colorize(),lt.format.simple())}),ac=new lt.transports.File({filename:Er,level:"debug",format:lt.format.combine(lt.format.timestamp(),lt.format.printf(({timestamp:n,level:e,message:t})=>{let i=typeof t=="string"?t.replace(/\u001b\[\d+m/g,""):t;return`${n} [${e.toUpperCase()}]: ${i}`}))}),b=lt.createLogger({levels:lt.config.cli.levels,level:"debug",transports:[Va,ac]});function Fa(n){Va.level=n}var jo=Gi.version;var te={green:n=>Ei("green",n),red:n=>Ei("red",n),yellow:n=>Ei("yellow",n),cyan:n=>Ei("cyan",n),dim:n=>Ei("dim",n),bold:n=>Ei("bold",n)};function nc(n,e,t){if(n.length===0)return"No data available.";let i={},r=t||e;for(let l=0;l<e.length;l++){let c=e[l],p=r[l]||c;i[c]=p.length}for(let l of n)for(let c of e){let p=typeof l[c]=="object"&&l[c]!==null?JSON.stringify(l[c]):String(l[c]??"");p.length>(i[c]||0)&&(i[c]=p.length)}let s=e.map((l,c)=>(r[c]||l).toUpperCase().padEnd(i[l])).join(" "),o=e.map(l=>"-".repeat(i[l])).join(" "),a=n.map(l=>e.map(c=>(typeof l[c]=="object"&&l[c]!==null?JSON.stringify(l[c]):String(l[c]??"")).padEnd(i[c])).join(" "));return[s,o,...a].join(`
3
+ `)}var W=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(te.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:jo,logFile:Er,...e},null,2));else{if(console.error(te.red(`\u2716 Error [${t}]: ${e.message}`)),e.detail&&console.error(te.dim(e.detail)),e.errors&&e.errors.length>0){console.error(`
4
+ Validation errors:`);for(let i of e.errors)console.error(` - ${te.yellow(i.field)}: ${i.message}`)}if(console.error(te.dim(`(cli v${jo})`)),console.error(te.dim(`Log file: ${Er}`)),t==="CLI_ERR_UNKNOWN"){let i="https://github.com/api-now/cli",r=encodeURIComponent(`[BUG] CLI Crash: ${e.message}`),s=encodeURIComponent(`**CLI Version:** ${jo}
5
5
  **Error Code:** ${t}
6
6
 
7
7
  **Error Message:**
@@ -11,46 +11,46 @@ ${e.message}
11
11
  \`\`\`
12
12
  ${e.detail||"No stack trace available"}
13
13
  \`\`\`
14
- `),a=`${i}/issues/new?title=${r}&body=${s}`;console.error(`
15
- Please report this bug: ${a}`)}}}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(Zl(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(`${ee.bold(i)}: ${s}`)}}};var Oe=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||A.resolved.org;return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:e,detail:t}),process.exit(1)),i}};var ht=class n extends Oe{static ALLOWED_KEYS=["activeProfile"];configManager;constructor(e,t,i=A){super(e,t),this.configManager=i}isAllowedKey(e){return n.ALLOWED_KEYS.includes(e)}};var _r=class extends ht{key;constructor(e,t,i,r=A){super(t,i,r),this.key=e}execute(){b.debug(`[config:get] Retrieving configuration key '${this.key}'...`);let e=this.configManager.resolved;if(this.key in e){let t=e[this.key];b.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 b.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 Ar=class extends ht{key;value;constructor(e,t,i,r,s=A){super(i,r,s),this.key=e,this.value=t}execute(){b.debug(`[config:set] Setting configuration key '${this.key}' to '${this.key==="token"?"**********":this.value}'...`),this.isAllowedKey(this.key)||(b.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:ht.ALLOWED_KEYS.length>0?`Allowed keys: ${ht.ALLOWED_KEYS.join(", ")}`:"Direct configuration editing is not supported. Use auth and orgs commands."}),process.exit(1)),this.configManager.writeProperty(this.key,this.value),b.debug("[config:set] Configuration property written successfully."),this.formatter.success(`Configuration '${this.key}' set to '${this.value}'.`)}};var Er=class extends ht{constructor(e,t,i=A){super(e,t,i)}execute(){b.debug("[config:reset] Resetting CLI configuration..."),this.configManager.reset(),b.debug("[config:reset] Configuration reset completed successfully."),this.formatter.success("Configuration has been reset successfully.")}};function Do(n){let e=n.command("config").description("Manage CLI configuration settings");e.command("get <key>").description("Get a configuration value").action((t,i)=>{let r=new Z({format:A.resolved.format});new _r(t,i,r).execute()}),e.command("set <key> <value>").description("Set a configuration value").action((t,i,r)=>{let s=new Z({format:A.resolved.format});new Ar(t,i,r,s).execute()}),e.command("reset").description("Reset all configuration settings and remove stored files").action(t=>{let i=new Z({format:A.resolved.format});new Er(t,i).execute()})}import{Argument as cc}from"commander";import Lo from"http";import Uo from"https";function Ji(n){return typeof n!="string"&&(n=String(n)),n.toLowerCase()}function Mo(n){return typeof n!="string"&&(n=String(n)),n}function*Ql(n){if(!n||n.trim()==="")return[];let e=n.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 a=r.indexOf(":");if(a===-1)yield{name:r,value:"",enabled:!s};else{let o=r.substring(0,a),l=r.substring(a+1).trim();yield{name:o,value:l,enabled:!s}}}}var Bi=class n{_map={};constructor(e){if(e instanceof n)e.forEach((t,i)=>this.append(i,t));else if(typeof e=="string")for(let t of Ql(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(a=>this.append(e,a));return}let r=Ji(e);t=t?Mo(t):"";let s=this._map[r];if(s){let a=s.value;s.value=a?`${a},${t}`:t}else s={name:e,value:t,enabled:i};this._map[r]=s}delete(e){delete this._map[Ji(e)]}get(e){if(e=Ji(e),!!this.has(e)&&this._map[e].enabled)return this._map[e].value}has(e){let t=Ji(e);return Object.prototype.hasOwnProperty.call(this._map,t)&&this._map[t].enabled}set(e,t,i=!0){let r=Ji(e);this._map[r]={value:Mo(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 a=this._map[s],o=e.call(t,a.value,a.name,a.enabled);r.push(o)}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],a="";if(!s.enabled)if(e)a+="# ";else continue;a+=`${s.name}: `,s.value&&(a+=s.value),t.push(a)}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 xa(n,e){let t=n.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 Ea(n){if(n==null)return n;if(Array.isArray(n))return n.map(e=>Ea(e));if(typeof n=="object"){let e={};for(let[t,i]of Object.entries(n)){let r=t.toLowerCase();r.includes("token")||r.includes("password")||r.includes("secret")||r.includes("key")?e[t]="**********":e[t]=Ea(i)}return e}return n}function Pa(n){if(!n)return n;try{let e=JSON.parse(n),t=Ea(e);return JSON.stringify(t,null,2)}catch{return n}}var g=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 o=Number(i.status);isNaN(o)||(r.status=o)}i.help!==void 0&&(r.help=String(i.help));let s=i.message!==void 0?String(i.message):t,a=new this(s,r);return i.name!==void 0&&(a.name=String(i.name)),a}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 J="Invalid JSON response.",K="The response has no value.",$="Invalid response status: ",X="Unknown response from the server.";var ce=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 g(e);let i;try{i=JSON.parse(t)}catch{return new g(e)}return!i||typeof i!="object"||!i.message?new g(e):g.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 a="Unable to delete in batch. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${a}${$}${s.status}`,s.body);if(!s.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let o;try{o=JSON.parse(s.body)}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(o.data))throw new g(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return o}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}${$}${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 a="Unable to list revisions for a file. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${a}${$}${s.status}`,s.body);if(!s.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let o;try{o=JSON.parse(s.body)}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(o.data))throw new g(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return o}readResponseBody(e,t){if(![200,202].includes(e.status))throw this.logInvalidResponse(e),this.createApiError(`${t}${$}${e.status}`,e.body);if(!e.body)throw new g(`${t}${K}`,{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 g(`${t}${J}`,{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 g(`${t}${X}`,{code:"E_RESPONSE_UNKNOWN",status:e.status});return i}assertObjectKind(e,t,i){if(t!==i)throw new g(`${e}${X}`,{code:"E_RESPONSE_UNKNOWN",status:500})}};var oi=class extends Error{status;response;constructor(e,t){super(`HTTP Error: ${e}`),this.status=e,this.response=t}},xr=class extends ce{logRequest(e,t,i){if(!this.sdk.logger)return;let r=i?.headers||{},s={};for(let[c,p]of Object.entries(r))s[c]=xa(c,p);(i?.token||this.sdk.token)&&!s.authorization&&!s.Authorization&&(s.Authorization="Bearer **********");let o=i?.body,l=Pa(o);this.sdk.logger.log("debug",`--> HTTP ${e} ${t}`),Object.keys(s).length>0&&this.sdk.logger.log("debug",`Headers: ${JSON.stringify(s,null,2)}`),l&&this.sdk.logger.log("debug",`Body: ${l}`)}logResponse(e,t,i){if(!this.sdk.logger)return;let r=i.headers?i.headers.toJSON():{},s={};for(let[o,l]of Object.entries(r))s[o]=xa(o,l);let a=Pa(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)}`),a&&this.sdk.logger.log("debug",`Body: ${a}`)}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 ec(n,e=1e3){return globalThis.__MOCK_RETRY_DELAY_MS__!==void 0?globalThis.__MOCK_RETRY_DELAY_MS__:n<=0?e:e*Math.pow(2,n-1)}function tc(n){let{status:e}=n;return!(typeof e=="number"&&e>=400&&e<500)}async function Oa(n,e={}){let{retries:t=3,delayMs:i=ec,shouldRetry:r=tc}=e,s;for(let o=0;o<t;o++)try{return await n()}catch(l){if(s=l,!r(s)||o===t-1)throw s;let c=typeof i=="function"?i(o+1):i;c>0&&await new Promise(p=>setTimeout(p,c))}throw s||new Error("Retry operation failed without a specific error.")}var Pr=class extends xr{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 a=new URL(s,e);return this.get(a.toString(),t)}if(t.retry&&r.status>=400)throw new oi(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 Oa(i,r)}catch(r){if(r instanceof oi)return r.response;throw r}return i()}_get(e,t={}){return new Promise((i,r)=>{let{method:s="GET",headers:a={},token:o=this.sdk.token}=t,l={...a};o&&(l.authorization=`Bearer ${o}`);let u=(e.startsWith("https:")?Uo:Lo).request(e,{method:s,headers:l,rejectUnauthorized:!1});u.on("response",m=>{let h={status:m.statusCode,headers:new Bi(m.headers),body:""};m.on("data",f=>{h.body+=f}),m.on("end",()=>i(h))}),u.on("error",m=>r(m)),u.end()})}async post(e,t={}){let i=t.method||"POST",r=async()=>{this.logRequest(i,e,t);let s=await new Promise((a,o)=>{let{headers:l={},token:c=this.sdk.token}=t,p={...l};c&&(p.authorization=`Bearer ${c}`),t.body&&!p["content-type"]&&!p["Content-Type"]&&(p["content-type"]="application/json");let h=(e.startsWith("https:")?Uo:Lo).request(e,{method:i,headers:p});h.on("response",f=>{let v={status:f.statusCode,headers:new Bi(f.headers),body:""};f.on("data",w=>{v.body+=w}),f.on("end",()=>{this.logResponse(i,e,v),a(v)})}),h.on("error",f=>{this.logError(i,e,f),o(f)}),t.body&&h.write(t.body),h.end()});if(t.retry&&s.status>=400)throw new oi(s.status,s);return s};if(t.retry)try{let s=typeof t.retry=="object"?t.retry:{};return await Oa(r,s)}catch(s){if(s instanceof oi)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 x=class n{static folders(e){return`/v1/orgs/${e}/folders`}static files(e){return`/v1/orgs/${e}/files`}static filesSearch(e){return`${n.files(e)}/search`}static filesAccess(e,t){return`${n.file(e,t)}/access`}static filesBatch(e){return`${n.files(e)}/batch/read-meta`}static file(e,t){return`${n.files(e)}/${t}`}static fileMedia(e,t){return`${n.file(e,t)}/media`}static fileUsers(e,t){return`${n.file(e,t)}/users`}static fileRevisions(e,t){return`${n.file(e,t)}/revisions`}static fileBreadcrumbs(e,t){return`${n.file(e,t)}/breadcrumbs`}static fileRename(e,t){return`${n.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`${n.trash(e)}/${t}`}static trashRestore(e,t){return`${n.trashItem(e,t)}/restore`}static trashEmpty(e){return`${n.trash(e)}/empty`}static trashBatchRestore(e){return`${n.trash(e)}/restore`}static trashBatchDelete(e){return`${n.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`${n.usersMe()}/tokens`}static usersMeToken(e){return`${n.usersMeTokens()}/${e}`}static dataCatalog(){return"/v1/datacatalog"}static dataCatalogStatus(e){return`${n.dataCatalog()}/status/${e}`}static dataCatalogEntry(e){return`${n.dataCatalog()}/${e}`}static dataCatalogEntryVersions(e){return`${n.dataCatalogEntry(e)}/versions`}static dataCatalogDependencies(){return`${n.dataCatalog()}/dependencies`}static dataCatalogUpdates(){return`${n.dataCatalog()}/updates`}static dataCatalogVersion(e,t){return`${n.dataCatalogEntry(e)}/${t}`}static dataCatalogDeprecate(e){return`${n.dataCatalogEntry(e)}/deprecate`}static dataCatalogUnpublish(e){return`${n.dataCatalogEntry(e)}/unpublish`}static dataCatalogVersionDeprecate(e,t){return`${n.dataCatalogVersion(e,t)}/deprecate`}static dataCatalogVersionUnpublish(e,t){return`${n.dataCatalogVersion(e,t)}/unpublish`}static dataCatalogUsage(e){return`${n.dataCatalogEntry(e)}/apis`}static dataCatalogVersionUsage(e,t){return`${n.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`${n.aiSessions(e,t)}/${i}`}static aiMessages(e,t){return`${this.organization(e)}/ai/messages/${t}`}static aiMessage(e,t,i){return`${n.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`${n.deployments(e)}/apis`}static deployment(e,t){return`${n.deployments(e)}/${t}`}static deploymentsForApi(e,t){return`${n.deploymentsApis(e)}/${t}`}static deploymentsApisByEnvLatest(e,t){return`${n.deploymentsApis(e)}/${t}/environments/latest`}static rollback(e,t){return`${n.deployment(e,t)}/rollback`}static deploymentsApiRuntimeUsersUpdate(e,t){return`${n.deploymentsApis(e)}/${t}/runtime/users/update`}static job(e,t){return`/v1/orgs/${e}/jobs/${t}`}};var Or=class extends ce{oauthRedirect(e,t={}){let{redirect:i,token:r,type:s="redirect"}=t,a=new URL(this.sdk.baseUri);if(!["google","github","linkedin"].includes(e))throw new Error(`Invalid provider: ${e}`);let o=new URL(`/auth/${e}/redirect`,a);return i&&o.searchParams.set("r",i),r&&o.searchParams.set("token",r),s==="redirect"?(window.location.href=o.toString(),null):window.open(o.toString(),"_blank")}async logout(e={}){let{token:t,retry:i=!0}=e,r=this.sdk.getUrl(x.authLogout()),s=await this.sdk.http.post(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let a="Unable to log out. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${a}${$}${s.status}`,s.body)}};import{customAlphabet as ic}from"nanoid";var Q=ic("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var gt="Core#Permission",ft=["reader","commenter","writer","owner"],Vt=class n{kind=gt;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:Q(),kind:gt,itemId:t,granteeId:i,role:e,type:"user",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new n(s)}static fromGroupRole(e,t,i,r){let s={key:Q(),kind:gt,itemId:t,granteeId:i,role:e,type:"group",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new n(s)}static fromOrganizationRole(e,t,i,r){let s={key:Q(),kind:gt,itemId:t,granteeId:i,role:e,type:"organization",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new n(s)}static fromValues(e){return new n({...e,key:Q(),kind:gt})}constructor(e){let t;typeof e=="string"?t=JSON.parse(e):typeof e=="object"?t=e:t={kind:gt,key:Q(),granteeId:"",itemId:"",role:"reader",type:"user",addingUser:"",depth:0,sourceRule:"direct_user_grant"},this.new(t)}new(e){if(!n.isPermission(e))throw new Error("Not a permission.");let{key:t=Q(),granteeId:i,role:r,type:s,displayName:a,expirationTime:o,addingUser:l,itemId:c,depth:p,sourceRule:u}=e;this.kind=gt,this.key=t,this.granteeId=i,this.itemId=c,this.role=r,this.type=s,this.addingUser=l,this.depth=p||0,this.sourceRule=u||"direct_user_grant",a?this.displayName=a:this.displayName=void 0,typeof o=="number"?this.expirationTime=o:this.expirationTime=void 0}static isPermission(e){return!(!e||e.kind!==gt)}static hasRole(e,t){if(!t)return!1;let i=ft.indexOf(t),r=ft.indexOf(e);return i>=r}static isHigherRole(e,t){let i=ft.indexOf(e),r=ft.indexOf(t);return i>r}hasRole(e){return n.hasRole(e,this.role)}static hasRoleIn(e,t){if(!t||!t.length)return!1;let i=[...t].sort((l,c)=>l.depth-c.depth),r=i[0].depth,s=i.filter(l=>l.depth===r),a,o=s.filter(l=>l.type==="user");if(o.length)a=o.sort((l,c)=>ft.indexOf(c.role)-ft.indexOf(l.role))[0];else{let l=s.filter(c=>c.type==="group");if(l.length)a=l.sort((c,p)=>ft.indexOf(p.role)-ft.indexOf(c.role))[0];else{let c=s.filter(p=>p.type==="organization");c.length&&(a=c.sort((p,u)=>ft.indexOf(u.role)-ft.indexOf(p.role))[0])}}return a?n.hasRole(e,a.role):!1}toJSON(){let e={kind:gt,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 Ft="Core#Thing",We="Core#Folder";var Gi="Core#User",Kt="Data#DomainFile",Re="Data#Domain",Ie="Domain#Namespace",Ee="Domain#Model",j="Domain#Entity",de="Domain#Association",he="Domain#Property",ct="Core#DataCatalog",It="Core#DataCatalogVersion";var _i="Core#Deployment",Fe="Core#ApiModel",ni="Core#ExposedEntity",Na="Core#ApiFile";var Hi="Core#AiSession",$a="Core#AiMessage",Ia="Core#Job";var pe=class n{kind=Ft;name;displayName;description;version;static fromName(e){return new n({name:e,kind:Ft})}static fromJSON(e={},t={}){let i=new n,{name:r,displayName:s,description:a,version:o}=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),a?i.description=a:typeof t.description=="string"&&(i.description=t.description),o?i.version=o: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:Ft},this.new(t)}new(e){if(!n.isThing(e))throw new Error("Not a thing.");let{description:t,name:i,version:r,displayName:s}=e;this.kind=Ft,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!==Ft):!1}static isThing(e){return!!(e&&e.kind===Ft)}toJSON(){let e={kind:Ft};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 ja=Symbol("parents"),Nr=Symbol("deleted"),$r=Symbol("deletedInfo"),Ir=Symbol("lastModified"),Ra=Symbol("capabilities"),Ca=Symbol("permissions"),Ta=Symbol("permissionIds"),Da=Symbol("shortcutTarget"),Wi=class{kind="";key="";info=pe.fromName("");iconColor;get isShortcut(){return!!this.shortcutTarget}[Da];get shortcutTarget(){return this[Da]}set shortcutTarget(e){this[Da]=e}static createSchema(e={}){let{key:t=Q(),kind:i,iconColor:r,shortcutTarget:s}=e,a={key:t,kind:i||"",info:pe.fromJSON(e.info,{name:"Unnamed file"}).toJSON()};return r&&(a.iconColor=r),s&&(a.isShortcut=!0,a.shortcutTarget=s),a}constructor(e){this.kind=e.kind,this.key=e.key,this.info=new pe(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=Vt.hasRole("commenter",t),r=Vt.hasRole("owner",t),s=Vt.hasRole("reader",t),a=Vt.hasRole("writer",t),o=e.kind===We;return{canReadMedia:!o&&s,canListChildren:o&&s,canComment:!o&&i,canEditMedia:!o&&a,canEditMeta:a,canReadRevisions:a,canAddChildren:o&&a,canDelete:r,canTrash:r,canUntrash:r,canShare:a,canMove:a}}createFileCapabilities(e){return jt.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!==Gi)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!==Gi)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}},jt=class n extends Wi{[ja]=[];get parents(){return this[ja]}[Ta]=[];get permissionIds(){return this[Ta]}[Nr];get deleted(){return this[Nr]||!1}[$r];get deletedInfo(){return this[$r]}[Ir]={user:"",time:0,byMe:!1};get lastModified(){return this[Ir]}labels;[Ra];get capabilities(){return this[Ra]}[Ca]=[];get permissions(){return this[Ca]}static createSchema(e={}){let t=Wi.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=n.createSchema(e);super(t),this[ja]=[...t.parents],this[Ta]=[...t.permissionIds],this[Ca]=t.permissions.map(i=>({...i})),this[Ra]=t.capabilities?{...t.capabilities}:void 0,this[Ir]=Object.freeze({...t.lastModified}),typeof t.deleted=="boolean"&&(this[Nr]=t.deleted,this[$r]=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 n({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!==Gi)throw new Error('Invalid value for the user when setting "lastModified".');this[Ir]={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!==Gi)throw new Error('Invalid value for the user when setting "deletedInfo".');this[Nr]=!0,this[$r]={byMe:!1,time:Date.now(),user:e.key,name:e.name}}isFile(){return this.kind!==We}isFolder(){return this.kind===We}};var Xi=class extends jt{kind=We;static fromName(e){return super.fromName(e,We)}constructor(e){let t=jt.createSchema(e);t.kind=We,super(t)}static isFolder(e){return!(!e||e.kind!==We)}toJSON(){return{...super.toJSON(),kind:We}}};var jr=class extends ce{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a={...t},o=this.sdk.getUrl(x.files(e));this.sdk.appendListOptions(o,a);let l=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(l);let c="Unable to list files. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async search(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.filesSearch(e)),{searchParams:o}=a;if(t.cursor&&o.set("cursor",t.cursor),typeof t.limit=="number"&&o.set("limit",String(t.limit)),t.parent&&o.set("parent",t.parent),t.kind)for(let c of t.kind)o.append("kind",c);if(t.query)for(let c of t.query)o.append("query",c);let l=await this.sdk.http.get(a.toString(),{token:r,retry:s});return this.processListResponse(l,"Unable to search files. ")}async create(e,t,i,r={},s={}){let a=await this.createMeta(e,i,r,s);return await this.createMedia(t,i,a.key,r,s),a}async createMeta(e,t,i={},r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.files(t));i.parent&&o.searchParams.set("parent",i.parent);let l=JSON.stringify(e),c=await this.sdk.http.post(o.toString(),{token:s,body:l,retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(c);let p="Unable to create a file. ";if(c.status!==201)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}async createMedia(e,t,i,r={},s={}){let{token:a=this.sdk.token,retry:o=!0}=s,l=x.fileMedia(t,i),c=this.sdk.getUrl(l),p=r.mime||"application/json",u;p.includes("json")?u=JSON.stringify(e):u=String(e);let m=await this.sdk.http.put(c.toString(),{token:a,body:u,retry:o,headers:{"content-type":p}});this.inspectCommonStatusCodes(m);let h="Unable to create a file. ";if(m.status!==200)throw this.logInvalidResponse(m),this.createApiError(`${h}${$}${m.status}`,m.body)}async createFolder(e,t,i={},r={}){let s=Xi.fromName(e),{token:a=this.sdk.token,retry:o=!0}=r,l=this.sdk.getUrl(x.files(t));i.parent&&l.searchParams.set("parent",i.parent);let c=JSON.stringify(s),p=await this.sdk.http.post(l.toString(),{token:a,body:c,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(p);let u="Unable to create a file. ";if(p.status!==201)throw this.logInvalidResponse(p),this.createApiError(`${u}${$}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}if(!m.key)throw new g(`${u}${X}`,{code:"E_RESPONSE_UNKNOWN",status:p.status});return m}async read(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.file(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to read a file. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!c.kind)throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}async readMedia(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.fileMedia(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to read a file media. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!c||typeof c!="object"||!("data"in c)||!("meta"in c))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});let{data:p,meta:u}=c;if(!u||typeof u!="object"||typeof u.version!="number"||typeof u.updated!="number"||isNaN(u.version)||isNaN(u.updated))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return{media:p,meta:u}}async readBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.filesBatch(e)),o=JSON.stringify({ids:t}),l=await this.sdk.http.post(a.toString(),{token:r,body:o,retry:s});this.inspectCommonStatusCodes(l);let c="Unable to read files in bulk. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async patch(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=x.file(e,t),l=this.sdk.getUrl(o),c=JSON.stringify(i),p=await this.sdk.http.patch(l.toString(),{token:s,body:c,retry:a});this.inspectCommonStatusCodes(p);let u="Unable to patch a file. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${u}${$}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}if(!m.kind)throw new g(`${u}${X}`,{code:"E_RESPONSE_UNKNOWN",status:p.status});return m}async patchMedia(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=x.fileMedia(e,t),l=this.sdk.getUrl(o),c=JSON.stringify(i),p=await this.sdk.http.patch(l.toString(),{token:s,body:c,retry:a});this.inspectCommonStatusCodes(p);let u="Unable to patch a file contents. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${u}${$}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}return m}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.file(e,t)),o=await this.sdk.http.delete(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to trash a file. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body)}async deleteBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.files(e)),o=await this.sdk.http.delete(a.toString(),{token:r,body:JSON.stringify({ids:t}),retry:s});this.inspectCommonStatusCodes(o);let l="Unable to trash files. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body)}async patchUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.filesAccess(e,t)),l=JSON.stringify(i),c=await this.sdk.http.patch(o.toString(),{token:s,body:l,retry:a});this.inspectCommonStatusCodes(c);let p="Unable to patch the file. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}async addUser(e,t,i,r,s,a){let o={op:"add",type:"user",value:r,id:i};typeof s=="number"&&(o.expirationTime=s);let l={patch:[o],id:Q()};return this.patchUsers(e,t,l,a)}async removeUser(e,t,i,r){let a={patch:[{op:"remove",type:"user",id:i}],id:Q()};return this.patchUsers(e,t,a,r)}async listUsers(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.fileUsers(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to list users in the file. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(c.data))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}async breadcrumbs(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.fileBreadcrumbs(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to read breadcrumbs. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(c.data))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}async rename(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.fileRename(e,t)),l=await this.sdk.http.put(o.toString(),{token:s,body:JSON.stringify({name:i}),retry:a});this.inspectCommonStatusCodes(l);let c="Unable to rename file. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}return p}};var Rr=class extends ce{async me(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(x.usersMe()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let a="Unable to read a user. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${a}${$}${s.status}`,s.body);if(!s.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let o;try{o=JSON.parse(s.body).data}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!o.key)throw new g(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return o}async listTokens(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(x.usersMeTokens()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let a="Unable to list tokens. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${a}${$}${s.status}`,s.body);if(!s.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let o;try{o=JSON.parse(s.body).data}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:s.status})}return o}async createToken(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.usersMeTokens()),a=JSON.stringify(e),o=await this.sdk.http.post(s.toString(),{token:i,body:a,retry:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(o);let l="Unable to create a token. ";if(o.status!==200&&o.status!==201)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}return c}async deleteToken(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.usersMeToken(e)),a=await this.sdk.http.delete(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to delete a token. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body)}};var Cr=class extends ce{async list(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.shared(e));this.sdk.appendListOptions(a,t);let o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to list shared files. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(c.data))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}};var Tr=class extends ce{async list(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.fileRevisions(e,t));this.sdk.appendListOptions(o,i);let l=await this.sdk.http.get(o.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(l);let c="Unable to list revisions for a file. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}};var Dr=class extends ce{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.trash(e));this.sdk.appendListOptions(a,t);let o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to list trash. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(c.data))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}async delete(e,t,i={}){let r=x.trashBatchDelete(e),s=this.sdk.getUrl(r),{token:a=this.sdk.token,retry:o=!0}=i,l=await this.sdk.http.delete(s.toString(),{token:a,body:JSON.stringify({ids:t}),retry:o});this.inspectCommonStatusCodes(l);let c="Unable to delete trash. ";if(l.status!==204)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body)}async restore(e,t,i={}){let r=this.sdk.getUrl(x.trashBatchRestore(e)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.post(r.toString(),{token:s,body:JSON.stringify({ids:t}),retry:a});this.inspectCommonStatusCodes(o);let l="Unable to restore from trash. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body)}async empty(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.trashEmpty(e)),a=await this.sdk.http.delete(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to empty trash. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body)}};var Mr=class extends ce{async list(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(x.organizations()),s=await this.sdk.http.get(r.toString(),{token:t,retry:i});this.inspectCommonStatusCodes(s);let a="Unable to list your organizations. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${a}${$}${s.status}`,s.body);if(!s.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let o;try{o=JSON.parse(s.body)}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(o.data))throw new g(`${a}${X}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return o}async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizations()),o={name:e,slug:t},l=await this.sdk.http.post(a.toString(),{body:JSON.stringify(o),token:r,headers:{"Content-Type":"application/json"},retry:s});this.inspectCommonStatusCodes(l);let c="Unable to create an organization. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.kind)throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}invitations={list:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.invitations(e)),a=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to list organization invitations. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body);if(!a.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body)}catch{throw new g(`${o}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(l.data))throw new g(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},create:async(e,t,i,r,s={})=>{let{token:a=this.sdk.token,retry:o=!0}=s,l=this.sdk.getUrl(x.invitations(e)),c={email:t,name:r,grant_type:i},p=await this.sdk.http.post(l.toString(),{body:JSON.stringify(c),token:a,headers:{"Content-Type":"application/json"},retry:o});this.inspectCommonStatusCodes(p);let u="Unable to create an invitation. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${u}${$}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}if(!m.kind)throw new g(`${u}${X}`,{code:"E_RESPONSE_UNKNOWN",status:p.status});return m},findByToken:async(e,t={})=>{let i=this.sdk.getUrl(x.findInvitation());i.searchParams.append("token",e);let{retry:r=!0,token:s}=t,a=await this.sdk.http.get(i.toString(),{token:s,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to find invitation by token. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body);if(!a.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let l;try{l=JSON.parse(a.body).data}catch{throw new g(`${o}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!l.kind)throw new g(`${o}${X}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return l},decline:async(e,t,i={})=>{let r=this.sdk.getUrl(x.declineInvitation(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.post(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to decline invitation. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!c.kind)throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c},delete:async(e,t,i={})=>{let r=this.sdk.getUrl(x.invitation(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.delete(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to delete invitation. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!c.kind)throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c},patch:async(e,t,i,r={})=>{let s=this.sdk.getUrl(x.invitation(e,t)),{token:a=this.sdk.token,retry:o=!0}=r,l=await this.sdk.http.patch(s.toString(),{body:JSON.stringify(i),token:a,headers:{"Content-Type":"application/json"},retry:o});this.inspectCommonStatusCodes(l);let c="Unable to update invitation. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.kind)throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},resend:async(e,t,i={})=>{let r=this.sdk.getUrl(x.resendInvitation(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.put(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to resend invitation. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!c.kind)throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}};users={list:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizationUsers(e));this.sdk.appendListOptions(a,t);let o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to list projects. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(c.data))throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c},read:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizationUser(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to read the user info. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}return c},readBatch:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizationUserBatch(e)),o={ids:t},l=await this.sdk.http.post(a.toString(),{body:JSON.stringify(o),token:r,retry:s});this.inspectCommonStatusCodes(l);let c="Unable to read the user batch info. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},activate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizationUserActivate(e,t)),o=await this.sdk.http.post(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to activate the user. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}return c},deactivate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizationUserDeactivate(e,t)),o=await this.sdk.http.post(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to deactivate the user. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}return c},delete:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.organizationUser(e,t)),o=await this.sdk.http.delete(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to delete the user. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body)}};slugs={generate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.orgSlugGenerate()).toString(),a={name:e},o=await this.sdk.http.post(s,{body:JSON.stringify(a),token:i,retry:r});this.inspectCommonStatusCodes(o);let l="Unable to generate the slug. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!c.slug)throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c.slug},validate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.orgSlugValidate()).toString(),a={slug:e},o=await this.sdk.http.post(s,{body:JSON.stringify(a),token:i,retry:r});this.inspectCommonStatusCodes(o);let l="Unable to validate the slug. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);if(!o.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(typeof c.valid!="boolean")throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c}}};var Lr=class extends ce{async list(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s={...e},a=this.sdk.getUrl(x.dataCatalog());this.sdk.appendListOptions(a,s),s.scope&&a.searchParams.set("scope",s.scope);let o=await this.sdk.http.get(a.toString(),{token:i,retry:r});return this.processListResponse(o,"Unable to list data domains. ")}async listVersions(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.dataCatalogEntryVersions(e)),a=await this.sdk.http.get(s.toString(),{token:i,retry:r});return this.processListResponse(a,"Unable to list data domain versions. ")}async publish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.dataCatalog()),a=JSON.stringify(e),o=await this.sdk.http.post(s.toString(),{token:i,body:a,retry:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(o);let l="Unable to publish data domain. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,ct,c.kind),c}async read(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.dataCatalogEntry(e)),a=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to read data domain. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body);let l=this.readResponseJSON(a,o).data;return this.assertObjectKind(o,ct,l.kind),l}async deprecate(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.dataCatalogDeprecate(e)),o=JSON.stringify({reason:t}),l=await this.sdk.http.put(a.toString(),{token:r,body:o,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let c="Unable to deprecate data domain. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);let p=this.readResponseJSON(l,c).data;return this.assertObjectKind(c,ct,p.kind),p}async unpublish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.dataCatalogUnpublish(e)),a=await this.sdk.http.put(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to unpublish data domain. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body);let l=this.readResponseJSON(a,o).data;return this.assertObjectKind(o,ct,l.kind),l}async publishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.dataCatalogEntryVersions(e)),o=JSON.stringify(t),l=await this.sdk.http.post(a.toString(),{token:r,body:o,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let c="Unable to publish data domain version. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);let p=this.readResponseJSON(l,c).data;return this.assertObjectKind(c,It,p.kind),p}async readVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.dataCatalogVersion(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to read data domain version. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,It,c.kind),c}async listDependencies(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.dataCatalogDependencies()),a=JSON.stringify({items:e}),o=await this.sdk.http.post(s.toString(),{token:i,body:a,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(o,"Unable to list data domain dependencies. ")}async checkUpdates(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=e.map(c=>({fid:c.key,version:c.version})),a=this.sdk.getUrl(x.dataCatalogUpdates()),o=JSON.stringify({dependencies:s}),l=await this.sdk.http.post(a.toString(),{token:i,body:o,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(l,"Unable to check for data domain updates. ")}async deprecateVersion(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.dataCatalogVersionDeprecate(e,t)),l=JSON.stringify({reason:i}),c=await this.sdk.http.put(o.toString(),{token:s,body:l,retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(c);let p="Unable to deprecate data domain version. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);let u=this.readResponseJSON(c,p).data;return this.assertObjectKind(p,It,u.kind),u}async unpublishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.dataCatalogVersionUnpublish(e,t)),o=await this.sdk.http.put(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to unpublish data domain version. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,It,c.kind),c}async checkPublicationStatus(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.dataCatalogStatus(e));t&&a.searchParams.set("oid",t);let o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to check data domain publication status. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,ct,c.kind),c}async getUsageFiles(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.dataCatalogUsage(e)),a=await this.sdk.http.get(s.toString(),{token:i,retry:r});this.inspectCommonStatusCodes(a);let o="Unable to get data catalog usage files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${o}${$}${a.status}`,a.body);return this.processListResponse(a,o)}async getVersionUsageFiles(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.dataCatalogVersionUsage(e,t)),o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to get data catalog version usage files. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);return this.processListResponse(o,l)}};var Ur=class extends ce{async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.groups(e)),o=JSON.stringify(t),l=await this.sdk.http.post(a.toString(),{token:r,body:o,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(l);let c="Unable to create a group. ";if(l.status!==201)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.groups(e));this.sdk.appendListOptions(a,t);let o=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to create a group. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(l+$+o.status,o.body);if(!o.body)throw new g(l+K,{code:"E_RESPONSE_NO_VALUE",status:o.status});let c;try{c=JSON.parse(o.body)}catch{throw new g(l+J,{code:"E_INVALID_JSON",status:o.status})}return c}async update(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.group(e,t.key)),o=JSON.stringify(t),l=await this.sdk.http.put(a.toString(),{token:r,body:o,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(l);let c="Unable to update a group. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.group(e,t)),o=await this.sdk.http.delete(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(o);let l="Unable to delete a group. ";if(o.status!==204)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body)}async addUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.groupUsers(e,t)),l=JSON.stringify({ids:i}),c=await this.sdk.http.post(o.toString(),{token:s,body:l,headers:{"content-type":"application/json"},retry:a});this.inspectCommonStatusCodes(c);let p="Unable to add users to a group. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}async removeUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.groupUsers(e,t)),l=JSON.stringify({ids:i}),c=await this.sdk.http.delete(o.toString(),{token:s,body:l,headers:{"content-type":"application/json"},retry:a});this.inspectCommonStatusCodes(c);let p="Unable to remove users from a group. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}};var zr=class extends ce{async*modifyDomain(e,t,i,r,s={}){let{token:a=this.sdk.token,signal:o}=s,l=this.sdk.getUrl(x.aiModifyDomain(e,t)),c=JSON.stringify({goal:i,sid:r}),p={method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${a}`},redirect:"follow",credentials:"include",body:c,signal:o},u=await fetch(l,p);if(!u.ok){let v=await u.text();throw new g(`Failed to modify domain: ${u.status} ${v}`)}let m=u.body?.getReader();if(!m)throw new g("Failed to get reader from response");let h=new TextDecoder,f="";for(;;){let{done:v,value:w}=await m.read();if(v)return;f+=h.decode(w,{stream:!0});let E;for(;(E=f.indexOf(`
14
+ `),o=`${i}/issues/new?title=${r}&body=${s}`;console.error(`
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(nc(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(`${te.bold(i)}: ${s}`)}}};var Se=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||_.resolved.org;return i||(this.formatter.error({code:"CLI_ERR_MISSING_REQUIRED",message:e,detail:t}),process.exit(1)),i}};var ft=class n extends Se{static ALLOWED_KEYS=["activeProfile"];configManager;constructor(e,t,i=_){super(e,t),this.configManager=i}isAllowedKey(e){return n.ALLOWED_KEYS.includes(e)}};var xr=class extends ft{key;constructor(e,t,i,r=_){super(t,i,r),this.key=e}execute(){b.debug(`[config:get] Retrieving configuration key '${this.key}'...`);let e=this.configManager.resolved;if(this.key in e){let t=e[this.key];b.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 b.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 Or=class extends ft{key;value;constructor(e,t,i,r,s=_){super(i,r,s),this.key=e,this.value=t}execute(){b.debug(`[config:set] Setting configuration key '${this.key}' to '${this.key==="token"?"**********":this.value}'...`),this.isAllowedKey(this.key)||(b.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:ft.ALLOWED_KEYS.length>0?`Allowed keys: ${ft.ALLOWED_KEYS.join(", ")}`:"Direct configuration editing is not supported. Use auth and orgs commands."}),process.exit(1)),this.configManager.writeProperty(this.key,this.value),b.debug("[config:set] Configuration property written successfully."),this.formatter.success(`Configuration '${this.key}' set to '${this.value}'.`)}};var Pr=class extends ft{constructor(e,t,i=_){super(e,t,i)}execute(){b.debug("[config:reset] Resetting CLI configuration..."),this.configManager.reset(),b.debug("[config:reset] Configuration reset completed successfully."),this.formatter.success("Configuration has been reset successfully.")}};function Ka(n){let e=n.command("config").description("Manage CLI configuration settings");e.command("get <key>").description("Get a configuration value").action((t,i)=>{let r=new W({format:_.resolved.format});new xr(t,i,r).execute()}),e.command("set <key> <value>").description("Set a configuration value").action((t,i,r)=>{let s=new W({format:_.resolved.format});new Or(t,i,r,s).execute()}),e.command("reset").description("Reset all configuration settings and remove stored files").action(t=>{let i=new W({format:_.resolved.format});new Pr(t,i).execute()})}import{Argument as bc}from"commander";import Ja from"http";import Ba from"https";function Wi(n){return typeof n!="string"&&(n=String(n)),n.toLowerCase()}function qa(n){return typeof n!="string"&&(n=String(n)),n}function*lc(n){if(!n||n.trim()==="")return[];let e=n.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),l=r.substring(o+1).trim();yield{name:a,value:l,enabled:!s}}}}var Xi=class n{_map={};constructor(e){if(e instanceof n)e.forEach((t,i)=>this.append(i,t));else if(typeof e=="string")for(let t of lc(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=Wi(e);t=t?qa(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[Wi(e)]}get(e){if(e=Wi(e),!!this.has(e)&&this._map[e].enabled)return this._map[e].value}has(e){let t=Wi(e);return Object.prototype.hasOwnProperty.call(this._map,t)&&this._map[t].enabled}set(e,t,i=!0){let r=Wi(e);this._map[r]={value:qa(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 To(n,e){let t=n.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 Co(n){if(n==null)return n;if(Array.isArray(n))return n.map(e=>Co(e));if(typeof n=="object"){let e={};for(let[t,i]of Object.entries(n)){let r=t.toLowerCase();r.includes("token")||r.includes("password")||r.includes("secret")||r.includes("key")?e[t]="**********":e[t]=Co(i)}return e}return n}function Do(n){if(!n)return n;try{let e=JSON.parse(n),t=Co(e);return JSON.stringify(t,null,2)}catch{return n}}var g=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 J="Invalid JSON response.",K="The response has no value.",N="Invalid response status: ",Y="Unknown response from the server.";var ce=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 g(e);let i;try{i=JSON.parse(t)}catch{return new g(e)}return!i||typeof i!="object"||!i.message?new g(e):g.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}${N}${s.status}`,s.body);if(!s.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new g(`${o}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new g(`${o}${Y}`,{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}${N}${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}${N}${s.status}`,s.body);if(!s.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new g(`${o}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new g(`${o}${Y}`,{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}${N}${e.status}`,e.body);if(!e.body)throw new g(`${t}${K}`,{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 g(`${t}${J}`,{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 g(`${t}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:e.status});return i}assertObjectKind(e,t,i){if(t!==i)throw new g(`${e}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:500})}};var li=class extends Error{status;response;constructor(e,t){super(`HTTP Error: ${e}`),this.status=e,this.response=t}},Ir=class extends ce{logRequest(e,t,i){if(!this.sdk.logger)return;let r=i?.headers||{},s={};for(let[c,p]of Object.entries(r))s[c]=To(c,p);(i?.token||this.sdk.token)&&!s.authorization&&!s.Authorization&&(s.Authorization="Bearer **********");let a=i?.body,l=Do(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)}`),l&&this.sdk.logger.log("debug",`Body: ${l}`)}logResponse(e,t,i){if(!this.sdk.logger)return;let r=i.headers?i.headers.toJSON():{},s={};for(let[a,l]of Object.entries(r))s[a]=To(a,l);let o=Do(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 cc(n,e=1e3){return globalThis.__MOCK_RETRY_DELAY_MS__!==void 0?globalThis.__MOCK_RETRY_DELAY_MS__:n<=0?e:e*Math.pow(2,n-1)}function dc(n){let{status:e}=n;return!(typeof e=="number"&&e>=400&&e<500)}async function Mo(n,e={}){let{retries:t=3,delayMs:i=cc,shouldRetry:r=dc}=e,s;for(let a=0;a<t;a++)try{return await n()}catch(l){if(s=l,!r(s)||a===t-1)throw s;let c=typeof i=="function"?i(a+1):i;c>0&&await new Promise(p=>setTimeout(p,c))}throw s||new Error("Retry operation failed without a specific error.")}var Nr=class extends Ir{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 li(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 Mo(i,r)}catch(r){if(r instanceof li)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,l={...o};a&&(l.authorization=`Bearer ${a}`);let u=(e.startsWith("https:")?Ba:Ja).request(e,{method:s,headers:l,rejectUnauthorized:!1});u.on("response",m=>{let h={status:m.statusCode,headers:new Xi(m.headers),body:""};m.on("data",f=>{h.body+=f}),m.on("end",()=>i(h))}),u.on("error",m=>r(m)),u.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:l={},token:c=this.sdk.token}=t,p={...l};c&&(p.authorization=`Bearer ${c}`),t.body&&!p["content-type"]&&!p["Content-Type"]&&(p["content-type"]="application/json");let h=(e.startsWith("https:")?Ba:Ja).request(e,{method:i,headers:p});h.on("response",f=>{let k={status:f.statusCode,headers:new Xi(f.headers),body:""};f.on("data",v=>{k.body+=v}),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 li(s.status,s);return s};if(t.retry)try{let s=typeof t.retry=="object"?t.retry:{};return await Mo(r,s)}catch(s){if(s instanceof li)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 x=class n{static folders(e){return`/v1/orgs/${e}/folders`}static files(e){return`/v1/orgs/${e}/files`}static filesSearch(e){return`${n.files(e)}/search`}static filesAccess(e,t){return`${n.file(e,t)}/access`}static filesBatch(e){return`${n.files(e)}/batch/read-meta`}static file(e,t){return`${n.files(e)}/${t}`}static fileMedia(e,t){return`${n.file(e,t)}/media`}static fileUsers(e,t){return`${n.file(e,t)}/users`}static fileRevisions(e,t){return`${n.file(e,t)}/revisions`}static fileBreadcrumbs(e,t){return`${n.file(e,t)}/breadcrumbs`}static fileRename(e,t){return`${n.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`${n.trash(e)}/${t}`}static trashRestore(e,t){return`${n.trashItem(e,t)}/restore`}static trashEmpty(e){return`${n.trash(e)}/empty`}static trashBatchRestore(e){return`${n.trash(e)}/restore`}static trashBatchDelete(e){return`${n.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`${n.usersMe()}/tokens`}static usersMeToken(e){return`${n.usersMeTokens()}/${e}`}static dataCatalog(){return"/v1/datacatalog"}static dataCatalogStatus(e){return`${n.dataCatalog()}/status/${e}`}static dataCatalogEntry(e){return`${n.dataCatalog()}/${e}`}static dataCatalogEntryVersions(e){return`${n.dataCatalogEntry(e)}/versions`}static dataCatalogDependencies(){return`${n.dataCatalog()}/dependencies`}static dataCatalogUpdates(){return`${n.dataCatalog()}/updates`}static dataCatalogVersion(e,t){return`${n.dataCatalogEntry(e)}/${t}`}static dataCatalogDeprecate(e){return`${n.dataCatalogEntry(e)}/deprecate`}static dataCatalogUnpublish(e){return`${n.dataCatalogEntry(e)}/unpublish`}static dataCatalogVersionDeprecate(e,t){return`${n.dataCatalogVersion(e,t)}/deprecate`}static dataCatalogVersionUnpublish(e,t){return`${n.dataCatalogVersion(e,t)}/unpublish`}static dataCatalogUsage(e){return`${n.dataCatalogEntry(e)}/apis`}static dataCatalogVersionUsage(e,t){return`${n.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`${n.aiSessions(e,t)}/${i}`}static aiMessages(e,t){return`${this.organization(e)}/ai/messages/${t}`}static aiMessage(e,t,i){return`${n.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`${n.deployments(e)}/apis`}static deployment(e,t){return`${n.deployments(e)}/${t}`}static deploymentsForApi(e,t){return`${n.deploymentsApis(e)}/${t}`}static deploymentsApisByEnvLatest(e,t){return`${n.deploymentsApis(e)}/${t}/environments/latest`}static rollback(e,t){return`${n.deployment(e,t)}/rollback`}static deploymentsApiRuntimeUsersUpdate(e,t){return`${n.deploymentsApis(e)}/${t}/runtime/users/update`}static job(e,t){return`/v1/orgs/${e}/jobs/${t}`}};var $r=class extends ce{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(x.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}${N}${s.status}`,s.body)}};import{customAlphabet as pc}from"nanoid";var Q=pc("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var yt="Core#Permission",gt=["reader","commenter","writer","owner"],Ft=class n{kind=yt;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:Q(),kind:yt,itemId:t,granteeId:i,role:e,type:"user",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new n(s)}static fromGroupRole(e,t,i,r){let s={key:Q(),kind:yt,itemId:t,granteeId:i,role:e,type:"group",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new n(s)}static fromOrganizationRole(e,t,i,r){let s={key:Q(),kind:yt,itemId:t,granteeId:i,role:e,type:"organization",addingUser:r,depth:0,sourceRule:"direct_user_grant"};return new n(s)}static fromValues(e){return new n({...e,key:Q(),kind:yt})}constructor(e){let t;typeof e=="string"?t=JSON.parse(e):typeof e=="object"?t=e:t={kind:yt,key:Q(),granteeId:"",itemId:"",role:"reader",type:"user",addingUser:"",depth:0,sourceRule:"direct_user_grant"},this.new(t)}new(e){if(!n.isPermission(e))throw new Error("Not a permission.");let{key:t=Q(),granteeId:i,role:r,type:s,displayName:o,expirationTime:a,addingUser:l,itemId:c,depth:p,sourceRule:u}=e;this.kind=yt,this.key=t,this.granteeId=i,this.itemId=c,this.role=r,this.type=s,this.addingUser=l,this.depth=p||0,this.sourceRule=u||"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!==yt)}static hasRole(e,t){if(!t)return!1;let i=gt.indexOf(t),r=gt.indexOf(e);return i>=r}static isHigherRole(e,t){let i=gt.indexOf(e),r=gt.indexOf(t);return i>r}hasRole(e){return n.hasRole(e,this.role)}static hasRoleIn(e,t){if(!t||!t.length)return!1;let i=[...t].sort((l,c)=>l.depth-c.depth),r=i[0].depth,s=i.filter(l=>l.depth===r),o,a=s.filter(l=>l.type==="user");if(a.length)o=a.sort((l,c)=>gt.indexOf(c.role)-gt.indexOf(l.role))[0];else{let l=s.filter(c=>c.type==="group");if(l.length)o=l.sort((c,p)=>gt.indexOf(p.role)-gt.indexOf(c.role))[0];else{let c=s.filter(p=>p.type==="organization");c.length&&(o=c.sort((p,u)=>gt.indexOf(u.role)-gt.indexOf(p.role))[0])}}return o?n.hasRole(e,o.role):!1}toJSON(){let e={kind:yt,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 Kt="Core#Thing",Xe="Core#Folder";var Yi="Core#User",qt="Data#DomainFile",je="Data#Domain",Re="Domain#Namespace",Oe="Domain#Model",R="Domain#Entity",de="Domain#Association",he="Domain#Property",ct="Core#DataCatalog",jt="Core#DataCatalogVersion";var xi="Core#Deployment",Te="Core#ApiModel",Jt="Core#ExposedEntity",Lo="Core#ApiFile";var Zi="Core#AiSession",Uo="Core#AiMessage",zo="Core#Job";var pe=class n{kind=Kt;name;displayName;description;version;static fromName(e){return new n({name:e,kind:Kt})}static fromJSON(e={},t={}){let i=new n,{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:Kt},this.new(t)}new(e){if(!n.isThing(e))throw new Error("Not a thing.");let{description:t,name:i,version:r,displayName:s}=e;this.kind=Kt,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!==Kt):!1}static isThing(e){return!!(e&&e.kind===Kt)}toJSON(){let e={kind:Kt};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 Vo=Symbol("parents"),Rr=Symbol("deleted"),jr=Symbol("deletedInfo"),Cr=Symbol("lastModified"),Fo=Symbol("capabilities"),Ko=Symbol("permissions"),qo=Symbol("permissionIds"),Jo=Symbol("shortcutTarget"),Qi=class{kind="";key="";info=pe.fromName("");iconColor;get isShortcut(){return!!this.shortcutTarget}[Jo];get shortcutTarget(){return this[Jo]}set shortcutTarget(e){this[Jo]=e}static createSchema(e={}){let{key:t=Q(),kind:i,iconColor:r,shortcutTarget:s}=e,o={key:t,kind:i||"",info:pe.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 pe(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=Ft.hasRole("commenter",t),r=Ft.hasRole("owner",t),s=Ft.hasRole("reader",t),o=Ft.hasRole("writer",t),a=e.kind===Xe;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 Ct.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!==Yi)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!==Yi)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}},Ct=class n extends Qi{[Vo]=[];get parents(){return this[Vo]}[qo]=[];get permissionIds(){return this[qo]}[Rr];get deleted(){return this[Rr]||!1}[jr];get deletedInfo(){return this[jr]}[Cr]={user:"",time:0,byMe:!1};get lastModified(){return this[Cr]}labels;[Fo];get capabilities(){return this[Fo]}[Ko]=[];get permissions(){return this[Ko]}static createSchema(e={}){let t=Qi.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=n.createSchema(e);super(t),this[Vo]=[...t.parents],this[qo]=[...t.permissionIds],this[Ko]=t.permissions.map(i=>({...i})),this[Fo]=t.capabilities?{...t.capabilities}:void 0,this[Cr]=Object.freeze({...t.lastModified}),typeof t.deleted=="boolean"&&(this[Rr]=t.deleted,this[jr]=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 n({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!==Yi)throw new Error('Invalid value for the user when setting "lastModified".');this[Cr]={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!==Yi)throw new Error('Invalid value for the user when setting "deletedInfo".');this[Rr]=!0,this[jr]={byMe:!1,time:Date.now(),user:e.key,name:e.name}}isFile(){return this.kind!==Xe}isFolder(){return this.kind===Xe}};var er=class extends Ct{kind=Xe;static fromName(e){return super.fromName(e,Xe)}constructor(e){let t=Ct.createSchema(e);t.kind=Xe,super(t)}static isFolder(e){return!(!e||e.kind!==Xe)}toJSON(){return{...super.toJSON(),kind:Xe}}};var Tr=class extends ce{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o={...t},a=this.sdk.getUrl(x.files(e));this.sdk.appendListOptions(a,o);let l=await this.sdk.http.get(a.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(l);let c="Unable to list files. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async search(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.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 c of t.kind)a.append("kind",c);if(t.query)for(let c of t.query)a.append("query",c);let l=await this.sdk.http.get(o.toString(),{token:r,retry:s});return this.processListResponse(l,"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(x.files(t));i.parent&&a.searchParams.set("parent",i.parent);let l=JSON.stringify(e),c=await this.sdk.http.post(a.toString(),{token:s,body:l,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(c);let p="Unable to create a file. ";if(c.status!==201)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}async createMedia(e,t,i,r={},s={}){let{token:o=this.sdk.token,retry:a=!0}=s,l=x.fileMedia(t,i),c=this.sdk.getUrl(l),p=r.mime||"application/json",u;p.includes("json")?u=JSON.stringify(e):u=String(e);let m=await this.sdk.http.put(c.toString(),{token:o,body:u,retry:a,headers:{"content-type":p}});this.inspectCommonStatusCodes(m);let h="Unable to create a file. ";if(m.status!==200)throw this.logInvalidResponse(m),this.createApiError(`${h}${N}${m.status}`,m.body)}async createFolder(e,t,i={},r={}){let s=er.fromName(e),{token:o=this.sdk.token,retry:a=!0}=r,l=this.sdk.getUrl(x.files(t));i.parent&&l.searchParams.set("parent",i.parent);let c=JSON.stringify(s),p=await this.sdk.http.post(l.toString(),{token:o,body:c,retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(p);let u="Unable to create a file. ";if(p.status!==201)throw this.logInvalidResponse(p),this.createApiError(`${u}${N}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}if(!m.key)throw new g(`${u}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:p.status});return m}async read(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.file(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to read a file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!c.kind)throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}async readMedia(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.fileMedia(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to read a file media. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!c||typeof c!="object"||!("data"in c)||!("meta"in c))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});let{data:p,meta:u}=c;if(!u||typeof u!="object"||typeof u.version!="number"||typeof u.updated!="number"||isNaN(u.version)||isNaN(u.updated))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return{media:p,meta:u}}async readBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.filesBatch(e)),a=JSON.stringify({ids:t}),l=await this.sdk.http.post(o.toString(),{token:r,body:a,retry:s});this.inspectCommonStatusCodes(l);let c="Unable to read files in bulk. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async patch(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=x.file(e,t),l=this.sdk.getUrl(a),c=JSON.stringify(i),p=await this.sdk.http.patch(l.toString(),{token:s,body:c,retry:o});this.inspectCommonStatusCodes(p);let u="Unable to patch a file. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${u}${N}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}if(!m.kind)throw new g(`${u}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:p.status});return m}async patchMedia(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=x.fileMedia(e,t),l=this.sdk.getUrl(a),c=JSON.stringify(i),p=await this.sdk.http.patch(l.toString(),{token:s,body:c,retry:o});this.inspectCommonStatusCodes(p);let u="Unable to patch a file contents. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${u}${N}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}return m}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.file(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to trash a file. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body)}async deleteBulk(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.files(e)),a=await this.sdk.http.delete(o.toString(),{token:r,body:JSON.stringify({ids:t}),retry:s});this.inspectCommonStatusCodes(a);let l="Unable to trash files. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body)}async patchUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.filesAccess(e,t)),l=JSON.stringify(i),c=await this.sdk.http.patch(a.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(c);let p="Unable to patch the file. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}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 l={patch:[a],id:Q()};return this.patchUsers(e,t,l,o)}async removeUser(e,t,i,r){let o={patch:[{op:"remove",type:"user",id:i}],id:Q()};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(x.fileUsers(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to list users in the file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(c.data))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}async breadcrumbs(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.fileBreadcrumbs(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to read breadcrumbs. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(c.data))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}async rename(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.fileRename(e,t)),l=await this.sdk.http.put(a.toString(),{token:s,body:JSON.stringify({name:i}),retry:o});this.inspectCommonStatusCodes(l);let c="Unable to rename file. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}return p}};var Dr=class extends ce{async me(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(x.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}${N}${s.status}`,s.body);if(!s.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new g(`${o}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!a.key)throw new g(`${o}${Y}`,{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(x.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}${N}${s.status}`,s.body);if(!s.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new g(`${o}${J}`,{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(x.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 l="Unable to create a token. ";if(a.status!==200&&a.status!==201)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}return c}async deleteToken(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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}${N}${o.status}`,o.body)}};var Mr=class extends ce{async list(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.shared(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to list shared files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(c.data))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}};var Lr=class extends ce{async list(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.fileRevisions(e,t));this.sdk.appendListOptions(a,i);let l=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(l);let c="Unable to list revisions for a file. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}};var Ur=class extends ce{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.trash(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to list trash. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(c.data))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}async delete(e,t,i={}){let r=x.trashBatchDelete(e),s=this.sdk.getUrl(r),{token:o=this.sdk.token,retry:a=!0}=i,l=await this.sdk.http.delete(s.toString(),{token:o,body:JSON.stringify({ids:t}),retry:a});this.inspectCommonStatusCodes(l);let c="Unable to delete trash. ";if(l.status!==204)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body)}async restore(e,t,i={}){let r=this.sdk.getUrl(x.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 l="Unable to restore from trash. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body)}async empty(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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}${N}${o.status}`,o.body)}};var zr=class extends ce{async list(e={}){let{token:t=this.sdk.token,retry:i=!0}=e,r=this.sdk.getUrl(x.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}${N}${s.status}`,s.body);if(!s.body)throw new g(`${o}${K}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new g(`${o}${J}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new g(`${o}${Y}`,{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(x.organizations()),a={name:e,slug:t},l=await this.sdk.http.post(o.toString(),{body:JSON.stringify(a),token:r,headers:{"Content-Type":"application/json"},retry:s});this.inspectCommonStatusCodes(l);let c="Unable to create an organization. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.kind)throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}invitations={list:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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}${N}${o.status}`,o.body);if(!o.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let l;try{l=JSON.parse(o.body)}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!Array.isArray(l.data))throw new g(`${a}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return l},create:async(e,t,i,r,s={})=>{let{token:o=this.sdk.token,retry:a=!0}=s,l=this.sdk.getUrl(x.invitations(e)),c={email:t,name:r,grant_type:i},p=await this.sdk.http.post(l.toString(),{body:JSON.stringify(c),token:o,headers:{"Content-Type":"application/json"},retry:a});this.inspectCommonStatusCodes(p);let u="Unable to create an invitation. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${u}${N}${p.status}`,p.body);if(!p.body)throw new g(`${u}${K}`,{code:"E_RESPONSE_NO_VALUE",status:p.status});let m;try{m=JSON.parse(p.body).data}catch{throw new g(`${u}${J}`,{code:"E_INVALID_JSON",status:p.status})}if(!m.kind)throw new g(`${u}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:p.status});return m},findByToken:async(e,t={})=>{let i=this.sdk.getUrl(x.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}${N}${o.status}`,o.body);if(!o.body)throw new g(`${a}${K}`,{code:"E_RESPONSE_NO_VALUE",status:o.status});let l;try{l=JSON.parse(o.body).data}catch{throw new g(`${a}${J}`,{code:"E_INVALID_JSON",status:o.status})}if(!l.kind)throw new g(`${a}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return l},decline:async(e,t,i={})=>{let r=this.sdk.getUrl(x.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 l="Unable to decline invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!c.kind)throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c},delete:async(e,t,i={})=>{let r=this.sdk.getUrl(x.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 l="Unable to delete invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!c.kind)throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c},patch:async(e,t,i,r={})=>{let s=this.sdk.getUrl(x.invitation(e,t)),{token:o=this.sdk.token,retry:a=!0}=r,l=await this.sdk.http.patch(s.toString(),{body:JSON.stringify(i),token:o,headers:{"Content-Type":"application/json"},retry:a});this.inspectCommonStatusCodes(l);let c="Unable to update invitation. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.kind)throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},resend:async(e,t,i={})=>{let r=this.sdk.getUrl(x.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 l="Unable to resend invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!c.kind)throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}};users={list:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.organizationUsers(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to list projects. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!Array.isArray(c.data))throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c},read:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.organizationUser(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to read the user info. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}return c},readBatch:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.organizationUserBatch(e)),a={ids:t},l=await this.sdk.http.post(o.toString(),{body:JSON.stringify(a),token:r,retry:s});this.inspectCommonStatusCodes(l);let c="Unable to read the user batch info. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},activate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.organizationUserActivate(e,t)),a=await this.sdk.http.post(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to activate the user. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}return c},deactivate:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.organizationUserDeactivate(e,t)),a=await this.sdk.http.post(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to deactivate the user. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}return c},delete:async(e,t,i={})=>{let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.organizationUser(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to delete the user. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body)}};slugs={generate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.orgSlugGenerate()).toString(),o={name:e},a=await this.sdk.http.post(s,{body:JSON.stringify(o),token:i,retry:r});this.inspectCommonStatusCodes(a);let l="Unable to generate the slug. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(!c.slug)throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c.slug},validate:async(e,t={})=>{let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.orgSlugValidate()).toString(),o={slug:e},a=await this.sdk.http.post(s,{body:JSON.stringify(o),token:i,retry:r});this.inspectCommonStatusCodes(a);let l="Unable to validate the slug. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);if(!a.body)throw new g(`${l}${K}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body).data}catch{throw new g(`${l}${J}`,{code:"E_INVALID_JSON",status:a.status})}if(typeof c.valid!="boolean")throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c}}};var Vr=class extends ce{async list(e={},t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s={...e},o=this.sdk.getUrl(x.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(x.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(x.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 l="Unable to publish data domain. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,ct,c.kind),c}async read(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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}${N}${o.status}`,o.body);let l=this.readResponseJSON(o,a).data;return this.assertObjectKind(a,ct,l.kind),l}async deprecate(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.dataCatalogDeprecate(e)),a=JSON.stringify({reason:t}),l=await this.sdk.http.put(o.toString(),{token:r,body:a,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let c="Unable to deprecate data domain. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);let p=this.readResponseJSON(l,c).data;return this.assertObjectKind(c,ct,p.kind),p}async unpublish(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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}${N}${o.status}`,o.body);let l=this.readResponseJSON(o,a).data;return this.assertObjectKind(a,ct,l.kind),l}async publishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.dataCatalogEntryVersions(e)),a=JSON.stringify(t),l=await this.sdk.http.post(o.toString(),{token:r,body:a,retry:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(l);let c="Unable to publish data domain version. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);let p=this.readResponseJSON(l,c).data;return this.assertObjectKind(c,jt,p.kind),p}async readVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.dataCatalogVersion(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to read data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,jt,c.kind),c}async listDependencies(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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(c=>({fid:c.key,version:c.version})),o=this.sdk.getUrl(x.dataCatalogUpdates()),a=JSON.stringify({dependencies:s}),l=await this.sdk.http.post(o.toString(),{token:i,body:a,retry:r,headers:{"content-type":"application/json"}});return this.processListResponse(l,"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(x.dataCatalogVersionDeprecate(e,t)),l=JSON.stringify({reason:i}),c=await this.sdk.http.put(a.toString(),{token:s,body:l,retry:o,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(c);let p="Unable to deprecate data domain version. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);let u=this.readResponseJSON(c,p).data;return this.assertObjectKind(p,jt,u.kind),u}async unpublishVersion(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.dataCatalogVersionUnpublish(e,t)),a=await this.sdk.http.put(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to unpublish data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,jt,c.kind),c}async checkPublicationStatus(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.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 l="Unable to check data domain publication status. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,ct,c.kind),c}async getUsageFiles(e,t={}){let{token:i=this.sdk.token,retry:r=!0}=t,s=this.sdk.getUrl(x.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}${N}${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(x.dataCatalogVersionUsage(e,t)),a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to get data catalog version usage files. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);return this.processListResponse(a,l)}};var Fr=class extends ce{async create(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.groups(e)),a=JSON.stringify(t),l=await this.sdk.http.post(o.toString(),{token:r,body:a,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(l);let c="Unable to create a group. ";if(l.status!==201)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.groups(e));this.sdk.appendListOptions(o,t);let a=await this.sdk.http.get(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to create a group. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(l+N+a.status,a.body);if(!a.body)throw new g(l+K,{code:"E_RESPONSE_NO_VALUE",status:a.status});let c;try{c=JSON.parse(a.body)}catch{throw new g(l+J,{code:"E_INVALID_JSON",status:a.status})}return c}async update(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.group(e,t.key)),a=JSON.stringify(t),l=await this.sdk.http.put(o.toString(),{token:r,body:a,headers:{"content-type":"application/json"},retry:s});this.inspectCommonStatusCodes(l);let c="Unable to update a group. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!p.key)throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p}async delete(e,t,i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.group(e,t)),a=await this.sdk.http.delete(o.toString(),{token:r,retry:s});this.inspectCommonStatusCodes(a);let l="Unable to delete a group. ";if(a.status!==204)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body)}async addUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.groupUsers(e,t)),l=JSON.stringify({ids:i}),c=await this.sdk.http.post(a.toString(),{token:s,body:l,headers:{"content-type":"application/json"},retry:o});this.inspectCommonStatusCodes(c);let p="Unable to add users to a group. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}async removeUsers(e,t,i,r={}){let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.groupUsers(e,t)),l=JSON.stringify({ids:i}),c=await this.sdk.http.delete(a.toString(),{token:s,body:l,headers:{"content-type":"application/json"},retry:o});this.inspectCommonStatusCodes(c);let p="Unable to remove users from a group. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(!u.key)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}};var Kr=class extends ce{async*modifyDomain(e,t,i,r,s={}){let{token:o=this.sdk.token,signal:a}=s,l=this.sdk.getUrl(x.aiModifyDomain(e,t)),c=JSON.stringify({goal:i,sid:r}),p={method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${o}`},redirect:"follow",credentials:"include",body:c,signal:a},u=await fetch(l,p);if(!u.ok){let k=await u.text();throw new g(`Failed to modify domain: ${u.status} ${k}`)}let m=u.body?.getReader();if(!m)throw new g("Failed to get reader from response");let h=new TextDecoder,f="";for(;;){let{done:k,value:v}=await m.read();if(k)return;f+=h.decode(v,{stream:!0});let E;for(;(E=f.indexOf(`
17
17
 
18
- `))>=0;){let I=f.slice(0,E);if(f=f.slice(E+2),!I.trim())continue;let R=I.split(`
19
- `),C="message",N="";for(let L of R)L.startsWith("event:")?C=L.substring(6).trim():L.startsWith("data:")&&(N+=L.substring(5).trim());if(!N)continue;let T;try{T=JSON.parse(N)}catch{console.error("Failed to parse SSE JSON data:",N);continue}switch(C){case"user-message":yield{event:C,data:T};break;case"agent-message":yield{event:C,data:T};break;case"thought-chunk":case"text-chunk":yield{event:C,data:T};break;case"done":yield{event:C,data:T};return;case"error":yield{event:C,data:g.fromRawException(T,"Failed to generate results")};break;case"session-updated":yield{event:C,data:T};break;default:console.warn(`Unknown SSE event: ${C}`)}}}}sessions={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiSessions(e,t));this.sdk.appendListOptions(o,i);let l=await this.sdk.http.get(o.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(l);let c="Unable to list sessions. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},read:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiSession(e,t,i)),l=await this.sdk.http.get(o.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(l);let c="Unable to read session. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==Hi)throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},create:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiSessions(e,t)),l=JSON.stringify(i),c=await this.sdk.http.post(o.toString(),{token:s,body:l,retry:a});this.inspectCommonStatusCodes(c);let p="Unable to create session. ";if(c.status!==201)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(u.kind!==Hi)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiSession(e,t,i)),l=await this.sdk.http.delete(o.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(l);let c="Unable to delete session. ";if(l.status!==204)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiSession(e,t,i.key)),l=JSON.stringify(i),c=await this.sdk.http.put(o.toString(),{token:s,body:l,retry:a});this.inspectCommonStatusCodes(c);let p="Unable to update session. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(u.kind!==Hi)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}};messages={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiMessages(e,t));this.sdk.appendListOptions(o,i);let l=await this.sdk.http.get(o.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(l);let c="Unable to list messages. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${X}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiMessage(e,t,i)),l=await this.sdk.http.delete(o.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(l);let c="Unable to delete message. ";if(l.status!==204)throw this.logInvalidResponse(l),this.createApiError(`${c}${$}${l.status}`,l.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:a=!0}=r,o=this.sdk.getUrl(x.aiMessage(e,t,i.key)),l=JSON.stringify(i),c=await this.sdk.http.put(o.toString(),{token:s,body:l,retry:a});this.inspectCommonStatusCodes(c);let p="Unable to update message. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${$}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(u.kind!==$a)throw new g(`${p}${X}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}}};var Ma;(function(n){n.Pending="pending",n.Active="active",n.Inactive="inactive",n.Failed="failed"})(Ma||(Ma={}));var Ai;(function(n){n.PROD="prod",n.STAGING="staging",n.DEV="dev"})(Ai||(Ai={}));var Vr=class extends ce{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,a=this.sdk.getUrl(x.deployments(e));this.sdk.appendListOptions(a,t);let o=await this.sdk.http.get(a.toString(),{token:r,retry:s});return this.processListResponse(o,"Unable to list deployments. ")}async create(e,t,i={}){if(t.env===Ai.PROD&&!t.version)throw new g(`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!==Ai.PROD&&t.version)throw new g(`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(x.deployments(e)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.post(r.toString(),{token:s,body:JSON.stringify(t),retry:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(o);let l="Unable to create a deployment. ";if(o.status!==202)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,_i,c.kind),c}async read(e,t,i={}){let r=this.sdk.getUrl(x.deployment(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.get(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to read a deployment. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,_i,c.kind),c}async deactivate(e,t,i={}){let r=this.sdk.getUrl(x.deployment(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.delete(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to deactivate a deployment. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,_i,c.kind),c}async rollback(e,t,i={}){let r=this.sdk.getUrl(x.rollback(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.post(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to rollback a deployment. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,_i,c.kind),c}apis={getLatestPerEnvironment:async(e,t,i={})=>{let r=this.sdk.getUrl(x.deploymentsApisByEnvLatest(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.get(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to list latest deployments for an API. ",c=this.readResponseJSON(o,l);if(!c.data)throw new g(`${l}${X}`,{code:"E_RESPONSE_UNKNOWN",status:o.status});return c},list:async(e,t={})=>{let i=this.sdk.getUrl(x.deploymentsApis(e)),{token:r=this.sdk.token,retry:s=!0}=t,a=await this.sdk.http.get(i.toString(),{token:r,retry:s});return this.processListResponse(a,"Unable to list APIs. ")},listDeployments:async(e,t,i={},r={})=>{let s=this.sdk.getUrl(x.deploymentsForApi(e,t));this.sdk.appendListOptions(s,i);let{token:a=this.sdk.token,retry:o=!0}=r,l=await this.sdk.http.get(s.toString(),{token:a,retry:o});return this.processListResponse(l,"Unable to list deployments. ")},updateRuntimeUser:async(e,t,i,r,s="production",a={})=>{let o=this.sdk.getUrl(x.deploymentsApiRuntimeUsersUpdate(e,t)),{token:l=this.sdk.token,retry:c=!0}=a,p=JSON.stringify({userId:i,properties:r,env:s}),u=await this.sdk.http.post(o.toString(),{token:l,body:p,retry:c,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(u);let m="Unable to update runtime user. ";if(u.status!==200)throw this.logInvalidResponse(u),this.createApiError(`${m}${$}${u.status}`,u.body);if(!u.body)throw new g(`${m}${K}`,{code:"E_RESPONSE_NO_VALUE",status:u.status});return this.readResponseJSON(u,m)}}};var La;(function(n){n.Pending="pending",n.Running="running",n.Completed="completed",n.Failed="failed"})(La||(La={}));var Fr=class extends ce{async checkStatus(e,t,i={}){let r=this.sdk.getUrl(x.job(e,t)),{token:s=this.sdk.token,retry:a=!0}=i,o=await this.sdk.http.get(r.toString(),{token:s,retry:a});this.inspectCommonStatusCodes(o);let l="Unable to check job status. ";if(o.status!==200)throw this.logInvalidResponse(o),this.createApiError(`${l}${$}${o.status}`,o.body);let c=this.readResponseJSON(o,l).data;return this.assertObjectKind(l,Ia,c.kind),c}};var Ua=Symbol("baseUri"),Kr=class extends EventTarget{basePath;#e;logger;get token(){return this.#e}set token(e){this.#e=e}auth=new Or(this);files=new jr(this);users=new Rr(this);shared=new Cr(this);revisions=new Tr(this);trash=new Dr(this);organizations=new Mr(this);dataCatalog=new Lr(this);groups=new Ur(this);ai=new zr(this);deployments=new Vr(this);jobs=new Fr(this);silent=!1;[Ua]="";get baseUri(){return this[Ua]}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[Ua]=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,a=>String.fromCodePoint(a)).join("");i.set("filter",btoa(s))}}};var qr=class extends Kr{http=new Pr(this)};function G(n={}){let e=A.resolved,t=n.apiUrl||e.apiUrl,i=new qr(t);return e.token&&(i.token=e.token),i.logger=b,i}function F(n){if(n&&typeof n=="object"){let t=n,i=t.status,r=t.code,s=t.message||"An unknown error occurred.",a=t.help;return i===401?(s="Unauthorized. Please login using `auth login`.",{message:s,status:i,code:"CLI_ERR_UNAUTHORIZED",help:a}):{message:s,status:i,code:r||"CLI_ERR_API_FAILURE",help:a}}return{message:n?.message||"An unknown error occurred.",code:"CLI_ERR_UNKNOWN"}}function Ei(n,e){return n.token||(e.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1)),n.token}var Ke=class extends Oe{client;constructor(e,t,i=G()){super(e,t),this.client=i}ensureAuth(){return Ei(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 oc from"node:http";import{readFileSync as nc}from"node:fs";import lc from"open";import{input as rc,confirm as sc,select as ac}from"@inquirer/prompts";async function je(n,e){return(await rc({message:n,default:e})).trim()}async function Jr(n,e=!0){return sc({message:n,default:e})}async function Xe(n,e){return ac({message:n,choices:e})}async function Br(n,e){let t;try{t=(await n.organizations.list({token:n.token})).data||[]}catch{return}if(t.length>0){if(!A.resolved.org){let a=t[0],o=a.key;A.writeOrgToActiveProfile(o),e.format!=="json"&&console.log(`
20
- `+ee.cyan(`\u2139 Automatically set default organization to "${a.name}" (${o}).`))}return}if(e.format==="json")return;console.log(`
21
- `+ee.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 je("Enter organization name:"),i||console.log(ee.red("Error: Organization name cannot be empty."));let r;try{r=await n.organizations.slugs.generate(i,{token:n.token})}catch{r=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}if(!await Jr(`Use suggested organization slug "${r}"?`,!0)){let a=!1;for(;!a;){let o=await je("Enter organization slug:");if(!o){console.log(ee.red("Error: Slug cannot be empty."));continue}try{let l=await n.organizations.slugs.validate(o,{token:n.token});l.valid?(r=o,a=!0):console.log(ee.red(`Error: ${l.reason||"Invalid slug"}`))}catch{console.log(ee.red("Error validating slug with server. Please try another slug."))}}}console.log(`
22
- Creating organization "${i}" with slug "${r}"...`);try{let o=(await n.organizations.create(i,r,{token:n.token})).key;A.writeOrgToActiveProfile(o),console.log(`
23
- `+ee.green(`\u2714 Organization "${i}" created successfully!`)),console.log(`Set as default organization: ${ee.cyan(o)}`)}catch(a){let o=F(a);console.log(ee.red(`Error creating organization: ${o.message}`))}}var Gr=class n extends Ke{static ALLOWED_PROVIDERS=["google","github","linkedin"];provider;constructor(e,t,i,r=G()){super(t,i,r),this.provider=e}async execute(){b.debug(`[auth] Initiating authentication flow for provider '${this.provider}'...`),n.ALLOWED_PROVIDERS.includes(this.provider)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid provider '${this.provider}'. Allowed: ${n.ALLOWED_PROVIDERS.join(", ")}`}),process.exit(1));let e=this.options.profile||"default",t=this.options.apiUrl||process.env.APINOW_API_URL||A.resolved.apiUrl||qi;A.resolved.format!=="json"&&console.log(`Starting authentication flow for profile '${e}' using provider '${this.provider}'...`);try{let i=await this.runLoginServer(t,this.provider,e);b.debug("[auth] Login server callback received token successfully."),this.formatter.success(`Successfully authenticated profile '${e}'!`),this.client.token=i,b.debug("[auth] Checking/setting up first organization for authenticated user..."),await Br(this.client,this.formatter)}catch(i){i instanceof Error?this.formatter.error({code:"CLI_ERR_UNAUTHORIZED",message:i.message}):this.formatter.error({code:"CLI_ERR_UNAUTHORIZED",message:"Authentication failed."}),process.exit(1)}}runLoginServer(e,t,i){return new Promise((r,s)=>{let a=oc.createServer((p,u)=>{if(p.method==="GET"&&p.url?.startsWith("/callback")){b.debug(`[auth] Received request for callback: ${p.url}`),u.writeHead(200,{"Content-Type":"text/html"});let m=this.getLoginHtml(e);u.end(m);return}if(p.method==="POST"&&p.url==="/token"){let m="";p.on("data",h=>{m+=h}),p.on("end",()=>{try{let h=JSON.parse(m);h.token?(b.debug(`[auth] Storing retrieved token for profile '${i}'...`),A.upsertProfile(i,{token:h.token,apiUrl:e}),A.setActiveProfile(i),u.writeHead(200,{"Content-Type":"application/json"}),u.end(JSON.stringify({success:!0})),r(h.token)):(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:"Token missing"})),s(new Error("Token missing from browser callback.")))}catch(h){h instanceof Error?(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:h.message})),s(new Error("Invalid body received: "+h.message))):(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:"Invalid body received"})),s(new Error("Invalid body received")))}finally{c()}});return}if(p.method==="POST"&&p.url==="/error"){let m="";p.on("data",h=>{m+=h}),p.on("end",()=>{try{let h=JSON.parse(m);b.debug(`[auth] Received login error from browser callback: ${h.message}`),s(new Error(h.message||"Browser login failed"))}catch{s(new Error("Browser login failed"))}finally{c()}});return}u.writeHead(404),u.end()}),o=()=>{c(),process.exit(130)};process.on("SIGINT",o),process.on("SIGTERM",o);let l=setTimeout(()=>{s(new Error("Authentication timed out.")),c()},3e5);function c(){clearTimeout(l),process.off("SIGINT",o),process.off("SIGTERM",o),a.close()}a.listen(0,"127.0.0.1",async()=>{let p=a.address().port,m=new URL(e).hostname==="localhost"?"localhost":"127.0.0.1",h=`${e}/auth/${t}/redirect?r=http://${m}:${p}/callback`;b.debug(`[auth] Ephemeral loopback server listening on http://127.0.0.1:${p}`),b.debug(`[auth] Browser callback origin configured to http://${m}:${p}`),this.formatter.format!=="json"&&(console.log("Opening browser to log in..."),console.log(`If it doesn't open automatically, navigate to:
24
- ${h}`));try{await lc(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 nc(i,"utf8").replaceAll("{{API_URL}}",e)}catch{}throw new Error("Unable to locate login.html template.")}};var Hr=class extends Ke{constructor(e,t,i=G()){super(e,t,i)}execute(){let e=this.options.profile||A.resolved.activeProfile||"default";b.debug(`[auth] Executing logout command for profile '${e}'...`),A.deleteProfile(e),b.debug("[auth] Profile credentials removed successfully."),this.formatter.success(`Logged out of profile '${e}'.`),!A.resolved.activeProfile&&this.formatter.format!=="json"&&console.log("No active profile is set. Run `apinow auth profile use <name>` or `apinow auth login`.")}};var Wr=class extends Ke{constructor(e,t,i=G()){super(e,t,i)}async execute(){b.debug("[auth] Checking current authentication status..."),this.ensureAuth();try{b.debug("[auth] Retrieving user profile details from platform...");let e=await this.client.users.me({token:this.client.token});if(b.debug(`[auth] User retrieved successfully: ${e.name}`),A.resolved.format==="json")this.formatter.object({authenticated:!0,profile:A.resolved.activeProfile,user:e});else{console.log(ee.green("\u2714 Authenticated successfully!")),A.resolved.activeProfile&&console.log(`Profile: ${A.resolved.activeProfile}`);let t=this.extractUserEmail(e.email);console.log(`User: ${e.name} (${t})`);let i=await this.resolveDefaultOrgLabel(A.resolved.org);console.log(`Default Org: ${i}`)}b.debug("[auth] Checking default organization status..."),await Br(this.client,this.formatter)}catch(e){let t=F(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 Xr=class extends Ke{execute(){b.debug("[auth:profile:list] Listing configured authentication profiles...");let e=A.listProfiles(),t=A.getActiveProfile(),i=Object.entries(e);if(this.formatter.format==="json"){let s=i.map(([a,o])=>({alias:a,active:a===t,org:o.org||null,apiUrl:o.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,a])=>({alias:s===t?`* ${s}`:` ${s}`,active:s===t?"true":"false",org:a.org||"-",apiUrl:a.apiUrl||"-"}));this.formatter.list(r,["alias","active","org","apiUrl"],{headers:["PROFILE","ACTIVE","DEFAULT ORG","API URL"]})}};var Yr=class extends Ke{alias;constructor(e,t,i,r=G()){super(t,i,r),this.alias=e}async execute(){b.debug(`[auth:profile:use] Switching active profile to '${this.alias}'...`);let e=A.listProfiles();this.alias in e||(b.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){b.debug(`[auth:profile:use] Verifying token validity for profile '${this.alias}'...`);try{await G({apiUrl:t.apiUrl}).users.me({token:t.token}),b.debug(`[auth:profile:use] Profile '${this.alias}' verified successfully.`)}catch(i){b.debug(`[auth:profile:use] Verification failed for profile '${this.alias}': ${String(i)}`),this.formatter.format!=="json"&&console.warn(ee.yellow(`\u26A0 Warning: Token for profile '${this.alias}' appears to be invalid or expired.`))}}A.setActiveProfile(this.alias),b.debug(`[auth:profile:use] Active profile updated to '${this.alias}'.`),this.formatter.success(`Switched to profile '${this.alias}'.`)}};var Zr=class extends Ke{alias;constructor(e,t,i){super(t,i),this.alias=e}execute(){b.debug(`[auth:profile:delete] Deleting profile '${this.alias}'...`);let e=A.listProfiles();this.alias in e||(b.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=A.getActiveProfile()===this.alias;A.deleteProfile(this.alias),b.debug(`[auth:profile:delete] Profile '${this.alias}' deleted successfully.`),this.formatter.success(`Profile '${this.alias}' deleted.`),t&&!A.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 qt=class extends Oe{client;constructor(e,t,i=G()){super(e,t),this.client=i}ensureAuth(){return Ei(this.client,this.formatter)}getActiveTokenId(){let e=A.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 Qr=class extends qt{constructor(e,t,i=G()){super(e,t,i)}async execute(){try{b.debug("[auth:tokens] Listing personal access tokens..."),this.ensureAuth();let e=await this.client.users.listTokens({token:this.client.token});b.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=F(e);this.formatter.error(t),process.exit(1)}}};var es=class extends qt{constructor(e,t,i=G()){super(e,t,i)}async execute(){try{b.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});b.debug(`[auth:tokens] Token created successfully with ID="${t.id}"`),this.formatResult(t)}catch(e){let t=F(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){A.resolved.format==="json"?this.formatter.success("Token created successfully!",e):(this.formatter.success("Token created successfully!"),console.log(`
25
- `+ee.yellow("\u26A0 WARNING: Make sure to copy your personal access token now. You will NOT be able to see it again!")+`
26
- `),console.log(`${ee.bold("Raw Token")}: ${ee.cyan(e.token)}`),console.log(`${ee.bold("ID")}: ${e.id}`),console.log(`${ee.bold("Name")}: ${e.name||"N/A"}`),console.log(`${ee.bold("Type")}: ${e.type}`),console.log(`${ee.bold("Expires At")}: ${e.expiresAt||"Never"}
27
- `))}};var ts=class extends qt{id;constructor(e,t,i,r=G()){super(t,i,r),this.id=e}async execute(){try{b.debug(`[auth:tokens] Deleting personal access token with ID="${this.id}"`),this.ensureAuth(),await this.client.users.deleteToken(this.id,{token:this.client.token}),b.debug(`[auth:tokens] Successfully deleted token ID="${this.id}"`),this.formatter.success(`Token '${this.id}' deleted successfully.`)}catch(e){let t=F(e);this.formatter.error(t),process.exit(1)}}};function zo(n){let e=n.command("tokens").description("Manage personal access tokens");e.command("list").description("List all personal access tokens").action(async t=>{let i=new Z({format:A.resolved.format});await new Qr(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 Z({format:A.resolved.format});await new es(t,i).execute()}),e.command("delete <id>").description("Delete a personal access token by ID").action(async(t,i)=>{let r=new Z({format:A.resolved.format});await new ts(t,i,r).execute()})}function Vo(n){let e=n.command("auth").description("Manage CLI authentication");zo(e),e.command("login").description("Authenticate with the API platform using OAuth2 (google, github, or linkedin)").addArgument(new cc("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 Z({format:A.resolved.format});await new Gr(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 Z({format:A.resolved.format});new Hr(i,r).execute()}),e.command("status").description("Check current authentication status").action(async i=>{let r=new Z({format:A.resolved.format});await new Wr(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 Z({format:A.resolved.format});new Xr(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 Z({format:A.resolved.format});await new Yr(i,r,s).execute()}),t.command("delete <name>").description("Delete a configured authentication profile").action((i,r)=>{let s=new Z({format:A.resolved.format});new Zr(i,r,s).execute()})}var Jt=class extends Oe{client;constructor(e,t,i=G()){super(e,t),this.client=i}async fetchOrganizations(){return(await this.client.organizations.list({token:this.client.token})).data||[]}};var is=class extends Jt{constructor(e,t,i=G()){super(e,t,i)}async execute(){b.debug("[orgs:list] Listing all authorized organizations...");try{let e=await this.fetchOrganizations();b.debug(`[orgs:list] Found ${e.length} organizations.`);let t=A.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=F(e);this.formatter.error(t),process.exit(1)}}};var rs=class extends Jt{oid;constructor(e,t,i,r=G()){super(t,i,r),this.oid=e}async execute(){b.debug(`[orgs:set-default] Setting default organization ID to '${this.oid}'...`);try{b.debug("[orgs:set-default] Validating organization ID in user's authorized list..."),(await this.fetchOrganizations()).some(i=>i.key===this.oid)||(b.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)),b.debug(`[orgs:set-default] Organization ID validated. Writing 'org' property as '${this.oid}'...`),A.writeOrgToActiveProfile(this.oid),b.debug("[orgs:set-default] Configuration property written successfully."),this.formatter.success(`Default organization ID set to '${this.oid}'.`)}catch(e){let t=F(e);this.formatter.error(t),process.exit(1)}}};var ss=class extends Jt{constructor(e,t,i=G()){super(e,t,i)}async execute(){b.debug("[orgs:default] Retrieving the default configured organization...");try{let e=A.resolved;e.org||(b.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)),b.debug(`[orgs:default] Fetching organization list to validate configured org '${e.org}'...`);let i=(await this.fetchOrganizations()).find(r=>r.key===e.org);i||(b.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)),b.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=F(e);this.formatter.error(t),process.exit(1)}}};function Fo(n){let e=n.command("orgs").description("Manage organization configurations");e.command("list").description("List all organizations you belong to").action(async t=>{let i=new Z({format:A.resolved.format});await new is(t,i).execute()}),e.command("set-default <oid>").description("Set your default organization ID").action(async(t,i)=>{let r=new Z({format:A.resolved.format});await new rs(t,i,r).execute()}),e.command("default").alias("get-default").description("Get the default configured organization").action(async t=>{let i=new Z({format:A.resolved.format});await new ss(t,i).execute()})}import Ko from"node:fs";import dc from"node:path";import{nanoid as pc}from"nanoid";var ne=class{constructor(e=G()){this.client=e}client;getFileMetaKind(e){let t=e.toLowerCase();if(t==="api"||t===Na.toLowerCase())return Na;if(t==="domain"||t===Kt.toLowerCase())return Kt;if(t==="folder"||t===We.toLowerCase())return We;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 b.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 read(e,t){return b.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){b.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=jt.createSchema({kind:i,info:{name:t.name},key:t.key}),s={};t.parent&&(s.parent=t.parent),b.debug(`[FileManager:create] Creating file metadata '${t.name}' (kind: ${i})...`);let a=await this.client.files.createMeta(r,e,s,{token:this.client.token}),o=a.key;return b.debug(`[FileManager:create] Created file metadata successfully. Key: ${o}`),t.mediaContent!==void 0&&(b.debug(`[FileManager:create] Uploading file media for key '${o}'...`),await this.client.files.createMedia(t.mediaContent,e,o,{},{token:this.client.token}),b.debug("[FileManager:create] Media uploaded successfully.")),a}async patchMedia(e,t,i){b.debug(`[FileManager:patchMedia] Sending ${i.patchOps.length} patch op(s) for file ID '${t}' (current version: ${i.version})...`);let r={id:pc(),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=dc.resolve(e.mediaPath);if(b.debug(`[FileManager:parseMediaInput] Reading media file from: ${i}`),!Ko.existsSync(i))throw new Error(`Media file not found at path: ${i}`);t=Ko.readFileSync(i,"utf8")}else e.stdin&&(b.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 Bt=class extends Oe{fileManager;constructor(e,t,i=new ne){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){b.debug("[files] ID not provided, fetching files list for interactive selection...");try{let r=await this.fileManager.list(e);r.length>0&&(i=await Xe(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 as=class extends Bt{constructor(e,t,i=new ne){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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});b.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=F(t);this.formatter.error(i),process.exit(1)}}};var os=class extends Bt{constructor(e,t,i=new ne){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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 je("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 Xe("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 a=F(r);this.formatter.error({code:"CLI_ERR_API_FAILURE",...a}),process.exit(1)}}};var ns=class extends Bt{constructor(e,t,i=new ne){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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){b.debug(`[files:read] Fetching media content for file ID '${t}'...`);let r=(await this.fileManager.readMedia(e,t)).media;b.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{b.debug(`[files:read] Fetching metadata for file ID '${t}'...`);let i=await this.fileManager.read(e,t);b.debug("[files:read] Metadata retrieved successfully."),this.formatter.object(i)}}catch(i){let r=F(i);this.formatter.error(r),process.exit(1)}}};function qo(n){let e=n.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 Z({format:A.resolved.format});await new as(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 Z({format:A.resolved.format});await new os(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 Z({format:A.resolved.format});await new ns(t,i).execute()})}var Me=class extends Oe{client;fileManager;constructor(e,t,i=G(),r=new ne){super(e,t),this.client=i,this.fileManager=r}resolveVersionOption(e){return e.catalogVersion||e.ver}};var li=class n{key;get kind(){return It}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:a=0,catalogKey:o="",lifecycle:l="stable",version:c=""}=e;if(["public","private","organization"].indexOf(i)===-1)throw new Error(`Invalid scope: ${i}`);let p={key:t,kind:It,scope:i,publishedBy:r,createdAt:s,updatedAt:a,catalogKey:o,lifecycle:l,version:c};return typeof e.deprecated=="boolean"&&(p.deprecated=e.deprecated),typeof e.deprecatedAt=="number"&&(p.deprecatedAt=e.deprecatedAt),typeof e.deprecatedBy=="string"&&(p.deprecatedBy=e.deprecatedBy),typeof e.changelog=="string"&&(p.changelog=e.changelog),typeof e.deprecationReason=="string"&&(p.deprecationReason=e.deprecationReason),typeof e.unpublishedAt=="number"&&(p.unpublishedAt=e.unpublishedAt),p}constructor(e={}){let t=n.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:It,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 y;(function(n){n.User="Semantic#User",n.Address="Semantic#Address",n.Organization="Semantic#Organization",n.Project="Semantic#Project",n.AbstractManyToMany="Semantic#AbstractManyToMany",n.Password="Semantic#Password",n.Username="Semantic#Username",n.CreatedTimestamp="Semantic#CreatedTimestamp",n.UpdatedTimestamp="Semantic#UpdatedTimestamp",n.DeletedTimestamp="Semantic#DeletedTimestamp",n.DeletedFlag="Semantic#DeletedFlag",n.PublicUniqueName="Semantic#PublicUniqueName",n.Title="Semantic#Title",n.Name="Semantic#Name",n.UserRole="Semantic#UserRole",n.OrganizationRole="Semantic#OrganizationRole",n.ProjectRole="Semantic#ProjectRole",n.AssociationRole="Semantic#AssociationRole",n.Status="Semantic#Status",n.Version="Semantic#Version",n.ImageURL="Semantic#ImageURL",n.FileURL="Semantic#FileURL",n.Markdown="Semantic#Markdown",n.HTML="Semantic#HTML",n.GeospatialCoordinates="Semantic#GeospatialCoordinates",n.Email="Semantic#Email",n.Phone="Semantic#Phone",n.Currency="Semantic#Currency",n.URL="Semantic#URL",n.SKU="Semantic#SKU",n.Description="Semantic#Description",n.Summary="Semantic#Summary",n.Calculated="Semantic#Calculated",n.Derived="Semantic#Derived",n.ClientIPAddress="Semantic#ClientIPAddress",n.StreetAddress="Semantic#StreetAddress",n.StreetAddressSupplemental="Semantic#StreetAddressSupplemental",n.City="Semantic#City",n.PostalCode="Semantic#PostalCode",n.Country="Semantic#Country",n.Region="Semantic#Region",n.ResourceOwnerIdentifier="Semantic#ResourceOwnerIdentifier",n.RelationalResourceOwner="Semantic#RelationalResourceOwner",n.OrganizationMembers="Semantic#OrganizationMembers",n.ProjectMembers="Semantic#ProjectMembers",n.OrganizationResource="Semantic#OrganizationResource",n.ProjectResource="Semantic#ProjectResource",n.CreatedBy="Semantic#CreatedBy",n.UpdatedBy="Semantic#UpdatedBy",n.DeletedBy="Semantic#DeletedBy",n.Tags="Semantic#Tags",n.Categories="Semantic#Categories"})(y||(y={}));var q;(function(n){n.Entity="Entity",n.Property="Property",n.Association="Association"})(q||(q={}));var H;(function(n){n.Identity="Identity & Authentication",n.Lifecycle="Timestamps & Versioning",n.Content="Content & Media",n.Business="Business Data",n.Organization="Classification & Organization",n.Location="Location & Geography",n.Contact="Contact Information",n.Computed="Computed Values"})(H||(H={}));var Jo=n=>n.scope===q.Entity,ls=n=>n.scope===q.Property,cs=n=>n.scope===q.Association,dt={[y.User]:{id:y.User,displayName:"User Entity",scope:q.Entity,description:"System users and accounts",category:H.Identity,hasConfig:!1},[y.Password]:{id:y.Password,displayName:"User Password",scope:q.Property,description:"Secure password field",category:H.Identity,applicableDataTypes:["string"],hasConfig:!0},[y.Username]:{id:y.Username,displayName:"Username",scope:q.Property,description:"User authentication identifier",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.UserRole]:{id:y.UserRole,displayName:"User Role Field",scope:q.Property,description:"User permissions and access level",category:H.Identity,applicableDataTypes:["string"],hasConfig:!0},[y.ResourceOwnerIdentifier]:{id:y.ResourceOwnerIdentifier,displayName:"Resource Owner Identifier",scope:q.Association,description:"Links record to owner user",category:H.Identity,hasConfig:!1},[y.RelationalResourceOwner]:{id:y.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:H.Identity,hasConfig:!1},[y.Organization]:{id:y.Organization,displayName:"Organization Entity",scope:q.Entity,description:"Applied to the top-level Organization entity",category:H.Identity,hasConfig:!0},[y.AbstractManyToMany]:{id:y.AbstractManyToMany,displayName:"Abstract Many-To-Many",scope:q.Association,description:"Hidden parent semantic for all M:N relationships",category:H.Organization,hasConfig:!1,isHidden:!0,isManyToMany:!0},[y.OrganizationMembers]:{id:y.OrganizationMembers,displayName:"Organization Members",scope:q.Association,description:"Applied to the association pointing from Organization to User",category:H.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Organization Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:y.Organization,target:y.User},{parent:y.User,target:y.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:y.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:y.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[y.Project]:{id:y.Project,displayName:"Project Entity",scope:q.Entity,description:"Applied to a Project entity",category:H.Identity,hasConfig:!1},[y.ProjectMembers]:{id:y.ProjectMembers,displayName:"Project Members",scope:q.Association,description:"Applied to the association pointing from Project to User",category:H.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Project Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:y.Project,target:y.User},{parent:y.User,target:y.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:y.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:y.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[y.OrganizationRole]:{id:y.OrganizationRole,displayName:"Organization Role Property",scope:q.Property,description:"Represents a membership role inside an organization",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.ProjectRole]:{id:y.ProjectRole,displayName:"Project Role Property",scope:q.Property,description:"Represents a membership role inside a project",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.AssociationRole]:{id:y.AssociationRole,displayName:"Association Role Property",scope:q.Property,description:"Represents a membership access role on a many-to-many association",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.OrganizationResource]:{id:y.OrganizationResource,displayName:"Organization Resources",scope:q.Association,description:"Represents resources owned by an organization",category:H.Identity,hasConfig:!1},[y.ProjectResource]:{id:y.ProjectResource,displayName:"Project Resources",scope:q.Association,description:"Represents resources owned by a project",category:H.Identity,hasConfig:!1},[y.CreatedBy]:{id:y.CreatedBy,displayName:"Created By",scope:q.Association,description:"Links record to the user who created it",category:H.Identity,hasConfig:!1},[y.UpdatedBy]:{id:y.UpdatedBy,displayName:"Updated By",scope:q.Association,description:"Links record to the user who last updated it",category:H.Identity,hasConfig:!1},[y.DeletedBy]:{id:y.DeletedBy,displayName:"Deleted By",scope:q.Association,description:"Links record to the user who soft-deleted it",category:H.Identity,hasConfig:!1},[y.CreatedTimestamp]:{id:y.CreatedTimestamp,displayName:"Creation Timestamp",scope:q.Property,description:"When record was created",category:H.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[y.UpdatedTimestamp]:{id:y.UpdatedTimestamp,displayName:"Update Timestamp",scope:q.Property,description:"When record was last modified",category:H.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[y.DeletedTimestamp]:{id:y.DeletedTimestamp,displayName:"Soft Delete Timestamp",scope:q.Property,description:"When record was marked deleted",category:H.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[y.DeletedFlag]:{id:y.DeletedFlag,displayName:"Soft Delete Flag",scope:q.Property,description:"Mark record as deleted",category:H.Lifecycle,applicableDataTypes:["boolean"],hasConfig:!1},[y.Address]:{id:y.Address,displayName:"Address Entity",scope:q.Entity,description:"Physical address entity",category:H.Contact,hasConfig:!1},[y.StreetAddress]:{id:y.StreetAddress,displayName:"Street Address",scope:q.Property,description:"Street address line",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.StreetAddressSupplemental]:{id:y.StreetAddressSupplemental,displayName:"Street Address Supplemental",scope:q.Property,description:"Supplemental street address line (e.g., Unit, Suite, Apartment, Floor)",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.City]:{id:y.City,displayName:"City",scope:q.Property,description:"City or locality",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.PostalCode]:{id:y.PostalCode,displayName:"Postal Code",scope:q.Property,description:"Postal or zip code",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.Country]:{id:y.Country,displayName:"Country",scope:q.Property,description:"Country name or code",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.Region]:{id:y.Region,displayName:"Region",scope:q.Property,description:"State, province, or region",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.Version]:{id:y.Version,displayName:"Version Number",scope:q.Property,description:"Auto-incrementing version counter",category:H.Lifecycle,applicableDataTypes:["number"],hasConfig:!1},[y.Title]:{id:y.Title,displayName:"Record Title",scope:q.Property,description:"Main title or heading",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Name]:{id:y.Name,displayName:"Name",scope:q.Property,description:"A person or pet name",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Description]:{id:y.Description,displayName:"Description",scope:q.Property,description:"Detailed description text",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Summary]:{id:y.Summary,displayName:"Summary",scope:q.Property,description:"Brief summary text",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Markdown]:{id:y.Markdown,displayName:"Markdown Content",scope:q.Property,description:"Formatted text content",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.HTML]:{id:y.HTML,displayName:"HTML Content",scope:q.Property,description:"Rich HTML content",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.ImageURL]:{id:y.ImageURL,displayName:"Image URL",scope:q.Property,description:"Link to image file",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.FileURL]:{id:y.FileURL,displayName:"File URL",scope:q.Property,description:"Link to file attachment",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.Status]:{id:y.Status,displayName:"Record Status",scope:q.Property,description:"Current state of record",category:H.Business,applicableDataTypes:["string"],hasConfig:!0},[y.Currency]:{id:y.Currency,displayName:"Currency",scope:q.Property,description:"Monetary value with currency",category:H.Business,applicableDataTypes:["number","string"],hasConfig:!0},[y.SKU]:{id:y.SKU,displayName:"SKU",scope:q.Property,description:"Product identification code",category:H.Business,applicableDataTypes:["string"],hasConfig:!0},[y.Email]:{id:y.Email,displayName:"Email",scope:q.Property,description:"Email address",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.Phone]:{id:y.Phone,displayName:"Phone",scope:q.Property,description:"Phone number",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.URL]:{id:y.URL,displayName:"URL",scope:q.Property,description:"Web address or link",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.ClientIPAddress]:{id:y.ClientIPAddress,displayName:"Client IP Address",scope:q.Property,description:"Automatically populated client IP address",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.PublicUniqueName]:{id:y.PublicUniqueName,displayName:"Public Unique Name (Slug)",scope:q.Property,description:"URL-friendly unique identifier",category:H.Organization,applicableDataTypes:["string"],hasConfig:!0},[y.Tags]:{id:y.Tags,displayName:"Tags",scope:q.Association,description:"Enable tagging functionality",category:H.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany},[y.Categories]:{id:y.Categories,displayName:"Categories",scope:q.Association,description:"Enable categorization functionality",category:H.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany},[y.GeospatialCoordinates]:{id:y.GeospatialCoordinates,displayName:"Geospatial Coordinates",scope:q.Property,description:"Location coordinates",category:H.Location,applicableDataTypes:["string"],hasConfig:!0},[y.Calculated]:{id:y.Calculated,displayName:"Calculated",scope:q.Property,description:"Auto-calculated field value",category:H.Computed,applicableDataTypes:["string","number","boolean","date","datetime","time","binary"],hasConfig:!0},[y.Derived]:{id:y.Derived,displayName:"Derived",scope:q.Property,description:"Value derived from other fields",category:H.Computed,applicableDataTypes:["string"],hasConfig:!0}};var za;(function(n){n[n.Initializing=0]="Initializing",n[n.PendingDns=1]="PendingDns",n[n.Issuing=2]="Issuing",n[n.Active=3]="Active",n[n.Error=4]="Error"})(za||(za={}));var ve=class n extends Error{static E_VALIDATION_ERROR="E_VALIDATION_ERROR";code=n.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,n)}};function ds(n,e){if(n==="-")return;let t=new ve([{message:"Invalid pointer",path:`/${n}`}]),{length:i}=n;if(i>1&&n[0]==="0")throw t;let r=+n;if(Number.isNaN(r)||Math.abs(r).toString()!==n||r<0||r>e)throw t}function xi(n,e){let{length:t}=e,i=n,r;for(let s=0;s<t-1;s++){if(r=e[s],Array.isArray(i))ds(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))ds(r,i.length);else if(typeof i!="object"||i===null)throw new Error("Invalid target");return{token:r,parent:i}}function pt(n,e){let t=e.tokens,i=t.length;if(i===0||i===1&&t[0]==="")throw new ve([{message:"Cannot walk empty path.",path:e.raw}]);try{let r=xi(n,t);return{token:r.token,parent:r.parent}}catch{throw new ve([{message:"Path not found.",path:e.raw}])}}var uc=["boolean","string","number","null"];function Gt(n){let e=typeof n;if(e==="boolean"||e==="string")return e;if(e==="number"&&Number.isFinite(n))return"number";if(e==="object"){if(Array.isArray(n)||n instanceof Set)return"array";if(n instanceof Map)return"object";if(n===null)return"null";if(e==="object")return"object"}}function ps(n){return n===void 0?!0:uc.includes(n)}function Bo(n,e="/"){return n.replace(/~0/g,"~").replace(/~1/g,e)}function Va(n,e="/"){let t="",i=n;typeof i=="number"&&(i=String(i));for(let r=0,s=i.length;r<s;r++){let a=i.charAt(r);a==="~"?t+="~0":a===e?t+="~1":t+=a}return t}function we(n,e="/"){let t="";for(let i=0,r=n.length;i<r;i++)t+=e+Va(n[i],e);return t}function ut(n,e="/"){if(Array.isArray(n))return n;if(n.length===0)return[];if(n.charAt(0)!==e)throw new ve([{message:"Invalid pointer.",path:n}]);let t=[""],i=0;for(let r=1,s=n.length;r<s;r++){let a=n.charAt(r);if(a===e){let o=t[t.length-1];if(o==="constructor"||o==="__proto__")throw new Error("Prototype pollution attempt");t.push(""),i++}else a==="~"?n.charAt(r+1)==="1"?(t[i]+=e,r++):n.charAt(r+1)==="0"?(t[i]+="~",r++):t[i]+=a:t[i]+=a}return t}function us(n,e,t){let i,r;return typeof n=="string"?i=ut(n,t):i=n,typeof e=="string"?r=[e]:r=e,we(i.concat(r),t)}function mc(n,e){if(n instanceof Set){let t=0;for(let i of n)e(i,t+=1)}else if(Array.isArray(n)||n instanceof Map)n.forEach(e);else if(typeof n=="object"&&n!==null)Object.keys(n).forEach(t=>{e(n[t],t)});else throw new TypeError(`${n} is not a structure`)}function Go(n,e,t,i){i(n,e,t),!(n===null||typeof n!="object")&&mc(n,(r,s)=>{Go(r,s,n,i)})}function ms(n,e){let t=Object.create(null);function i(s){for(let a in t)if(t[a]===s)return a}function r(s,a,o){let l=us(o&&i(o),a);t[l]=s}Go(n,void 0,void 0,(s,a,o)=>{if(s!==null&&typeof s=="object"&&(o===void 0||a===void 0?r(s,[],""):r(s,a.toString(),o)),a===void 0||o===void 0)e(s,"");else{let l=i(o);e(s,us(l,a.toString()),o,l)}})}var ue=class n{_raw="";_tokens=[];_separator;_index;_parent;constructor(e,t="/"){if(e instanceof n&&e.separator===t)return e;this._separator=t,Array.isArray(e)?(this._tokens=e,this._raw=we(e,this._separator)):typeof e=="string"?(this._raw=e,this._tokens=ut(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 n(this._tokens.slice(0,-1),this._separator),this._parent)}isRoot(){return this._tokens.length===0||this._tokens[0]===""}append(e){return new n([...this._tokens,String(e)],this._separator)}prefix(e){if(e<0||e>this._tokens.length)throw new Error("Levels out of bound.");return new n(this._tokens.slice(0,e),this._separator)}escape(e){return Va(e,this._separator)}unescape(e){return Bo(e,this._separator)}static encode(e,t="/"){return we(e,t)}encode(e=this._separator){return we(this._tokens,e)}static decode(e,t="/"){return ut(e,t)}find(e){let{tokens:t}=this;if(t.length===0)return e;let i;try{i=xi(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 n(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 ve([{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 n(e).getIndex()}setIndex(e){let t=this._tokens,i=t[t.length-1];if(i===void 0)return new n(`/${e}`,this._separator);if(isNaN(+i))return new n([...t,e.toString()],this._separator);let r=Array.from(t);return r[r.length-1]=e.toString(),new n(r,this._separator)}static index(e){let t=Object.create(null);return ms(e,(i,r)=>{t[r]=i}),t}static join(e,t,i){let r,s;if(typeof e=="string"?r=ut(e,i):r=e,typeof t=="string"){if(!t)return we(r,i);let a=t,o=i||"/";a.startsWith(o)||(a=`${o}${a}`),s=ut(a,i)}else s=t;return we(r.concat(s),i)}static unflatten(e){let t=Object.keys(e),i=e[""];for(let r of t){if(r==="")continue;let s=ut(r),a=xi(i,s),{parent:o,token:l}=a;o instanceof Map?o.set(l,e[r]):o instanceof Set?o.add(e[r]):Array.isArray(o)?o.push(e[r]):o[l]=e[r]}return i}static flatten(e){let t=Object.create(null);return ms(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 ci(n,e){let t=new ue(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return n;let{parent:i,token:r}=pt(n,t);if(Array.isArray(i))ue.isValidArrayToken(r,i.length);else if(typeof i=="object"&&i!==null&&!(r in i))throw new ve([{path:`/${r}`,message:"The target does not exists."}]);return i[r]}function yt(n,e,t){let i=new ue(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:n};let{token:s,parent:a}=pt(n,i),o,l;if(Array.isArray(a))s==="-"?(a.push(r),l=a.length-1):a.splice(parseInt(s,10),0,r);else{o=a[s];let c=a;c[s]=r}return{doc:n,previous:o,idx:l}}function Rt(n,e){let t=new ue(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return{doc:void 0,previous:n};let{parent:i,token:r}=pt(n,t),s=i[r];if(s===void 0)throw new ve([{message:"Parent does not exists.",path:t.raw}]);return Array.isArray(i)?i.splice(parseInt(r,10),1):delete i[r],{doc:n,previous:s}}function Pi(n,e,t){let i=new ue(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:n};let{parent:s,token:a}=pt(n,i),o=s[a];if(o===void 0)throw new ve([{message:"Location not found.",path:i.raw}]);return s[a]=r,{doc:n,previous:o}}function Yi(n,e,t){let i=new ue(e),r=new ue(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:Rt(n,i).previous,previous:n};let s=Rt(n,i);return yt(s.doc,r,s.previous)}function Oi(n,e,t){let i=new ue(e),r=new ue(t),s=ci(n,i);return e===""||e==="/"?{doc:s,previous:n}:yt(n,r,s)}function Ho(n){let e=[];return n.forEach(t=>{e.push(t)}),e}function Wo(n){let e=Object.create(null);return n.forEach((t,i)=>{e[i]=t}),e}function Fa(n,e,t,i){let r=Gt(n),s=Gt(e);if(r!==s)return!1;switch(r){case"number":return n===0&&1/n===-1/0?e===0&&1/e===-1/0:n===e;case"string":case"null":case"boolean":return n===e;default:}let a,o,l=t.indexOf(n);if(l!==-1)return i[l]===e;if(t.push(n),i.push(e),r==="array"){n instanceof Set&&(n=Ho(n)),e instanceof Set&&(e=Ho(e));let c=n,p=e;if(c.length!==p.length)return t.pop(),i.pop(),!1;for(a=0,o=c.length;a<o;a++)if(!Fa(c[a],p[a],t,i))return t.pop(),i.pop(),!1;return!0}if(r==="object"){n instanceof Map&&(n=Wo(n)),e instanceof Map&&(e=Wo(e));let c=n,p=e,u=Object.keys(c),m=Object.keys(p);if(u.length!==m.length)return t.pop(),i.pop(),!1;for(u.sort(),m.sort(),a=0,o=u.length;a<o;a++){let h=u[a],f=m[a];if(h!==f||!Object.prototype.hasOwnProperty.call(p,h)||!Fa(c[h],p[h],t,i))return t.pop(),i.pop(),!1}return t.pop(),i.pop(),!0}return t.pop(),i.pop(),!0}function bt(n,e){return Fa(n,e,[],[])}var hs=class n extends Me{static ALLOWED_SCOPES=["public","organization","private"];static ALLOWED_LIFECYCLES=["dev","beta","stable"];constructor(e,t,i=G(),r=new ne){super(e,t,i,r)}async execute(){let e=this.resolveOrgId(),t=this.resolveVersionOption(this.options);b.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(),a=await this.resolveScope(),o=await this.resolveVersion(t),l=this.validateLifecycle(this.options.lifecycle);try{let c=await this.resolveOrCreateCatalogId(i,e,r,s,a),p=await this.publishVersion(c,a,l,o,this.options.changelog);this.formatter.success(`Successfully published version '${o}' to the data catalog!`,p)}catch(c){let p=F(c);this.formatter.error(p),process.exit(1)}}async resolveFileId(e){let t=this.options.file;if(!t&&process.stdout.isTTY){b.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:Kt}},{token:this.client.token})).data||[];r.length>0&&(t=await Xe("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 je("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 je("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 Xe("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)),n.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'.`,detail:`Allowed: ${n.ALLOWED_SCOPES.join(", ")}`}),process.exit(1)),e}async resolveVersion(e){let t=e;return!t&&process.stdout.isTTY&&(t=await je("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 n.ALLOWED_LIFECYCLES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${e}'.`,detail:`Allowed: ${n.ALLOWED_LIFECYCLES.join(", ")}`}),process.exit(1)),e}async resolveOrCreateCatalogId(e,t,i,r,s){b.debug(`[catalog:publish] Checking publication status for file ID '${e}' in organization '${t}'...`);let a=null;try{a=(await this.client.dataCatalog.checkPublicationStatus(e,t,{token:this.client.token})).key,b.debug(`[catalog:publish] Found existing catalog entry key: ${a}`)}catch(o){if(F(o).status!==404)throw o;b.debug("[catalog:publish] Catalog entry does not exist yet.")}if(a)b.debug(`[catalog:publish] Using existing catalog entry key: ${a}`),A.resolved.format!=="json"&&console.log(`Catalog entry already exists (ID: ${a}). Publishing new version...`);else{b.debug("[catalog:publish] Creating a new catalog entry..."),A.resolved.format!=="json"&&console.log("Catalog entry does not exist. Creating new catalog entry...");let o={key:"",kind:ct,organization:t,file:e,scope:s,name:i,description:r,publishedBy:"",publishedAt:0,createdAt:0,updatedAt:0,tags:[]};a=(await this.client.dataCatalog.publish(o,{token:this.client.token})).key,b.debug(`[catalog:publish] Created new catalog entry with key: ${a}`)}return a}async publishVersion(e,t,i,r,s){let a=li.createSchema({scope:t,lifecycle:i,version:r,changelog:s||void 0});b.debug(`[catalog:publish] Publishing version '${r}' for catalog key '${e}'...`);let o=await this.client.dataCatalog.publishVersion(e,a,{token:this.client.token});return b.debug(`[catalog:publish] Version published successfully. Version key: ${o.key}`),o}};var fs=class n extends Me{static ALLOWED_SCOPES=["all","public","organization","private"];constructor(e,t,i=G()){super(e,t,i)}async execute(){let e=this.options.org||A.resolved.org;b.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=F(t);this.formatter.error(i),process.exit(1)}}validateScope(e){n.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'. Allowed: ${n.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){b.debug(`[catalog:list] Fetching versions for catalog entry key '${e}'...`);let i=(await this.client.dataCatalog.listVersions(e,{token:this.client.token})).data||[];b.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"){b.debug("[catalog:list] Fetching public catalog entries...");let r=await this.fetchScope("public",t);if(i.push(...r),t){b.debug(`[catalog:list] Fetching organization catalog entries for org '${t}'...`);let s=await this.fetchScope("organization",t);i.push(...s),b.debug(`[catalog:list] Fetching private catalog entries for org '${t}'...`);let a=await this.fetchScope("private",t);i.push(...a)}}else{b.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 b.debug(`[catalog:list] Failed to fetch catalog entries for scope '${e}'.`),[]}}deduplicateEntries(e){b.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 b.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 gs=class extends Me{key;constructor(e,t,i,r=G()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);b.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=F(t);this.formatter.error(i),process.exit(1)}}};var ys=class extends Me{key;constructor(e,t,i,r=G()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options),t=await this.resolveReason();try{if(e){b.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{b.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=F(i);this.formatter.error(r),process.exit(1)}}async resolveReason(){let e=this.options.reason;return!e&&process.stdout.isTTY&&(e=await je("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 bs=class extends Me{key;constructor(e,t,i,r=G()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);try{if(e){b.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{b.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=F(t);this.formatter.error(i),process.exit(1)}}};var ks=class extends Me{key;constructor(e,t,i,r=G()){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=F(t);this.formatter.error(i),process.exit(1)}}async fetchUsageFiles(e){return e?(b.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})):(b.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 vs=class extends Me{fid;constructor(e,t,i,r=G()){super(t,i,r),this.fid=e}async execute(){let e=this.options.org||A.resolved.org;try{b.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=F(t);this.formatter.error(i),process.exit(1)}}};function Xo(n){let e=n.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 Z({format:A.resolved.format});await new hs(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 Z({format:A.resolved.format});await new fs(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 Z({format:A.resolved.format});await new gs(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 Z({format:A.resolved.format});await new ys(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 Z({format:A.resolved.format});await new bs(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 Z({format:A.resolved.format});await new ks(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 Z({format:A.resolved.format});await new vs(t,i,r).execute()})}import da from"node:fs";import xl from"node:path";var et=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 gc="http://a.ml/",Ct=`${gc}vocabularies/`,te=`${Ct}document#`,ye=`${Ct}core#`,se=`${Ct}security#`,M=`${Ct}apiContract#`,Zi=`${Ct}apiBinding#`,W=`${Ct}shapes#`,Se=`${Ct}data#`,mt=`${Ct}document-source-maps#`,Qi="http://www.w3.org/",me=`${Qi}ns/shacl#`,qe=`${Qi}2001/XMLSchema#`,ws=`${Qi}1999/02/22-rdf-syntax-ns#`,Ka=`${Qi}2000/01/rdf-schema#`,d={aml:{key:"http://a.ml/",vocabularies:{key:Ct,document:{key:te,Module:`${te}Module`,Document:`${te}Document`,Fragment:`${te}Fragment`,Unit:`${te}Unit`,SecuritySchemeFragment:`${te}SecuritySchemeFragment`,UserDocumentation:`${te}UserDocumentation`,DataType:`${te}DataType`,NamedExamples:`${te}NamedExamples`,DomainElement:`${te}DomainElement`,DomainProperty:`${te}DomainProperty`,ParametrizedDeclaration:`${te}ParametrizedDeclaration`,AbstractDeclaration:`${te}AbstractDeclaration`,VariableValue:`${te}VariableValue`,ExternalFragment:`${te}ExternalFragment`,ExternalDomainElement:`${te}ExternalDomainElement`,RootDomainElement:`${te}RootDomainElement`,APIContractProcessingData:`${te}APIContractProcessingData`,BaseUnitProcessingData:`${te}BaseUnitProcessingData`,customDomainProperties:`${te}customDomainProperties`,encodes:`${te}encodes`,declares:`${te}declares`,references:`${te}references`,examples:`${te}examples`,linkTarget:`${te}link-target`,linkLabel:`${te}link-label`,referenceId:`${te}reference-id`,structuredValue:`${te}structuredValue`,raw:`${te}raw`,extends:`${te}extends`,value:`${te}value`,name:`${te}name`,strict:`${te}strict`,deprecated:`${te}deprecated`,location:`${te}location`,variable:`${te}variable`,target:`${te}target`,dataNode:`${te}dataNode`,root:`${te}root`,usage:`${te}usage`,version:`${te}version`},core:{key:ye,CreativeWork:`${ye}CreativeWork`,Parameter:`${ye}Parameter`,Organization:`${ye}Organization`,License:`${ye}License`,Operation:`${ye}Operation`,Response:`${ye}Response`,Payload:`${ye}Payload`,Request:`${ye}Request`,version:`${ye}version`,urlTemplate:`${ye}urlTemplate`,displayName:`${ye}displayName`,title:`${ye}title`,name:`${ye}name`,description:`${ye}description`,documentation:`${ye}documentation`,summary:`${ye}summary`,provider:`${ye}provider`,email:`${ye}email`,url:`${ye}url`,termsOfService:`${ye}termsOfService`,license:`${ye}license`,mediaType:`${ye}mediaType`,extensionName:`${ye}extensionName`,deprecated:`${ye}deprecated`},security:{key:se,ParametrizedSecurityScheme:`${se}ParametrizedSecurityScheme`,SecuritySchemeFragment:`${se}SecuritySchemeFragment`,SecurityScheme:`${se}SecurityScheme`,OAuth1Settings:`${se}OAuth1Settings`,OAuth2Settings:`${se}OAuth2Settings`,OAuth2Flow:`${se}OAuth2Flow`,Scope:`${se}Scope`,Settings:`${se}Settings`,HttpSettings:`${se}HttpSettings`,ApiKeySettings:`${se}ApiKeySettings`,OpenIdConnectSettings:`${se}OpenIdConnectSettings`,SecurityRequirement:`${se}SecurityRequirement`,security:`${se}security`,scheme:`${se}scheme`,schemes:`${se}schemes`,settings:`${se}settings`,name:`${se}name`,type:`${se}type`,scope:`${se}scope`,accessTokenUri:`${se}accessTokenUri`,authorizationUri:`${se}authorizationUri`,authorizationGrant:`${se}authorizationGrant`,flows:`${se}flows`,flow:`${se}flow`,signature:`${se}signature`,tokenCredentialsUri:`${se}tokenCredentialsUri`,requestTokenUri:`${se}requestTokenUri`,refreshUri:`${se}refreshUri`,securityRequirement:`${se}SecurityRequirement`,openIdConnectUrl:`${se}openIdConnectUrl`,bearerFormat:`${se}bearerFormat`,in:`${se}in`},apiContract:{key:M,Payload:`${M}Payload`,Request:`${M}Request`,Response:`${M}Response`,EndPoint:`${M}EndPoint`,Parameter:`${M}Parameter`,Operation:`${M}Operation`,WebAPI:`${M}WebAPI`,API:`${M}API`,AsyncAPI:`${M}AsyncAPI`,UserDocumentationFragment:`${M}UserDocumentationFragment`,Example:`${M}Example`,Server:`${M}Server`,ResourceType:`${M}ResourceType`,Trait:`${M}Trait`,TraitFragment:`${M}TraitFragment`,ParametrizedResourceType:`${M}ParametrizedResourceType`,ParametrizedTrait:`${M}ParametrizedTrait`,Callback:`${M}Callback`,TemplatedLink:`${M}TemplatedLink`,IriTemplateMapping:`${M}IriTemplateMapping`,Tag:`${M}Tag`,Message:`${M}Message`,DomainExtension:`${M}DomainExtension`,Encoding:`${M}Encoding`,header:`${M}header`,parameter:`${M}parameter`,paramName:`${M}paramName`,uriParameter:`${M}uriParameter`,cookieParameter:`${M}cookieParameter`,variable:`${M}variable`,payload:`${M}payload`,server:`${M}server`,path:`${M}path`,url:`${M}url`,scheme:`${M}scheme`,endpoint:`${M}endpoint`,queryString:`${M}queryString`,accepts:`${M}accepts`,guiSummary:`${M}guiSummary`,binding:`${M}binding`,response:`${M}response`,returns:`${M}returns`,expects:`${M}expects`,examples:`${M}examples`,supportedOperation:`${M}supportedOperation`,messageId:`${M}messageId`,statusCode:`${M}statusCode`,method:`${M}method`,required:`${M}required`,callback:`${M}callback`,expression:`${M}expression`,link:`${M}link`,linkExpression:`${M}linkExpression`,templateVariable:`${M}templateVariable`,mapping:`${M}mapping`,operationId:`${M}operationId`,protocol:`${M}protocol`,protocolVersion:`${M}protocolVersion`,headerSchema:`${M}headerSchema`,contentType:`${M}contentType`,allowEmptyValue:`${M}allowEmptyValue`,style:`${M}style`,explode:`${M}explode`,allowReserved:`${M}allowReserved`,tag:`${M}tag`,tags:`${M}tags`},apiBinding:{key:Zi,binding:`${Zi}binding`,bindings:`${Zi}bindings`,messageKey:`${Zi}messageKey`,type:`${Zi}type`},shapes:{key:W,Shape:`${W}Shape`,ScalarShape:`${W}ScalarShape`,ArrayShape:`${W}ArrayShape`,UnionShape:`${W}UnionShape`,NilShape:`${W}NilShape`,FileShape:`${W}FileShape`,AnyShape:`${W}AnyShape`,SchemaShape:`${W}SchemaShape`,MatrixShape:`${W}MatrixShape`,TupleShape:`${W}TupleShape`,RecursiveShape:`${W}RecursiveShape`,DataTypeFragment:`${W}DataTypeFragment`,XMLSerializer:`${W}XMLSerializer`,number:`${W}number`,integer:`${W}integer`,long:`${W}long`,double:`${W}double`,boolean:`${W}boolean`,float:`${W}float`,nil:`${W}nil`,password:`${W}password`,int32:`${W}int32`,int64:`${W}int64`,uint32:`${W}uint32`,uint64:`${W}uint64`,sint32:`${W}sint32`,sint64:`${W}sint64`,fixed32:`${W}fixed32`,fixed64:`${W}fixed64`,sfixed32:`${W}sfixed32`,sfixed64:`${W}sfixed64`,dateTimeOnly:`${W}dateTimeOnly`,range:`${W}range`,items:`${W}items`,anyOf:`${W}anyOf`,fileType:`${W}fileType`,schema:`${W}schema`,xmlSerialization:`${W}xmlSerialization`,xmlName:`${W}xmlName`,xmlAttribute:`${W}xmlAttribute`,xmlWrapped:`${W}xmlWrapped`,xmlNamespace:`${W}xmlNamespace`,xmlPrefix:`${W}xmlPrefix`,readOnly:`${W}readOnly`,writeOnly:`${W}writeOnly`,deprecated:`${W}deprecated`,fixPoint:`${W}fixPoint`,discriminator:`${W}discriminator`,discriminatorValue:`${W}discriminatorValue`,format:`${W}format`,multipleOf:`${W}multipleOf`,uniqueItems:`${W}uniqueItems`},data:{key:Se,Scalar:`${Se}Scalar`,Object:`${Se}Object`,Array:`${Se}Array`,Node:`${Se}Node`,value:`${Se}value`,type:`${Se}type`,description:`${Se}description`,required:`${Se}required`,displayName:`${Se}displayName`,minLength:`${Se}minLength`,maxLength:`${Se}maxLength`,default:`${Se}default`,multipleOf:`${Se}multipleOf`,minimum:`${Se}minimum`,maximum:`${Se}maximum`,enum:`${Se}enum`,pattern:`${Se}pattern`,items:`${Se}items`,format:`${Se}format`,example:`${Se}example`,examples:`${Se}examples`},docSourceMaps:{key:mt,SourceMap:`${mt}SourceMap`,sources:`${mt}sources`,element:`${mt}element`,value:`${mt}value`,declaredElement:`${mt}declared-element`,trackedElement:`${mt}tracked-element`,parsedJsonSchema:`${mt}parsed-json-schema`,autoGeneratedName:`${mt}auto-generated-name`,lexical:`${mt}lexical`,synthesizedField:`${mt}synthesized-field`}}},w3:{key:Qi,shacl:{key:me,Shape:`${me}Shape`,NodeShape:`${me}NodeShape`,SchemaShape:`${me}SchemaShape`,PropertyShape:`${me}PropertyShape`,in:`${me}in`,defaultValue:`${me}defaultValue`,defaultValueStr:`${me}defaultValueStr`,pattern:`${me}pattern`,minInclusive:`${me}minInclusive`,maxInclusive:`${me}maxInclusive`,multipleOf:`${me}multipleOf`,minLength:`${me}minLength`,maxLength:`${me}maxLength`,fileType:`${me}fileType`,and:`${me}and`,property:`${me}property`,name:`${me}name`,raw:`${me}raw`,datatype:`${me}datatype`,minCount:`${me}minCount`,maxCount:`${me}maxCount`,xone:`${me}xone`,not:`${me}not`,or:`${me}or`,closed:`${me}closed`,path:`${me}path`,additionalPropertiesSchema:`${me}additionalPropertiesSchema`},xmlSchema:{key:qe,boolean:`${qe}boolean`,string:`${qe}string`,number:`${qe}number`,integer:`${qe}integer`,long:`${qe}long`,double:`${qe}double`,float:`${qe}float`,nil:`${qe}nil`,dateTime:`${qe}dateTime`,time:`${qe}time`,date:`${qe}date`,base64Binary:`${qe}base64Binary`,byte:`${qe}byte`},rdfSyntax:{key:ws,Seq:`${ws}Seq`,Property:`${ws}Property`,member:`${ws}member`},rdfSchema:{key:Ka,Seq:`${Ka}Seq`,member:`${Ka}member`}}};function Ni(n,e=0){if(typeof n!="object")return n;let t="",i=new Array(e).fill(" ").join("");return Object.keys(n).forEach(r=>{t+=Array.isArray(n[r])?"":`${i}<${r}>`,Array.isArray(n[r])?n[r].forEach(s=>{t+=i,t+=`<${r}>
28
- `,t+=Ni({...s},e+1),t+=i,t+=`</${r}>
18
+ `))>=0;){let $=f.slice(0,E);if(f=f.slice(E+2),!$.trim())continue;let j=$.split(`
19
+ `),C="message",I="";for(let U of j)U.startsWith("event:")?C=U.substring(6).trim():U.startsWith("data:")&&(I+=U.substring(5).trim());if(!I)continue;let T;try{T=JSON.parse(I)}catch{console.error("Failed to parse SSE JSON data:",I);continue}switch(C){case"user-message":yield{event:C,data:T};break;case"agent-message":yield{event:C,data:T};break;case"thought-chunk":case"text-chunk":yield{event:C,data:T};break;case"done":yield{event:C,data:T};return;case"error":yield{event:C,data:g.fromRawException(T,"Failed to generate results")};break;case"session-updated":yield{event:C,data:T};break;default:console.warn(`Unknown SSE event: ${C}`)}}}}sessions={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiSessions(e,t));this.sdk.appendListOptions(a,i);let l=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(l);let c="Unable to list sessions. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},read:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiSession(e,t,i)),l=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(l);let c="Unable to read session. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body).data}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(p.kind!==Zi)throw new g(`${c}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:l.status});return p},create:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiSessions(e,t)),l=JSON.stringify(i),c=await this.sdk.http.post(a.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(c);let p="Unable to create session. ";if(c.status!==201)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(u.kind!==Zi)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u},delete:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiSession(e,t,i)),l=await this.sdk.http.delete(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(l);let c="Unable to delete session. ";if(l.status!==204)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiSession(e,t,i.key)),l=JSON.stringify(i),c=await this.sdk.http.put(a.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(c);let p="Unable to update session. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(u.kind!==Zi)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}};messages={list:async(e,t,i={},r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiMessages(e,t));this.sdk.appendListOptions(a,i);let l=await this.sdk.http.get(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(l);let c="Unable to list messages. ";if(l.status!==200)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body);if(!l.body)throw new g(`${c}${K}`,{code:"E_RESPONSE_NO_VALUE",status:l.status});let p;try{p=JSON.parse(l.body)}catch{throw new g(`${c}${J}`,{code:"E_INVALID_JSON",status:l.status})}if(!Array.isArray(p.data))throw new g(`${c}${Y}`,{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(x.aiMessage(e,t,i)),l=await this.sdk.http.delete(a.toString(),{token:s,retry:o});this.inspectCommonStatusCodes(l);let c="Unable to delete message. ";if(l.status!==204)throw this.logInvalidResponse(l),this.createApiError(`${c}${N}${l.status}`,l.body)},update:async(e,t,i,r={})=>{let{token:s=this.sdk.token,retry:o=!0}=r,a=this.sdk.getUrl(x.aiMessage(e,t,i.key)),l=JSON.stringify(i),c=await this.sdk.http.put(a.toString(),{token:s,body:l,retry:o});this.inspectCommonStatusCodes(c);let p="Unable to update message. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${p}${N}${c.status}`,c.body);if(!c.body)throw new g(`${p}${K}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let u;try{u=JSON.parse(c.body).data}catch{throw new g(`${p}${J}`,{code:"E_INVALID_JSON",status:c.status})}if(u.kind!==Uo)throw new g(`${p}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return u}}};var Bo;(function(n){n.Pending="pending",n.Active="active",n.Inactive="inactive",n.Failed="failed"})(Bo||(Bo={}));var Oi;(function(n){n.PROD="prod",n.STAGING="staging",n.DEV="dev"})(Oi||(Oi={}));var qr=class extends ce{async list(e,t={},i={}){let{token:r=this.sdk.token,retry:s=!0}=i,o=this.sdk.getUrl(x.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===Oi.PROD&&!t.version)throw new g(`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!==Oi.PROD&&t.version)throw new g(`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(x.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 l="Unable to create a deployment. ";if(a.status!==202)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,xi,c.kind),c}async read(e,t,i={}){let r=this.sdk.getUrl(x.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 l="Unable to read a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,xi,c.kind),c}async deactivate(e,t,i={}){let r=this.sdk.getUrl(x.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 l="Unable to deactivate a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,xi,c.kind),c}async rollback(e,t,i={}){let r=this.sdk.getUrl(x.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 l="Unable to rollback a deployment. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,xi,c.kind),c}apis={getLatestPerEnvironment:async(e,t,i={})=>{let r=this.sdk.getUrl(x.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 l="Unable to list latest deployments for an API. ",c=this.readResponseJSON(a,l);if(!c.data)throw new g(`${l}${Y}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return c},list:async(e,t={})=>{let i=this.sdk.getUrl(x.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(x.deploymentsForApi(e,t));this.sdk.appendListOptions(s,i);let{token:o=this.sdk.token,retry:a=!0}=r,l=await this.sdk.http.get(s.toString(),{token:o,retry:a});return this.processListResponse(l,"Unable to list deployments. ")},updateRuntimeUser:async(e,t,i,r,s="production",o={})=>{let a=this.sdk.getUrl(x.deploymentsApiRuntimeUsersUpdate(e,t)),{token:l=this.sdk.token,retry:c=!0}=o,p=JSON.stringify({userId:i,properties:r,env:s}),u=await this.sdk.http.post(a.toString(),{token:l,body:p,retry:c,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(u);let m="Unable to update runtime user. ";if(u.status!==200)throw this.logInvalidResponse(u),this.createApiError(`${m}${N}${u.status}`,u.body);if(!u.body)throw new g(`${m}${K}`,{code:"E_RESPONSE_NO_VALUE",status:u.status});return this.readResponseJSON(u,m)}}};var Go;(function(n){n.Pending="pending",n.Running="running",n.Completed="completed",n.Failed="failed"})(Go||(Go={}));var Jr=class extends ce{async checkStatus(e,t,i={}){let r=this.sdk.getUrl(x.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 l="Unable to check job status. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${l}${N}${a.status}`,a.body);let c=this.readResponseJSON(a,l).data;return this.assertObjectKind(l,zo,c.kind),c}};var Ho=Symbol("baseUri"),Br=class extends EventTarget{basePath;#e;logger;get token(){return this.#e}set token(e){this.#e=e}auth=new $r(this);files=new Tr(this);users=new Dr(this);shared=new Mr(this);revisions=new Lr(this);trash=new Ur(this);organizations=new zr(this);dataCatalog=new Vr(this);groups=new Fr(this);ai=new Kr(this);deployments=new qr(this);jobs=new Jr(this);silent=!1;[Ho]="";get baseUri(){return this[Ho]}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[Ho]=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 Gr=class extends Br{http=new Nr(this)};function G(n={}){let e=_.resolved,t=n.apiUrl||e.apiUrl,i=new Gr(t);return e.token&&(i.token=e.token),i.logger=b,i}function D(n){if(n&&typeof n=="object"){let t=n,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}):{message:s,status:i,code:r||"CLI_ERR_API_FAILURE",help:o}}return{message:n?.message||"An unknown error occurred.",code:"CLI_ERR_UNKNOWN"}}function Pi(n,e){return n.token||(e.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1)),n.token}var Je=class extends Se{client;constructor(e,t,i=G()){super(e,t),this.client=i}ensureAuth(){return Pi(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 fc from"node:http";import{readFileSync as gc}from"node:fs";import yc from"open";import{input as uc,confirm as mc,select as hc}from"@inquirer/prompts";async function be(n,e){return(await uc({message:n,default:e})).trim()}async function Hr(n,e=!0){return mc({message:n,default:e})}async function Ke(n,e){return hc({message:n,choices:e})}async function Wr(n,e){let t;try{t=(await n.organizations.list({token:n.token})).data||[]}catch{return}if(t.length>0){if(!_.resolved.org){let o=t[0],a=o.key;_.writeOrgToActiveProfile(a),e.format!=="json"&&console.log(`
20
+ `+te.cyan(`\u2139 Automatically set default organization to "${o.name}" (${a}).`))}return}if(e.format==="json")return;console.log(`
21
+ `+te.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 be("Enter organization name:"),i||console.log(te.red("Error: Organization name cannot be empty."));let r;try{r=await n.organizations.slugs.generate(i,{token:n.token})}catch{r=i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}if(!await Hr(`Use suggested organization slug "${r}"?`,!0)){let o=!1;for(;!o;){let a=await be("Enter organization slug:");if(!a){console.log(te.red("Error: Slug cannot be empty."));continue}try{let l=await n.organizations.slugs.validate(a,{token:n.token});l.valid?(r=a,o=!0):console.log(te.red(`Error: ${l.reason||"Invalid slug"}`))}catch{console.log(te.red("Error validating slug with server. Please try another slug."))}}}console.log(`
22
+ Creating organization "${i}" with slug "${r}"...`);try{let a=(await n.organizations.create(i,r,{token:n.token})).key;_.writeOrgToActiveProfile(a),console.log(`
23
+ `+te.green(`\u2714 Organization "${i}" created successfully!`)),console.log(`Set as default organization: ${te.cyan(a)}`)}catch(o){let a=D(o);console.log(te.red(`Error creating organization: ${a.message}`))}}var Xr=class n extends Je{static ALLOWED_PROVIDERS=["google","github","linkedin"];provider;constructor(e,t,i,r=G()){super(t,i,r),this.provider=e}async execute(){b.debug(`[auth] Initiating authentication flow for provider '${this.provider}'...`),n.ALLOWED_PROVIDERS.includes(this.provider)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid provider '${this.provider}'. Allowed: ${n.ALLOWED_PROVIDERS.join(", ")}`}),process.exit(1));let e=this.options.profile||"default",t=this.options.apiUrl||process.env.APINOW_API_URL||_.resolved.apiUrl||Hi;_.resolved.format!=="json"&&console.log(`Starting authentication flow for profile '${e}' using provider '${this.provider}'...`);try{let i=await this.runLoginServer(t,this.provider,e);b.debug("[auth] Login server callback received token successfully."),this.formatter.success(`Successfully authenticated profile '${e}'!`),this.client.token=i,b.debug("[auth] Checking/setting up first organization for authenticated user..."),await Wr(this.client,this.formatter)}catch(i){i instanceof Error?this.formatter.error({code:"CLI_ERR_UNAUTHORIZED",message:i.message}):this.formatter.error({code:"CLI_ERR_UNAUTHORIZED",message:"Authentication failed."}),process.exit(1)}}runLoginServer(e,t,i){return new Promise((r,s)=>{let o=fc.createServer((p,u)=>{if(p.method==="GET"&&p.url?.startsWith("/callback")){b.debug(`[auth] Received request for callback: ${p.url}`),u.writeHead(200,{"Content-Type":"text/html"});let m=this.getLoginHtml(e);u.end(m);return}if(p.method==="POST"&&p.url==="/token"){let m="";p.on("data",h=>{m+=h}),p.on("end",()=>{try{let h=JSON.parse(m);h.token?(b.debug(`[auth] Storing retrieved token for profile '${i}'...`),_.upsertProfile(i,{token:h.token,apiUrl:e}),_.setActiveProfile(i),u.writeHead(200,{"Content-Type":"application/json"}),u.end(JSON.stringify({success:!0})),r(h.token)):(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:"Token missing"})),s(new Error("Token missing from browser callback.")))}catch(h){h instanceof Error?(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:h.message})),s(new Error("Invalid body received: "+h.message))):(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:"Invalid body received"})),s(new Error("Invalid body received")))}finally{c()}});return}if(p.method==="POST"&&p.url==="/error"){let m="";p.on("data",h=>{m+=h}),p.on("end",()=>{try{let h=JSON.parse(m);b.debug(`[auth] Received login error from browser callback: ${h.message}`),s(new Error(h.message||"Browser login failed"))}catch{s(new Error("Browser login failed"))}finally{c()}});return}u.writeHead(404),u.end()}),a=()=>{c(),process.exit(130)};process.on("SIGINT",a),process.on("SIGTERM",a);let l=setTimeout(()=>{s(new Error("Authentication timed out.")),c()},3e5);function c(){clearTimeout(l),process.off("SIGINT",a),process.off("SIGTERM",a),o.close()}o.listen(0,"127.0.0.1",async()=>{let p=o.address().port,m=new URL(e).hostname==="localhost"?"localhost":"127.0.0.1",h=`${e}/auth/${t}/redirect?r=http://${m}:${p}/callback`;b.debug(`[auth] Ephemeral loopback server listening on http://127.0.0.1:${p}`),b.debug(`[auth] Browser callback origin configured to http://${m}:${p}`),this.formatter.format!=="json"&&(console.log("Opening browser to log in..."),console.log(`If it doesn't open automatically, navigate to:
24
+ ${h}`));try{await yc(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 gc(i,"utf8").replaceAll("{{API_URL}}",e)}catch{}throw new Error("Unable to locate login.html template.")}};var Yr=class extends Je{constructor(e,t,i=G()){super(e,t,i)}execute(){let e=this.options.profile||_.resolved.activeProfile||"default";b.debug(`[auth] Executing logout command for profile '${e}'...`),_.deleteProfile(e),b.debug("[auth] Profile credentials removed successfully."),this.formatter.success(`Logged out of profile '${e}'.`),!_.resolved.activeProfile&&this.formatter.format!=="json"&&console.log("No active profile is set. Run `apinow auth profile use <name>` or `apinow auth login`.")}};var Zr=class extends Je{constructor(e,t,i=G()){super(e,t,i)}async execute(){b.debug("[auth] Checking current authentication status..."),this.ensureAuth();try{b.debug("[auth] Retrieving user profile details from platform...");let e=await this.client.users.me({token:this.client.token});if(b.debug(`[auth] User retrieved successfully: ${e.name}`),_.resolved.format==="json")this.formatter.object({authenticated:!0,profile:_.resolved.activeProfile,user:e});else{console.log(te.green("\u2714 Authenticated successfully!")),_.resolved.activeProfile&&console.log(`Profile: ${_.resolved.activeProfile}`);let t=this.extractUserEmail(e.email);console.log(`User: ${e.name} (${t})`);let i=await this.resolveDefaultOrgLabel(_.resolved.org);console.log(`Default Org: ${i}`)}b.debug("[auth] Checking default organization status..."),await Wr(this.client,this.formatter)}catch(e){let t=D(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 Qr=class extends Je{execute(){b.debug("[auth:profile:list] Listing configured authentication profiles...");let e=_.listProfiles(),t=_.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 es=class extends Je{alias;constructor(e,t,i,r=G()){super(t,i,r),this.alias=e}async execute(){b.debug(`[auth:profile:use] Switching active profile to '${this.alias}'...`);let e=_.listProfiles();this.alias in e||(b.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){b.debug(`[auth:profile:use] Verifying token validity for profile '${this.alias}'...`);try{await G({apiUrl:t.apiUrl}).users.me({token:t.token}),b.debug(`[auth:profile:use] Profile '${this.alias}' verified successfully.`)}catch(i){b.debug(`[auth:profile:use] Verification failed for profile '${this.alias}': ${String(i)}`),this.formatter.format!=="json"&&console.warn(te.yellow(`\u26A0 Warning: Token for profile '${this.alias}' appears to be invalid or expired.`))}}_.setActiveProfile(this.alias),b.debug(`[auth:profile:use] Active profile updated to '${this.alias}'.`),this.formatter.success(`Switched to profile '${this.alias}'.`)}};var ts=class extends Je{alias;constructor(e,t,i){super(t,i),this.alias=e}execute(){b.debug(`[auth:profile:delete] Deleting profile '${this.alias}'...`);let e=_.listProfiles();this.alias in e||(b.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=_.getActiveProfile()===this.alias;_.deleteProfile(this.alias),b.debug(`[auth:profile:delete] Profile '${this.alias}' deleted successfully.`),this.formatter.success(`Profile '${this.alias}' deleted.`),t&&!_.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 Bt=class extends Se{client;constructor(e,t,i=G()){super(e,t),this.client=i}ensureAuth(){return Pi(this.client,this.formatter)}getActiveTokenId(){let e=_.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 is=class extends Bt{constructor(e,t,i=G()){super(e,t,i)}async execute(){try{b.debug("[auth:tokens] Listing personal access tokens..."),this.ensureAuth();let e=await this.client.users.listTokens({token:this.client.token});b.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=D(e);this.formatter.error(t),process.exit(1)}}};var rs=class extends Bt{constructor(e,t,i=G()){super(e,t,i)}async execute(){try{b.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});b.debug(`[auth:tokens] Token created successfully with ID="${t.id}"`),this.formatResult(t)}catch(e){let t=D(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){_.resolved.format==="json"?this.formatter.success("Token created successfully!",e):(this.formatter.success("Token created successfully!"),console.log(`
25
+ `+te.yellow("\u26A0 WARNING: Make sure to copy your personal access token now. You will NOT be able to see it again!")+`
26
+ `),console.log(`${te.bold("Raw Token")}: ${te.cyan(e.token)}`),console.log(`${te.bold("ID")}: ${e.id}`),console.log(`${te.bold("Name")}: ${e.name||"N/A"}`),console.log(`${te.bold("Type")}: ${e.type}`),console.log(`${te.bold("Expires At")}: ${e.expiresAt||"Never"}
27
+ `))}};var ss=class extends Bt{id;constructor(e,t,i,r=G()){super(t,i,r),this.id=e}async execute(){try{b.debug(`[auth:tokens] Deleting personal access token with ID="${this.id}"`),this.ensureAuth(),await this.client.users.deleteToken(this.id,{token:this.client.token}),b.debug(`[auth:tokens] Successfully deleted token ID="${this.id}"`),this.formatter.success(`Token '${this.id}' deleted successfully.`)}catch(e){let t=D(e);this.formatter.error(t),process.exit(1)}}};function Ga(n){let e=n.command("tokens").description("Manage personal access tokens");e.command("list").description("List all personal access tokens").action(async t=>{let i=new W({format:_.resolved.format});await new is(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 W({format:_.resolved.format});await new rs(t,i).execute()}),e.command("delete <id>").description("Delete a personal access token by ID").action(async(t,i)=>{let r=new W({format:_.resolved.format});await new ss(t,i,r).execute()})}function Ha(n){let e=n.command("auth").description("Manage CLI authentication");Ga(e),e.command("login").description("Authenticate with the API platform using OAuth2 (google, github, or linkedin)").addArgument(new bc("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 W({format:_.resolved.format});await new Xr(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 W({format:_.resolved.format});new Yr(i,r).execute()}),e.command("status").description("Check current authentication status").action(async i=>{let r=new W({format:_.resolved.format});await new Zr(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 W({format:_.resolved.format});new Qr(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 W({format:_.resolved.format});await new es(i,r,s).execute()}),t.command("delete <name>").description("Delete a configured authentication profile").action((i,r)=>{let s=new W({format:_.resolved.format});new ts(i,r,s).execute()})}var Gt=class extends Se{client;constructor(e,t,i=G()){super(e,t),this.client=i}async fetchOrganizations(){return(await this.client.organizations.list({token:this.client.token})).data||[]}};var os=class extends Gt{constructor(e,t,i=G()){super(e,t,i)}async execute(){b.debug("[orgs:list] Listing all authorized organizations...");try{let e=await this.fetchOrganizations();b.debug(`[orgs:list] Found ${e.length} organizations.`);let t=_.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=D(e);this.formatter.error(t),process.exit(1)}}};var as=class extends Gt{oid;constructor(e,t,i,r=G()){super(t,i,r),this.oid=e}async execute(){b.debug(`[orgs:set-default] Setting default organization ID to '${this.oid}'...`);try{b.debug("[orgs:set-default] Validating organization ID in user's authorized list..."),(await this.fetchOrganizations()).some(i=>i.key===this.oid)||(b.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)),b.debug(`[orgs:set-default] Organization ID validated. Writing 'org' property as '${this.oid}'...`),_.writeOrgToActiveProfile(this.oid),b.debug("[orgs:set-default] Configuration property written successfully."),this.formatter.success(`Default organization ID set to '${this.oid}'.`)}catch(e){let t=D(e);this.formatter.error(t),process.exit(1)}}};var ns=class extends Gt{constructor(e,t,i=G()){super(e,t,i)}async execute(){b.debug("[orgs:default] Retrieving the default configured organization...");try{let e=_.resolved;e.org||(b.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)),b.debug(`[orgs:default] Fetching organization list to validate configured org '${e.org}'...`);let i=(await this.fetchOrganizations()).find(r=>r.key===e.org);i||(b.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)),b.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=D(e);this.formatter.error(t),process.exit(1)}}};function Wa(n){let e=n.command("orgs").description("Manage organization configurations");e.command("list").description("List all organizations you belong to").action(async t=>{let i=new W({format:_.resolved.format});await new os(t,i).execute()}),e.command("set-default <oid>").description("Set your default organization ID").action(async(t,i)=>{let r=new W({format:_.resolved.format});await new as(t,i,r).execute()}),e.command("default").alias("get-default").description("Get the default configured organization").action(async t=>{let i=new W({format:_.resolved.format});await new ns(t,i).execute()})}import Xa from"node:fs";import kc from"node:path";import{nanoid as vc}from"nanoid";var ee=class{constructor(e=G()){this.client=e}client;getFileMetaKind(e){let t=e.toLowerCase();if(t==="api"||t===Lo.toLowerCase())return Lo;if(t==="domain"||t===qt.toLowerCase())return qt;if(t==="folder"||t===Xe.toLowerCase())return Xe;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 b.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 b.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 b.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){b.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=Ct.createSchema({kind:i,info:{name:t.name},key:t.key}),s={};t.parent&&(s.parent=t.parent),b.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 b.debug(`[FileManager:create] Created file metadata successfully. Key: ${a}`),t.mediaContent!==void 0&&(b.debug(`[FileManager:create] Uploading file media for key '${a}'...`),await this.client.files.createMedia(t.mediaContent,e,a,{},{token:this.client.token}),b.debug("[FileManager:create] Media uploaded successfully.")),o}async patchMedia(e,t,i){b.debug(`[FileManager:patchMedia] Sending ${i.patchOps.length} patch op(s) for file ID '${t}' (current version: ${i.version})...`);let r={id:vc(),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=kc.resolve(e.mediaPath);if(b.debug(`[FileManager:parseMediaInput] Reading media file from: ${i}`),!Xa.existsSync(i))throw new Error(`Media file not found at path: ${i}`);t=Xa.readFileSync(i,"utf8")}else e.stdin&&(b.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 Ht=class extends Se{fileManager;constructor(e,t,i=new ee){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){b.debug("[files] ID not provided, fetching files list for interactive selection...");try{let r=await this.fileManager.list(e);r.length>0&&(i=await Ke(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 ls=class extends Ht{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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});b.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=D(t);this.formatter.error(i),process.exit(1)}}};var cs=class extends Ht{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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 be("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 Ke("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=D(r);this.formatter.error({code:"CLI_ERR_API_FAILURE",...o}),process.exit(1)}}};var ds=class extends Ht{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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){b.debug(`[files:read] Fetching media content for file ID '${t}'...`);let r=(await this.fileManager.readMedia(e,t)).media;b.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{b.debug(`[files:read] Fetching metadata for file ID '${t}'...`);let i=await this.fileManager.read(e,t);b.debug("[files:read] Metadata retrieved successfully."),this.formatter.object(i)}}catch(i){let r=D(i);this.formatter.error(r),process.exit(1)}}};function Ya(n){let e=n.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 W({format:_.resolved.format});await new ls(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 W({format:_.resolved.format});await new cs(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 W({format:_.resolved.format});await new ds(t,i).execute()})}var Le=class extends Se{client;fileManager;constructor(e,t,i=G(),r=new ee){super(e,t),this.client=i,this.fileManager=r}resolveVersionOption(e){return e.catalogVersion||e.ver}};var ci=class n{key;get kind(){return jt}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:l="stable",version:c=""}=e;if(["public","private","organization"].indexOf(i)===-1)throw new Error(`Invalid scope: ${i}`);let p={key:t,kind:jt,scope:i,publishedBy:r,createdAt:s,updatedAt:o,catalogKey:a,lifecycle:l,version:c};return typeof e.deprecated=="boolean"&&(p.deprecated=e.deprecated),typeof e.deprecatedAt=="number"&&(p.deprecatedAt=e.deprecatedAt),typeof e.deprecatedBy=="string"&&(p.deprecatedBy=e.deprecatedBy),typeof e.changelog=="string"&&(p.changelog=e.changelog),typeof e.deprecationReason=="string"&&(p.deprecationReason=e.deprecationReason),typeof e.unpublishedAt=="number"&&(p.unpublishedAt=e.unpublishedAt),p}constructor(e={}){let t=n.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:jt,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 y;(function(n){n.User="Semantic#User",n.Address="Semantic#Address",n.Organization="Semantic#Organization",n.Project="Semantic#Project",n.AbstractManyToMany="Semantic#AbstractManyToMany",n.Password="Semantic#Password",n.Username="Semantic#Username",n.CreatedTimestamp="Semantic#CreatedTimestamp",n.UpdatedTimestamp="Semantic#UpdatedTimestamp",n.DeletedTimestamp="Semantic#DeletedTimestamp",n.DeletedFlag="Semantic#DeletedFlag",n.PublicUniqueName="Semantic#PublicUniqueName",n.Title="Semantic#Title",n.Name="Semantic#Name",n.UserRole="Semantic#UserRole",n.OrganizationRole="Semantic#OrganizationRole",n.ProjectRole="Semantic#ProjectRole",n.AssociationRole="Semantic#AssociationRole",n.Status="Semantic#Status",n.Version="Semantic#Version",n.ImageURL="Semantic#ImageURL",n.FileURL="Semantic#FileURL",n.Markdown="Semantic#Markdown",n.HTML="Semantic#HTML",n.GeospatialCoordinates="Semantic#GeospatialCoordinates",n.Email="Semantic#Email",n.Phone="Semantic#Phone",n.Currency="Semantic#Currency",n.URL="Semantic#URL",n.SKU="Semantic#SKU",n.Description="Semantic#Description",n.Summary="Semantic#Summary",n.Calculated="Semantic#Calculated",n.Derived="Semantic#Derived",n.ClientIPAddress="Semantic#ClientIPAddress",n.StreetAddress="Semantic#StreetAddress",n.StreetAddressSupplemental="Semantic#StreetAddressSupplemental",n.City="Semantic#City",n.PostalCode="Semantic#PostalCode",n.Country="Semantic#Country",n.Region="Semantic#Region",n.ResourceOwnerIdentifier="Semantic#ResourceOwnerIdentifier",n.RelationalResourceOwner="Semantic#RelationalResourceOwner",n.OrganizationMembers="Semantic#OrganizationMembers",n.ProjectMembers="Semantic#ProjectMembers",n.OrganizationResource="Semantic#OrganizationResource",n.ProjectResource="Semantic#ProjectResource",n.CreatedBy="Semantic#CreatedBy",n.UpdatedBy="Semantic#UpdatedBy",n.DeletedBy="Semantic#DeletedBy",n.Tags="Semantic#Tags",n.Categories="Semantic#Categories"})(y||(y={}));var q;(function(n){n.Entity="Entity",n.Property="Property",n.Association="Association"})(q||(q={}));var H;(function(n){n.Identity="Identity & Authentication",n.Lifecycle="Timestamps & Versioning",n.Content="Content & Media",n.Business="Business Data",n.Organization="Classification & Organization",n.Location="Location & Geography",n.Contact="Contact Information",n.Computed="Computed Values"})(H||(H={}));var Za=n=>n.scope===q.Entity,ps=n=>n.scope===q.Property,us=n=>n.scope===q.Association,dt={[y.User]:{id:y.User,displayName:"User Entity",scope:q.Entity,description:"System users and accounts",category:H.Identity,hasConfig:!1},[y.Password]:{id:y.Password,displayName:"User Password",scope:q.Property,description:"Secure password field",category:H.Identity,applicableDataTypes:["string"],hasConfig:!0},[y.Username]:{id:y.Username,displayName:"Username",scope:q.Property,description:"User authentication identifier",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.UserRole]:{id:y.UserRole,displayName:"User Role Field",scope:q.Property,description:"User permissions and access level",category:H.Identity,applicableDataTypes:["string"],hasConfig:!0},[y.ResourceOwnerIdentifier]:{id:y.ResourceOwnerIdentifier,displayName:"Resource Owner Identifier",scope:q.Association,description:"Links record to owner user",category:H.Identity,hasConfig:!1},[y.RelationalResourceOwner]:{id:y.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:H.Identity,hasConfig:!1},[y.Organization]:{id:y.Organization,displayName:"Organization Entity",scope:q.Entity,description:"Applied to the top-level Organization entity",category:H.Identity,hasConfig:!0},[y.AbstractManyToMany]:{id:y.AbstractManyToMany,displayName:"Abstract Many-To-Many",scope:q.Association,description:"Hidden parent semantic for all M:N relationships",category:H.Organization,hasConfig:!1,isHidden:!0,isManyToMany:!0},[y.OrganizationMembers]:{id:y.OrganizationMembers,displayName:"Organization Members",scope:q.Association,description:"Applied to the association pointing from Organization to User",category:H.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Organization Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:y.Organization,target:y.User},{parent:y.User,target:y.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:y.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:y.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[y.Project]:{id:y.Project,displayName:"Project Entity",scope:q.Entity,description:"Applied to a Project entity",category:H.Identity,hasConfig:!1},[y.ProjectMembers]:{id:y.ProjectMembers,displayName:"Project Members",scope:q.Association,description:"Applied to the association pointing from Project to User",category:H.Identity,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany,preconditions:[{kind:"associationMultiple",multiple:!0,unmetMessage:"Project Members semantic can only be applied to multi-valued (array) associations."},{kind:"entityPairs",entityPairs:[{parent:y.Project,target:y.User},{parent:y.User,target:y.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:y.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:y.Status}],type:"string",index:!0,required:!0,schema:{enum:["active","inactive","invited"],defaultValue:{type:"literal",value:"invited"}}}}]},[y.OrganizationRole]:{id:y.OrganizationRole,displayName:"Organization Role Property",scope:q.Property,description:"Represents a membership role inside an organization",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.ProjectRole]:{id:y.ProjectRole,displayName:"Project Role Property",scope:q.Property,description:"Represents a membership role inside a project",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.AssociationRole]:{id:y.AssociationRole,displayName:"Association Role Property",scope:q.Property,description:"Represents a membership access role on a many-to-many association",category:H.Identity,applicableDataTypes:["string"],hasConfig:!1},[y.OrganizationResource]:{id:y.OrganizationResource,displayName:"Organization Resources",scope:q.Association,description:"Represents resources owned by an organization",category:H.Identity,hasConfig:!1},[y.ProjectResource]:{id:y.ProjectResource,displayName:"Project Resources",scope:q.Association,description:"Represents resources owned by a project",category:H.Identity,hasConfig:!1},[y.CreatedBy]:{id:y.CreatedBy,displayName:"Created By",scope:q.Association,description:"Links record to the user who created it",category:H.Identity,hasConfig:!1},[y.UpdatedBy]:{id:y.UpdatedBy,displayName:"Updated By",scope:q.Association,description:"Links record to the user who last updated it",category:H.Identity,hasConfig:!1},[y.DeletedBy]:{id:y.DeletedBy,displayName:"Deleted By",scope:q.Association,description:"Links record to the user who soft-deleted it",category:H.Identity,hasConfig:!1},[y.CreatedTimestamp]:{id:y.CreatedTimestamp,displayName:"Creation Timestamp",scope:q.Property,description:"When record was created",category:H.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[y.UpdatedTimestamp]:{id:y.UpdatedTimestamp,displayName:"Update Timestamp",scope:q.Property,description:"When record was last modified",category:H.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[y.DeletedTimestamp]:{id:y.DeletedTimestamp,displayName:"Soft Delete Timestamp",scope:q.Property,description:"When record was marked deleted",category:H.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[y.DeletedFlag]:{id:y.DeletedFlag,displayName:"Soft Delete Flag",scope:q.Property,description:"Mark record as deleted",category:H.Lifecycle,applicableDataTypes:["boolean"],hasConfig:!1},[y.Address]:{id:y.Address,displayName:"Address Entity",scope:q.Entity,description:"Physical address entity",category:H.Contact,hasConfig:!1},[y.StreetAddress]:{id:y.StreetAddress,displayName:"Street Address",scope:q.Property,description:"Street address line",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.StreetAddressSupplemental]:{id:y.StreetAddressSupplemental,displayName:"Street Address Supplemental",scope:q.Property,description:"Supplemental street address line (e.g., Unit, Suite, Apartment, Floor)",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.City]:{id:y.City,displayName:"City",scope:q.Property,description:"City or locality",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.PostalCode]:{id:y.PostalCode,displayName:"Postal Code",scope:q.Property,description:"Postal or zip code",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.Country]:{id:y.Country,displayName:"Country",scope:q.Property,description:"Country name or code",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.Region]:{id:y.Region,displayName:"Region",scope:q.Property,description:"State, province, or region",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.Version]:{id:y.Version,displayName:"Version Number",scope:q.Property,description:"Auto-incrementing version counter",category:H.Lifecycle,applicableDataTypes:["number"],hasConfig:!1},[y.Title]:{id:y.Title,displayName:"Record Title",scope:q.Property,description:"Main title or heading",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Name]:{id:y.Name,displayName:"Name",scope:q.Property,description:"A person or pet name",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Description]:{id:y.Description,displayName:"Description",scope:q.Property,description:"Detailed description text",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Summary]:{id:y.Summary,displayName:"Summary",scope:q.Property,description:"Brief summary text",category:H.Content,applicableDataTypes:["string"],hasConfig:!1},[y.Markdown]:{id:y.Markdown,displayName:"Markdown Content",scope:q.Property,description:"Formatted text content",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.HTML]:{id:y.HTML,displayName:"HTML Content",scope:q.Property,description:"Rich HTML content",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.ImageURL]:{id:y.ImageURL,displayName:"Image URL",scope:q.Property,description:"Link to image file",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.FileURL]:{id:y.FileURL,displayName:"File URL",scope:q.Property,description:"Link to file attachment",category:H.Content,applicableDataTypes:["string"],hasConfig:!0},[y.Status]:{id:y.Status,displayName:"Record Status",scope:q.Property,description:"Current state of record",category:H.Business,applicableDataTypes:["string"],hasConfig:!0},[y.Currency]:{id:y.Currency,displayName:"Currency",scope:q.Property,description:"Monetary value with currency",category:H.Business,applicableDataTypes:["number","string"],hasConfig:!0},[y.SKU]:{id:y.SKU,displayName:"SKU",scope:q.Property,description:"Product identification code",category:H.Business,applicableDataTypes:["string"],hasConfig:!0},[y.Email]:{id:y.Email,displayName:"Email",scope:q.Property,description:"Email address",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.Phone]:{id:y.Phone,displayName:"Phone",scope:q.Property,description:"Phone number",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.URL]:{id:y.URL,displayName:"URL",scope:q.Property,description:"Web address or link",category:H.Contact,applicableDataTypes:["string"],hasConfig:!0},[y.ClientIPAddress]:{id:y.ClientIPAddress,displayName:"Client IP Address",scope:q.Property,description:"Automatically populated client IP address",category:H.Contact,applicableDataTypes:["string"],hasConfig:!1},[y.PublicUniqueName]:{id:y.PublicUniqueName,displayName:"Public Unique Name (Slug)",scope:q.Property,description:"URL-friendly unique identifier",category:H.Organization,applicableDataTypes:["string"],hasConfig:!0},[y.Tags]:{id:y.Tags,displayName:"Tags",scope:q.Association,description:"Enable tagging functionality",category:H.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany},[y.Categories]:{id:y.Categories,displayName:"Categories",scope:q.Association,description:"Enable categorization functionality",category:H.Organization,hasConfig:!0,isManyToMany:!0,inheritsFrom:y.AbstractManyToMany},[y.GeospatialCoordinates]:{id:y.GeospatialCoordinates,displayName:"Geospatial Coordinates",scope:q.Property,description:"Location coordinates",category:H.Location,applicableDataTypes:["string"],hasConfig:!0},[y.Calculated]:{id:y.Calculated,displayName:"Calculated",scope:q.Property,description:"Auto-calculated field value",category:H.Computed,applicableDataTypes:["string","number","boolean","date","datetime","time","binary"],hasConfig:!0},[y.Derived]:{id:y.Derived,displayName:"Derived",scope:q.Property,description:"Value derived from other fields",category:H.Computed,applicableDataTypes:["string"],hasConfig:!0}};var Wo;(function(n){n[n.Initializing=0]="Initializing",n[n.PendingDns=1]="PendingDns",n[n.Issuing=2]="Issuing",n[n.Active=3]="Active",n[n.Error=4]="Error"})(Wo||(Wo={}));var Ae=class n extends Error{static E_VALIDATION_ERROR="E_VALIDATION_ERROR";code=n.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,n)}};function ms(n,e){if(n==="-")return;let t=new Ae([{message:"Invalid pointer",path:`/${n}`}]),{length:i}=n;if(i>1&&n[0]==="0")throw t;let r=+n;if(Number.isNaN(r)||Math.abs(r).toString()!==n||r<0||r>e)throw t}function Ii(n,e){let{length:t}=e,i=n,r;for(let s=0;s<t-1;s++){if(r=e[s],Array.isArray(i))ms(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))ms(r,i.length);else if(typeof i!="object"||i===null)throw new Error("Invalid target");return{token:r,parent:i}}function pt(n,e){let t=e.tokens,i=t.length;if(i===0||i===1&&t[0]==="")throw new Ae([{message:"Cannot walk empty path.",path:e.raw}]);try{let r=Ii(n,t);return{token:r.token,parent:r.parent}}catch{throw new Ae([{message:"Path not found.",path:e.raw}])}}var wc=["boolean","string","number","null"];function Wt(n){let e=typeof n;if(e==="boolean"||e==="string")return e;if(e==="number"&&Number.isFinite(n))return"number";if(e==="object"){if(Array.isArray(n)||n instanceof Set)return"array";if(n instanceof Map)return"object";if(n===null)return"null";if(e==="object")return"object"}}function hs(n){return n===void 0?!0:wc.includes(n)}function Qa(n,e="/"){return n.replace(/~0/g,"~").replace(/~1/g,e)}function Xo(n,e="/"){let t="",i=n;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 _e(n,e="/"){let t="";for(let i=0,r=n.length;i<r;i++)t+=e+Xo(n[i],e);return t}function ut(n,e="/"){if(Array.isArray(n))return n;if(n.length===0)return[];if(n.charAt(0)!==e)throw new Ae([{message:"Invalid pointer.",path:n}]);let t=[""],i=0;for(let r=1,s=n.length;r<s;r++){let o=n.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==="~"?n.charAt(r+1)==="1"?(t[i]+=e,r++):n.charAt(r+1)==="0"?(t[i]+="~",r++):t[i]+=o:t[i]+=o}return t}function fs(n,e,t){let i,r;return typeof n=="string"?i=ut(n,t):i=n,typeof e=="string"?r=[e]:r=e,_e(i.concat(r),t)}function Sc(n,e){if(n instanceof Set){let t=0;for(let i of n)e(i,t+=1)}else if(Array.isArray(n)||n instanceof Map)n.forEach(e);else if(typeof n=="object"&&n!==null)Object.keys(n).forEach(t=>{e(n[t],t)});else throw new TypeError(`${n} is not a structure`)}function en(n,e,t,i){i(n,e,t),!(n===null||typeof n!="object")&&Sc(n,(r,s)=>{en(r,s,n,i)})}function gs(n,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 l=fs(a&&i(a),o);t[l]=s}en(n,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 l=i(a);e(s,fs(l,o.toString()),a,l)}})}var ue=class n{_raw="";_tokens=[];_separator;_index;_parent;constructor(e,t="/"){if(e instanceof n&&e.separator===t)return e;this._separator=t,Array.isArray(e)?(this._tokens=e,this._raw=_e(e,this._separator)):typeof e=="string"?(this._raw=e,this._tokens=ut(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 n(this._tokens.slice(0,-1),this._separator),this._parent)}isRoot(){return this._tokens.length===0||this._tokens[0]===""}append(e){return new n([...this._tokens,String(e)],this._separator)}prefix(e){if(e<0||e>this._tokens.length)throw new Error("Levels out of bound.");return new n(this._tokens.slice(0,e),this._separator)}escape(e){return Xo(e,this._separator)}unescape(e){return Qa(e,this._separator)}static encode(e,t="/"){return _e(e,t)}encode(e=this._separator){return _e(this._tokens,e)}static decode(e,t="/"){return ut(e,t)}find(e){let{tokens:t}=this;if(t.length===0)return e;let i;try{i=Ii(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 n(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 Ae([{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 n(e).getIndex()}setIndex(e){let t=this._tokens,i=t[t.length-1];if(i===void 0)return new n(`/${e}`,this._separator);if(isNaN(+i))return new n([...t,e.toString()],this._separator);let r=Array.from(t);return r[r.length-1]=e.toString(),new n(r,this._separator)}static index(e){let t=Object.create(null);return gs(e,(i,r)=>{t[r]=i}),t}static join(e,t,i){let r,s;if(typeof e=="string"?r=ut(e,i):r=e,typeof t=="string"){if(!t)return _e(r,i);let o=t,a=i||"/";o.startsWith(a)||(o=`${a}${o}`),s=ut(o,i)}else s=t;return _e(r.concat(s),i)}static unflatten(e){let t=Object.keys(e),i=e[""];for(let r of t){if(r==="")continue;let s=ut(r),o=Ii(i,s),{parent:a,token:l}=o;a instanceof Map?a.set(l,e[r]):a instanceof Set?a.add(e[r]):Array.isArray(a)?a.push(e[r]):a[l]=e[r]}return i}static flatten(e){let t=Object.create(null);return gs(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 di(n,e){let t=new ue(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return n;let{parent:i,token:r}=pt(n,t);if(Array.isArray(i))ue.isValidArrayToken(r,i.length);else if(typeof i=="object"&&i!==null&&!(r in i))throw new Ae([{path:`/${r}`,message:"The target does not exists."}]);return i[r]}function bt(n,e,t){let i=new ue(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:n};let{token:s,parent:o}=pt(n,i),a,l;if(Array.isArray(o))s==="-"?(o.push(r),l=o.length-1):o.splice(parseInt(s,10),0,r);else{a=o[s];let c=o;c[s]=r}return{doc:n,previous:a,idx:l}}function Tt(n,e){let t=new ue(e);if(t.tokens.length===0||t.tokens.length===1&&t.tokens[0]==="")return{doc:void 0,previous:n};let{parent:i,token:r}=pt(n,t),s=i[r];if(s===void 0)throw new Ae([{message:"Parent does not exists.",path:t.raw}]);return Array.isArray(i)?i.splice(parseInt(r,10),1):delete i[r],{doc:n,previous:s}}function Ni(n,e,t){let i=new ue(e),r=structuredClone(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:r,previous:n};let{parent:s,token:o}=pt(n,i),a=s[o];if(a===void 0)throw new Ae([{message:"Location not found.",path:i.raw}]);return s[o]=r,{doc:n,previous:a}}function tr(n,e,t){let i=new ue(e),r=new ue(t);if(i.tokens.length===0||i.tokens.length===1&&i.tokens[0]==="")return{doc:Tt(n,i).previous,previous:n};let s=Tt(n,i);return bt(s.doc,r,s.previous)}function $i(n,e,t){let i=new ue(e),r=new ue(t),s=di(n,i);return e===""||e==="/"?{doc:s,previous:n}:bt(n,r,s)}function tn(n){let e=[];return n.forEach(t=>{e.push(t)}),e}function rn(n){let e=Object.create(null);return n.forEach((t,i)=>{e[i]=t}),e}function Yo(n,e,t,i){let r=Wt(n),s=Wt(e);if(r!==s)return!1;switch(r){case"number":return n===0&&1/n===-1/0?e===0&&1/e===-1/0:n===e;case"string":case"null":case"boolean":return n===e;default:}let o,a,l=t.indexOf(n);if(l!==-1)return i[l]===e;if(t.push(n),i.push(e),r==="array"){n instanceof Set&&(n=tn(n)),e instanceof Set&&(e=tn(e));let c=n,p=e;if(c.length!==p.length)return t.pop(),i.pop(),!1;for(o=0,a=c.length;o<a;o++)if(!Yo(c[o],p[o],t,i))return t.pop(),i.pop(),!1;return!0}if(r==="object"){n instanceof Map&&(n=rn(n)),e instanceof Map&&(e=rn(e));let c=n,p=e,u=Object.keys(c),m=Object.keys(p);if(u.length!==m.length)return t.pop(),i.pop(),!1;for(u.sort(),m.sort(),o=0,a=u.length;o<a;o++){let h=u[o],f=m[o];if(h!==f||!Object.prototype.hasOwnProperty.call(p,h)||!Yo(c[h],p[h],t,i))return t.pop(),i.pop(),!1}return t.pop(),i.pop(),!0}return t.pop(),i.pop(),!0}function kt(n,e){return Yo(n,e,[],[])}var ys=class n extends Le{static ALLOWED_SCOPES=["public","organization","private"];static ALLOWED_LIFECYCLES=["dev","beta","stable"];constructor(e,t,i=G(),r=new ee){super(e,t,i,r)}async execute(){let e=this.resolveOrgId(),t=this.resolveVersionOption(this.options);b.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),l=this.validateLifecycle(this.options.lifecycle);try{let c=await this.resolveOrCreateCatalogId(i,e,r,s,o),p=await this.publishVersion(c,o,l,a,this.options.changelog);this.formatter.success(`Successfully published version '${a}' to the data catalog!`,p)}catch(c){let p=D(c);this.formatter.error(p),process.exit(1)}}async resolveFileId(e){let t=this.options.file;if(!t&&process.stdout.isTTY){b.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:qt}},{token:this.client.token})).data||[];r.length>0&&(t=await Ke("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 be("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 be("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 Ke("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)),n.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'.`,detail:`Allowed: ${n.ALLOWED_SCOPES.join(", ")}`}),process.exit(1)),e}async resolveVersion(e){let t=e;return!t&&process.stdout.isTTY&&(t=await be("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 n.ALLOWED_LIFECYCLES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${e}'.`,detail:`Allowed: ${n.ALLOWED_LIFECYCLES.join(", ")}`}),process.exit(1)),e}async resolveOrCreateCatalogId(e,t,i,r,s){b.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,b.debug(`[catalog:publish] Found existing catalog entry key: ${o}`)}catch(a){if(D(a).status!==404)throw a;b.debug("[catalog:publish] Catalog entry does not exist yet.")}if(o)b.debug(`[catalog:publish] Using existing catalog entry key: ${o}`),_.resolved.format!=="json"&&console.log(`Catalog entry already exists (ID: ${o}). Publishing new version...`);else{b.debug("[catalog:publish] Creating a new catalog entry..."),_.resolved.format!=="json"&&console.log("Catalog entry does not exist. Creating new catalog entry...");let a={key:"",kind:ct,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,b.debug(`[catalog:publish] Created new catalog entry with key: ${o}`)}return o}async publishVersion(e,t,i,r,s){let o=ci.createSchema({scope:t,lifecycle:i,version:r,changelog:s||void 0});b.debug(`[catalog:publish] Publishing version '${r}' for catalog key '${e}'...`);let a=await this.client.dataCatalog.publishVersion(e,o,{token:this.client.token});return b.debug(`[catalog:publish] Version published successfully. Version key: ${a.key}`),a}};var bs=class n extends Le{static ALLOWED_SCOPES=["all","public","organization","private"];constructor(e,t,i=G()){super(e,t,i)}async execute(){let e=this.options.org||_.resolved.org;b.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=D(t);this.formatter.error(i),process.exit(1)}}validateScope(e){n.ALLOWED_SCOPES.includes(e)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${e}'. Allowed: ${n.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){b.debug(`[catalog:list] Fetching versions for catalog entry key '${e}'...`);let i=(await this.client.dataCatalog.listVersions(e,{token:this.client.token})).data||[];b.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"){b.debug("[catalog:list] Fetching public catalog entries...");let r=await this.fetchScope("public",t);if(i.push(...r),t){b.debug(`[catalog:list] Fetching organization catalog entries for org '${t}'...`);let s=await this.fetchScope("organization",t);i.push(...s),b.debug(`[catalog:list] Fetching private catalog entries for org '${t}'...`);let o=await this.fetchScope("private",t);i.push(...o)}}else{b.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 b.debug(`[catalog:list] Failed to fetch catalog entries for scope '${e}'.`),[]}}deduplicateEntries(e){b.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 b.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 ks=class extends Le{key;constructor(e,t,i,r=G()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);b.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=D(t);this.formatter.error(i),process.exit(1)}}};var vs=class extends Le{key;constructor(e,t,i,r=G()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options),t=await this.resolveReason();try{if(e){b.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{b.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=D(i);this.formatter.error(r),process.exit(1)}}async resolveReason(){let e=this.options.reason;return!e&&process.stdout.isTTY&&(e=await be("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 ws=class extends Le{key;constructor(e,t,i,r=G()){super(t,i,r),this.key=e}async execute(){let e=this.resolveVersionOption(this.options);try{if(e){b.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{b.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=D(t);this.formatter.error(i),process.exit(1)}}};var Ss=class extends Le{key;constructor(e,t,i,r=G()){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=D(t);this.formatter.error(i),process.exit(1)}}async fetchUsageFiles(e){return e?(b.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})):(b.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 As=class extends Le{fid;constructor(e,t,i,r=G()){super(t,i,r),this.fid=e}async execute(){let e=this.options.org||_.resolved.org;try{b.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=D(t);this.formatter.error(i),process.exit(1)}}};function sn(n){let e=n.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 W({format:_.resolved.format});await new ys(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 W({format:_.resolved.format});await new bs(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 W({format:_.resolved.format});await new ks(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 W({format:_.resolved.format});await new vs(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 W({format:_.resolved.format});await new ws(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 W({format:_.resolved.format});await new Ss(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 W({format:_.resolved.format});await new As(t,i,r).execute()})}import mo from"node:fs";import jl from"node:path";var tt=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 Ec="http://a.ml/",Dt=`${Ec}vocabularies/`,ie=`${Dt}document#`,ke=`${Dt}core#`,oe=`${Dt}security#`,L=`${Dt}apiContract#`,ir=`${Dt}apiBinding#`,X=`${Dt}shapes#`,Ee=`${Dt}data#`,mt=`${Dt}document-source-maps#`,rr="http://www.w3.org/",me=`${rr}ns/shacl#`,Be=`${rr}2001/XMLSchema#`,_s=`${rr}1999/02/22-rdf-syntax-ns#`,Zo=`${rr}2000/01/rdf-schema#`,d={aml:{key:"http://a.ml/",vocabularies:{key:Dt,document:{key:ie,Module:`${ie}Module`,Document:`${ie}Document`,Fragment:`${ie}Fragment`,Unit:`${ie}Unit`,SecuritySchemeFragment:`${ie}SecuritySchemeFragment`,UserDocumentation:`${ie}UserDocumentation`,DataType:`${ie}DataType`,NamedExamples:`${ie}NamedExamples`,DomainElement:`${ie}DomainElement`,DomainProperty:`${ie}DomainProperty`,ParametrizedDeclaration:`${ie}ParametrizedDeclaration`,AbstractDeclaration:`${ie}AbstractDeclaration`,VariableValue:`${ie}VariableValue`,ExternalFragment:`${ie}ExternalFragment`,ExternalDomainElement:`${ie}ExternalDomainElement`,RootDomainElement:`${ie}RootDomainElement`,APIContractProcessingData:`${ie}APIContractProcessingData`,BaseUnitProcessingData:`${ie}BaseUnitProcessingData`,customDomainProperties:`${ie}customDomainProperties`,encodes:`${ie}encodes`,declares:`${ie}declares`,references:`${ie}references`,examples:`${ie}examples`,linkTarget:`${ie}link-target`,linkLabel:`${ie}link-label`,referenceId:`${ie}reference-id`,structuredValue:`${ie}structuredValue`,raw:`${ie}raw`,extends:`${ie}extends`,value:`${ie}value`,name:`${ie}name`,strict:`${ie}strict`,deprecated:`${ie}deprecated`,location:`${ie}location`,variable:`${ie}variable`,target:`${ie}target`,dataNode:`${ie}dataNode`,root:`${ie}root`,usage:`${ie}usage`,version:`${ie}version`},core:{key:ke,CreativeWork:`${ke}CreativeWork`,Parameter:`${ke}Parameter`,Organization:`${ke}Organization`,License:`${ke}License`,Operation:`${ke}Operation`,Response:`${ke}Response`,Payload:`${ke}Payload`,Request:`${ke}Request`,version:`${ke}version`,urlTemplate:`${ke}urlTemplate`,displayName:`${ke}displayName`,title:`${ke}title`,name:`${ke}name`,description:`${ke}description`,documentation:`${ke}documentation`,summary:`${ke}summary`,provider:`${ke}provider`,email:`${ke}email`,url:`${ke}url`,termsOfService:`${ke}termsOfService`,license:`${ke}license`,mediaType:`${ke}mediaType`,extensionName:`${ke}extensionName`,deprecated:`${ke}deprecated`},security:{key:oe,ParametrizedSecurityScheme:`${oe}ParametrizedSecurityScheme`,SecuritySchemeFragment:`${oe}SecuritySchemeFragment`,SecurityScheme:`${oe}SecurityScheme`,OAuth1Settings:`${oe}OAuth1Settings`,OAuth2Settings:`${oe}OAuth2Settings`,OAuth2Flow:`${oe}OAuth2Flow`,Scope:`${oe}Scope`,Settings:`${oe}Settings`,HttpSettings:`${oe}HttpSettings`,ApiKeySettings:`${oe}ApiKeySettings`,OpenIdConnectSettings:`${oe}OpenIdConnectSettings`,SecurityRequirement:`${oe}SecurityRequirement`,security:`${oe}security`,scheme:`${oe}scheme`,schemes:`${oe}schemes`,settings:`${oe}settings`,name:`${oe}name`,type:`${oe}type`,scope:`${oe}scope`,accessTokenUri:`${oe}accessTokenUri`,authorizationUri:`${oe}authorizationUri`,authorizationGrant:`${oe}authorizationGrant`,flows:`${oe}flows`,flow:`${oe}flow`,signature:`${oe}signature`,tokenCredentialsUri:`${oe}tokenCredentialsUri`,requestTokenUri:`${oe}requestTokenUri`,refreshUri:`${oe}refreshUri`,securityRequirement:`${oe}SecurityRequirement`,openIdConnectUrl:`${oe}openIdConnectUrl`,bearerFormat:`${oe}bearerFormat`,in:`${oe}in`},apiContract:{key:L,Payload:`${L}Payload`,Request:`${L}Request`,Response:`${L}Response`,EndPoint:`${L}EndPoint`,Parameter:`${L}Parameter`,Operation:`${L}Operation`,WebAPI:`${L}WebAPI`,API:`${L}API`,AsyncAPI:`${L}AsyncAPI`,UserDocumentationFragment:`${L}UserDocumentationFragment`,Example:`${L}Example`,Server:`${L}Server`,ResourceType:`${L}ResourceType`,Trait:`${L}Trait`,TraitFragment:`${L}TraitFragment`,ParametrizedResourceType:`${L}ParametrizedResourceType`,ParametrizedTrait:`${L}ParametrizedTrait`,Callback:`${L}Callback`,TemplatedLink:`${L}TemplatedLink`,IriTemplateMapping:`${L}IriTemplateMapping`,Tag:`${L}Tag`,Message:`${L}Message`,DomainExtension:`${L}DomainExtension`,Encoding:`${L}Encoding`,header:`${L}header`,parameter:`${L}parameter`,paramName:`${L}paramName`,uriParameter:`${L}uriParameter`,cookieParameter:`${L}cookieParameter`,variable:`${L}variable`,payload:`${L}payload`,server:`${L}server`,path:`${L}path`,url:`${L}url`,scheme:`${L}scheme`,endpoint:`${L}endpoint`,queryString:`${L}queryString`,accepts:`${L}accepts`,guiSummary:`${L}guiSummary`,binding:`${L}binding`,response:`${L}response`,returns:`${L}returns`,expects:`${L}expects`,examples:`${L}examples`,supportedOperation:`${L}supportedOperation`,messageId:`${L}messageId`,statusCode:`${L}statusCode`,method:`${L}method`,required:`${L}required`,callback:`${L}callback`,expression:`${L}expression`,link:`${L}link`,linkExpression:`${L}linkExpression`,templateVariable:`${L}templateVariable`,mapping:`${L}mapping`,operationId:`${L}operationId`,protocol:`${L}protocol`,protocolVersion:`${L}protocolVersion`,headerSchema:`${L}headerSchema`,contentType:`${L}contentType`,allowEmptyValue:`${L}allowEmptyValue`,style:`${L}style`,explode:`${L}explode`,allowReserved:`${L}allowReserved`,tag:`${L}tag`,tags:`${L}tags`},apiBinding:{key:ir,binding:`${ir}binding`,bindings:`${ir}bindings`,messageKey:`${ir}messageKey`,type:`${ir}type`},shapes:{key:X,Shape:`${X}Shape`,ScalarShape:`${X}ScalarShape`,ArrayShape:`${X}ArrayShape`,UnionShape:`${X}UnionShape`,NilShape:`${X}NilShape`,FileShape:`${X}FileShape`,AnyShape:`${X}AnyShape`,SchemaShape:`${X}SchemaShape`,MatrixShape:`${X}MatrixShape`,TupleShape:`${X}TupleShape`,RecursiveShape:`${X}RecursiveShape`,DataTypeFragment:`${X}DataTypeFragment`,XMLSerializer:`${X}XMLSerializer`,number:`${X}number`,integer:`${X}integer`,long:`${X}long`,double:`${X}double`,boolean:`${X}boolean`,float:`${X}float`,nil:`${X}nil`,password:`${X}password`,int32:`${X}int32`,int64:`${X}int64`,uint32:`${X}uint32`,uint64:`${X}uint64`,sint32:`${X}sint32`,sint64:`${X}sint64`,fixed32:`${X}fixed32`,fixed64:`${X}fixed64`,sfixed32:`${X}sfixed32`,sfixed64:`${X}sfixed64`,dateTimeOnly:`${X}dateTimeOnly`,range:`${X}range`,items:`${X}items`,anyOf:`${X}anyOf`,fileType:`${X}fileType`,schema:`${X}schema`,xmlSerialization:`${X}xmlSerialization`,xmlName:`${X}xmlName`,xmlAttribute:`${X}xmlAttribute`,xmlWrapped:`${X}xmlWrapped`,xmlNamespace:`${X}xmlNamespace`,xmlPrefix:`${X}xmlPrefix`,readOnly:`${X}readOnly`,writeOnly:`${X}writeOnly`,deprecated:`${X}deprecated`,fixPoint:`${X}fixPoint`,discriminator:`${X}discriminator`,discriminatorValue:`${X}discriminatorValue`,format:`${X}format`,multipleOf:`${X}multipleOf`,uniqueItems:`${X}uniqueItems`},data:{key:Ee,Scalar:`${Ee}Scalar`,Object:`${Ee}Object`,Array:`${Ee}Array`,Node:`${Ee}Node`,value:`${Ee}value`,type:`${Ee}type`,description:`${Ee}description`,required:`${Ee}required`,displayName:`${Ee}displayName`,minLength:`${Ee}minLength`,maxLength:`${Ee}maxLength`,default:`${Ee}default`,multipleOf:`${Ee}multipleOf`,minimum:`${Ee}minimum`,maximum:`${Ee}maximum`,enum:`${Ee}enum`,pattern:`${Ee}pattern`,items:`${Ee}items`,format:`${Ee}format`,example:`${Ee}example`,examples:`${Ee}examples`},docSourceMaps:{key:mt,SourceMap:`${mt}SourceMap`,sources:`${mt}sources`,element:`${mt}element`,value:`${mt}value`,declaredElement:`${mt}declared-element`,trackedElement:`${mt}tracked-element`,parsedJsonSchema:`${mt}parsed-json-schema`,autoGeneratedName:`${mt}auto-generated-name`,lexical:`${mt}lexical`,synthesizedField:`${mt}synthesized-field`}}},w3:{key:rr,shacl:{key:me,Shape:`${me}Shape`,NodeShape:`${me}NodeShape`,SchemaShape:`${me}SchemaShape`,PropertyShape:`${me}PropertyShape`,in:`${me}in`,defaultValue:`${me}defaultValue`,defaultValueStr:`${me}defaultValueStr`,pattern:`${me}pattern`,minInclusive:`${me}minInclusive`,maxInclusive:`${me}maxInclusive`,multipleOf:`${me}multipleOf`,minLength:`${me}minLength`,maxLength:`${me}maxLength`,fileType:`${me}fileType`,and:`${me}and`,property:`${me}property`,name:`${me}name`,raw:`${me}raw`,datatype:`${me}datatype`,minCount:`${me}minCount`,maxCount:`${me}maxCount`,xone:`${me}xone`,not:`${me}not`,or:`${me}or`,closed:`${me}closed`,path:`${me}path`,additionalPropertiesSchema:`${me}additionalPropertiesSchema`},xmlSchema:{key:Be,boolean:`${Be}boolean`,string:`${Be}string`,number:`${Be}number`,integer:`${Be}integer`,long:`${Be}long`,double:`${Be}double`,float:`${Be}float`,nil:`${Be}nil`,dateTime:`${Be}dateTime`,time:`${Be}time`,date:`${Be}date`,base64Binary:`${Be}base64Binary`,byte:`${Be}byte`},rdfSyntax:{key:_s,Seq:`${_s}Seq`,Property:`${_s}Property`,member:`${_s}member`},rdfSchema:{key:Zo,Seq:`${Zo}Seq`,member:`${Zo}member`}}};function Ri(n,e=0){if(typeof n!="object")return n;let t="",i=new Array(e).fill(" ").join("");return Object.keys(n).forEach(r=>{t+=Array.isArray(n[r])?"":`${i}<${r}>`,Array.isArray(n[r])?n[r].forEach(s=>{t+=i,t+=`<${r}>
28
+ `,t+=Ri({...s},e+1),t+=i,t+=`</${r}>
29
29
  `}):typeof n[r]=="object"?(t+=`
30
- `,t+=Ni({...n[r]},e+1),t+=i):t+=`${n[r]}`,t+=Array.isArray(n[r])?"":`</${r}>
31
- `}),t=t.replace(/<\/?[0-9]{1,}>/g,""),t}function Ss(n,e){return String(e).split(`
30
+ `,t+=Ri({...n[r]},e+1),t+=i):t+=`${n[r]}`,t+=Array.isArray(n[r])?"":`</${r}>
31
+ `}),t=t.replace(/<\/?[0-9]{1,}>/g,""),t}function Es(n,e){return String(e).split(`
32
32
  `).filter(s=>!!s).map(s=>`${n}${s}`).join(`
33
- `)}function qa(n,e){if(typeof n=="number")return n;let t=Number(n);return Number.isNaN(t)?e:t}function Ja(n,e){let t=typeof n;if(t==="boolean")return n;if(t==="string"){let i=n.trim();if(i==="true")return!0;if(i==="false")return!1}return e}function _s(n,e){switch(e){case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:return qa(n,0);case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return Ja(n,!1);case d.w3.xmlSchema.string:case d.aml.vocabularies.shapes.password:return n??"";case d.aml.vocabularies.shapes.nil:case d.w3.xmlSchema.nil:return null;default:return n}}function Ba(n,e=[]){let t;return Array.isArray(e)&&e.length&&(t=n.find(i=>e.includes(i.id))),t||([t]=n),t}function As(n,e){let t=[],{properties:i,inherits:r}=n;i.length&&(t=[...i]),Array.isArray(r)&&r.length&&r.forEach(a=>{let o=a;if(o.types.includes(d.aml.vocabularies.shapes.UnionShape)){let p=o,{anyOf:u=[]}=p;o=Ba(u,e)}if(!o.types.includes(d.w3.shacl.NodeShape))return;let c=As(o);c.length&&(t=t.concat(c))});let s=[];return t.forEach(a=>{s.find(l=>l.name===a.name)||s.push(a)}),s}var Ht=class{processNode(e){let{types:t}=e;if(t.includes(d.aml.vocabularies.data.Scalar))return this.processScalarNode(e);if(t.includes(d.aml.vocabularies.data.Array))return this.processArrayNode(e);if(t.includes(d.aml.vocabularies.data.Object))return this.processObjectNode(e)}processScalarNode(e){return _s(e.value,e.dataType)}processArrayNode(e){let t=[];return e.members.forEach(i=>{let r=this.processNode(i);r!==void 0&&t.push(r)}),t}processObjectNode(e){let t={},{properties:i}=e;return Object.keys(i).forEach(r=>{let s=i[r],a=this.processNode(s);if(typeof a<"u"){let o=this.normalizePropertyName(r);t[o]=a}}),t}normalizePropertyName(e){let t=e;try{t=decodeURIComponent(t)}catch{}return t}};var Ye=class extends Ht{generate(e){let t=this.processNode(e);return!t||typeof t=="string"?t:JSON.stringify(t,null,2)}};var Ve=class extends Ht{generate(e,t,i={}){let r=this.processNode(e);if(!r)return r;let{indent:s=0}=i,a=new Array(s).fill(" ").join("");return t?Array.isArray(r)?r.map(o=>`${a}<${t}>${Ni(o)}</${t}>`).filter(o=>!!o).join(`
34
- `):`${Ni({[t]:r})}`:`${Ni(r,s)}`}};var Je={};Ro(Je,{anyShape:()=>Wt,arrayShape:()=>gd,fileShape:()=>fd,nodeShape:()=>ud,propertyShape:()=>bd,recursiveShape:()=>kd,scalarShape:()=>md,shape:()=>oo,tupleShape:()=>yd,unionShape:()=>hd,xmlSerializer:()=>Yo});var er={};Ro(er,{IAmfAPIContractProcessingDataTypes:()=>Xc,IAmfAnyTypes:()=>Qa,IAmfApiKeySettingsTypes:()=>Mc,IAmfArrayNodeTypes:()=>so,IAmfArrayTypes:()=>Ha,IAmfAsyncApiTypes:()=>pd,IAmfBaseUnitProcessingDataTypes:()=>dd,IAmfCallbackTypes:()=>zc,IAmfCreativeWorkTypes:()=>Hc,IAmfDataTypeFragmentTypes:()=>sd,IAmfDocumentTypes:()=>Gc,IAmfDomainExtensionTypes:()=>Jc,IAmfDomainPropertyTypes:()=>ld,IAmfEncodingTypes:()=>Wc,IAmfEndpointType:()=>Ec,IAmfExampleTypes:()=>kc,IAmfExternalDomainElementTypes:()=>cd,IAmfExternalFragmentTypes:()=>ad,IAmfFileTypes:()=>Za,IAmfHttpSettingsTypes:()=>Dc,IAmfIriTemplateMappingTypes:()=>Fc,IAmfLicenseTypes:()=>Ac,IAmfMessageTypes:()=>qc,IAmfModuleTypes:()=>rd,IAmfNilTypes:()=>yc,IAmfNodeTypes:()=>Wa,IAmfOAuth1SettingsTypes:()=>Tc,IAmfOAuth2FlowTypes:()=>Cc,IAmfOAuth2SettingsTypes:()=>Rc,IAmfObjectNodeTypes:()=>ao,IAmfOpenIdConnectSettingsTypes:()=>Lc,IAmfParameterTypes:()=>Sc,IAmfParametrizedResourceTypeTypes:()=>Zc,IAmfParametrizedSecuritySchemeTypes:()=>Ic,IAmfParametrizedTraitTypes:()=>Qc,IAmfPayloadTypes:()=>Nc,IAmfPropertyTypes:()=>Xa,IAmfProviderTypes:()=>_c,IAmfRdfsSeqType:()=>Yc,IAmfRecursiveTypes:()=>to,IAmfRequestTypes:()=>Pc,IAmfResourceTypeTypes:()=>ed,IAmfResponseTypes:()=>Oc,IAmfScalarNodeTypes:()=>ro,IAmfScalarTypes:()=>Ga,IAmfSchemaTypes:()=>bc,IAmfScopeTypes:()=>Uc,IAmfSecurityRequirementTypes:()=>$c,IAmfSecuritySchemeFragmentTypes:()=>nd,IAmfSecuritySchemeTypes:()=>jc,IAmfServerType:()=>wc,IAmfSourceMapTypes:()=>Bc,IAmfSupportedOperationTypes:()=>xc,IAmfTagTypes:()=>Kc,IAmfTemplatedLinkTypes:()=>Vc,IAmfTraitFragmentTypes:()=>od,IAmfTraitTypes:()=>td,IAmfTupleTypes:()=>eo,IAmfUnionTypes:()=>Ya,IAmfVariableValueTypes:()=>id,IAmfWebApiType:()=>vc,IAmfXmlSerializationTypes:()=>io});var Ga=[d.aml.vocabularies.shapes.ScalarShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Ha=[d.aml.vocabularies.shapes.ArrayShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Wa=[d.w3.shacl.NodeShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Xa=[d.w3.shacl.PropertyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],yc=[d.aml.vocabularies.shapes.NilShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Ya=[d.aml.vocabularies.shapes.UnionShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Za=[d.aml.vocabularies.shapes.FileShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Qa=[d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],bc=[d.aml.vocabularies.shapes.SchemaShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],eo=[d.aml.vocabularies.shapes.TupleShape,d.aml.vocabularies.shapes.ArrayShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],to=[d.aml.vocabularies.shapes.RecursiveShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],io=[d.aml.vocabularies.shapes.XMLSerializer,d.aml.vocabularies.document.DomainElement],ro=[d.aml.vocabularies.data.Scalar,d.aml.vocabularies.data.Node,d.aml.vocabularies.document.DomainElement],so=[d.aml.vocabularies.data.Array,d.w3.rdfSyntax.Seq,d.aml.vocabularies.data.Node,d.aml.vocabularies.document.DomainElement],ao=[d.aml.vocabularies.data.Object,d.aml.vocabularies.data.Node,d.aml.vocabularies.document.DomainElement],kc=[d.aml.vocabularies.apiContract.Example,d.aml.vocabularies.document.DomainElement],vc=[d.aml.vocabularies.apiContract.WebAPI,d.aml.vocabularies.apiContract.API,d.aml.vocabularies.document.RootDomainElement,d.aml.vocabularies.document.DomainElement],wc=[d.aml.vocabularies.apiContract.Server,d.aml.vocabularies.document.DomainElement],Sc=[d.aml.vocabularies.apiContract.Parameter,d.aml.vocabularies.core.Parameter,d.aml.vocabularies.document.DomainElement],_c=[d.aml.vocabularies.core.Organization,d.aml.vocabularies.document.DomainElement],Ac=[d.aml.vocabularies.core.License,d.aml.vocabularies.document.DomainElement],Ec=[d.aml.vocabularies.apiContract.EndPoint,d.aml.vocabularies.document.DomainElement],xc=[d.aml.vocabularies.apiContract.Operation,d.aml.vocabularies.core.Operation,d.aml.vocabularies.document.DomainElement],Pc=[d.aml.vocabularies.apiContract.Request,d.aml.vocabularies.core.Request,d.aml.vocabularies.apiContract.Message,d.aml.vocabularies.document.DomainElement],Oc=[d.aml.vocabularies.apiContract.Response,d.aml.vocabularies.core.Response,d.aml.vocabularies.apiContract.Message,d.aml.vocabularies.document.DomainElement],Nc=[d.aml.vocabularies.apiContract.Payload,d.aml.vocabularies.core.Payload,d.aml.vocabularies.document.DomainElement],$c=[d.aml.vocabularies.security.SecurityRequirement,d.aml.vocabularies.document.DomainElement],Ic=[d.aml.vocabularies.security.ParametrizedSecurityScheme,d.aml.vocabularies.document.DomainElement],jc=[d.aml.vocabularies.security.SecurityScheme,d.aml.vocabularies.document.DomainElement],Rc=[d.aml.vocabularies.security.OAuth2Settings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Cc=[d.aml.vocabularies.security.OAuth2Flow,d.aml.vocabularies.document.DomainElement],Tc=[d.aml.vocabularies.security.OAuth1Settings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Dc=[d.aml.vocabularies.security.HttpSettings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Mc=[d.aml.vocabularies.security.ApiKeySettings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Lc=[d.aml.vocabularies.security.OpenIdConnectSettings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Uc=[d.aml.vocabularies.security.Scope,d.aml.vocabularies.document.DomainElement],zc=[d.aml.vocabularies.apiContract.Callback,d.aml.vocabularies.document.DomainElement],Vc=[d.aml.vocabularies.apiContract.TemplatedLink,d.aml.vocabularies.document.DomainElement],Fc=[d.aml.vocabularies.apiContract.IriTemplateMapping,d.aml.vocabularies.document.DomainElement],Kc=[d.aml.vocabularies.apiContract.Tag,d.aml.vocabularies.document.DomainElement],qc=[d.aml.vocabularies.apiContract.Message,d.aml.vocabularies.document.DomainElement],Jc=[d.aml.vocabularies.apiContract.DomainExtension,d.aml.vocabularies.document.DomainElement],Bc=[d.aml.vocabularies.docSourceMaps.SourceMap],Gc=[d.aml.vocabularies.document.Document,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Module,d.aml.vocabularies.document.Unit],Hc=[d.aml.vocabularies.core.CreativeWork,d.aml.vocabularies.document.DomainElement],Wc=[d.aml.vocabularies.apiContract.Encoding,d.aml.vocabularies.document.DomainElement],Xc=[d.aml.vocabularies.document.APIContractProcessingData],Yc=[d.w3.rdfSchema.Seq],Zc=[d.aml.vocabularies.apiContract.ParametrizedResourceType,d.aml.vocabularies.document.ParametrizedDeclaration,d.aml.vocabularies.document.DomainElement],Qc=[d.aml.vocabularies.apiContract.ParametrizedTrait,d.aml.vocabularies.document.ParametrizedDeclaration,d.aml.vocabularies.document.DomainElement],ed=[d.aml.vocabularies.apiContract.ResourceType,d.aml.vocabularies.document.AbstractDeclaration,d.aml.vocabularies.document.DomainElement],td=[d.aml.vocabularies.apiContract.Trait,d.aml.vocabularies.document.AbstractDeclaration,d.aml.vocabularies.document.DomainElement],id=[d.aml.vocabularies.document.VariableValue,d.aml.vocabularies.document.DomainElement],rd=[d.aml.vocabularies.document.Module,d.aml.vocabularies.document.Unit],sd=[d.aml.vocabularies.shapes.DataTypeFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],ad=[d.aml.vocabularies.document.ExternalFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],od=[d.aml.vocabularies.apiContract.TraitFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],nd=[d.aml.vocabularies.security.SecuritySchemeFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],ld=[d.aml.vocabularies.document.DomainProperty,d.w3.rdfSyntax.Property,d.aml.vocabularies.document.DomainElement],cd=[d.aml.vocabularies.document.ExternalDomainElement,d.aml.vocabularies.document.DomainElement],dd=[d.aml.vocabularies.document.BaseUnitProcessingData],pd=[d.aml.vocabularies.apiContract.AsyncAPI,d.aml.vocabularies.apiContract.API,d.aml.vocabularies.document.RootDomainElement,d.aml.vocabularies.document.DomainElement];function Yo(n){return{id:`xml-serializer-${n}`,types:io,customDomainProperties:[]}}function oo(n){return{id:n,types:[],values:[],inherits:[],or:[],and:[],xone:[],customDomainProperties:[]}}function Wt(n){return{...oo(n),types:Qa,examples:[],xmlSerialization:Yo(n)}}function ud(n){let e=Wt(n);return e.types=Wa,e.id=`node-shape-${n}`,{...e,properties:[],dependencies:[],customShapeProperties:[],customShapePropertyDefinitions:[]}}function md(n){let e=Wt(n);return e.id=`scalar-shape-${n}`,e.types=Ga,e}function hd(n){let e=Wt(n);return e.id=`union-shape-${n}`,e.types=Ya,{...e,anyOf:[]}}function fd(n){let e=Wt(n);return e.id=`file-shape-${n}`,e.types=Za,e}function gd(n){let e=Wt(n);return e.id=`array-shape-${n}`,e.types=Ha,e}function yd(n){let e=Wt(n);return e.id=`tuple-shape-${n}`,e.types=eo,{...e,items:[]}}function bd(n){let e=Wt(n);return e.types=Xa,e}function kd(n,e){return{...oo(n),id:`recursive-${n}`,types:to,fixPoint:e||""}}import{customAlphabet as vd}from"nanoid";var Zo=vd("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var kt=class n{id=Zo();types;name;properties;value;dataType;members;customDomainProperties=[];static scalar(e,t){let i=new n("scalar");return i.value=e,i.dataType=t,i}constructor(e){if(typeof e=="string"){if(e==="scalar")this.types=ro;else if(e==="array")this.types=so;else if(e==="object")this.types=ao;else throw new Error(`Invalid data node init option: ${e}`);return}if(!e)throw new Error("Expected an initialization option.");let t=e,{id:i,types:r,customDomainProperties:s}=t;if(this.id=i,this.types=r,this.customDomainProperties=s,r.includes(d.aml.vocabularies.data.Scalar)){let a=t;this.value=a.value,this.dataType=a.dataType}else if(r.includes(d.aml.vocabularies.data.Object)){let a=t,o={};this.properties=o,Object.keys(a.properties).forEach(l=>{let c=new n(a.properties[l]);o[l]=c})}else if(r.includes(d.aml.vocabularies.data.Array)){let a=t,o=[];this.members=o,Array.isArray(a.members)&&a.members.forEach(l=>{let c=new n(l);o.push(c)})}}toJSON(){let{id:e,customDomainProperties:t,types:i,name:r}=this,s={id:e,types:i,customDomainProperties:t};if(r&&(s.name=r),i.includes(d.aml.vocabularies.data.Scalar)){let a=s;a.dataType=this.dataType,a.value=this.value}else if(i.includes(d.aml.vocabularies.data.Object)){let a=s;a.properties={};let o=this.properties;o&&Object.keys(o).forEach(l=>{a.properties[l]=o[l].toJSON()})}else if(i.includes(d.aml.vocabularies.data.Array)){let a=s;a.members=[],this.members&&this.members.forEach(o=>{a.members.push(o.toJSON())})}return s}addMember(e){if(!this.types.includes(d.aml.vocabularies.data.Array))throw new Error("Not an ArrayNode.");this.members||(this.members=[]),this.members.push(e)}removeMember(e){if(!this.types.includes(d.aml.vocabularies.data.Array))throw new Error("Not an ArrayNode.");if(!this.members)return;let t=this.members.findIndex(i=>i.id===e);t>=0&&this.members.splice(t,1)}addProperty(e,t){if(!this.types.includes(d.aml.vocabularies.data.Object))throw new Error("Not an ObjectNode.");this.properties||(this.properties={}),this.properties[e]=t}removeProperty(e){if(!this.types.includes(d.aml.vocabularies.data.Object))throw new Error("Not an ObjectNode.");this.properties&&delete this.properties[e]}};var Ce=Symbol("nValue"),tr=Symbol("mValue"),Qo=Symbol("matrixAValue"),Es=Symbol("upperMaskValue"),xs=Symbol("lowerMaskValue"),re=Symbol("mtValue"),Ze=Symbol("mtiValue"),Ps=Symbol("instancesValue"),Xt=class n{static[Ps]=new Map;[Ce]=624;[tr]=397;[Qo]=2567483615;[Es]=2147483648;[xs]=2147483647;[re]=new Array(this[Ce]);[Ze]=this[Ce]+1;constructor(e=n.seedFn()){this.initGenRand(e)}static seedFn(){return Math.floor(Math.random()*10**13)}static fromSeed(e=n.seedFn()){if(this[Ps].has(e))return this[Ps].get(e);let t=new n(e);return this[Ps].set(e,t),t}initGenRand(e){let t=e;for(this[re][0]=t>>>0,this[Ze]=1;this[Ze]<this[Ce];this[Ze]++)t=this[re][this[Ze]-1]^this[re][this[Ze]-1]>>>30,this[re][this[Ze]]=(((t&4294901760)>>>16)*1812433253<<16)+(t&65535)*1812433253+this[Ze],this[re][this[Ze]]>>>=0}initByArray(e,t){let i=1,r=0,s;this.initGenRand(19650218);let a=this[Ce]>t?this[Ce]:t;for(;a;a--)s=this[re][i-1]^this[re][i-1]>>>30,this[re][i]=(this[re][i]^(((s&4294901760)>>>16)*1664525<<16)+(s&65535)*1664525)+e[r]+r,this[re][i]>>>=0,i++,r++,i>=this[Ce]&&(this[re][0]=this[re][this[Ce]-1],i=1),r>=t&&(r=0);for(a=this[Ce]-1;a;a--)s=this[re][i-1]^this[re][i-1]>>>30,this[re][i]=(this[re][i]^(((s&4294901760)>>>16)*1566083941<<16)+(s&65535)*1566083941)-i,this[re][i]>>>=0,i++,i>=this[Ce]&&(this[re][0]=this[re][this[Ce]-1],i=1);this[re][0]=2147483648}int32(){let e,t=[0,this[Qo]];if(this[Ze]>=this[Ce]){let i;for(this[Ze]===this[Ce]+1&&this.initGenRand(5489),i=0;i<this[Ce]-this[tr];i++)e=this[re][i]&this[Es]|this[re][i+1]&this[xs],this[re][i]=this[re][i+this[tr]]^e>>>1^t[e&1];for(;i<this[Ce]-1;i++)e=this[re][i]&this[Es]|this[re][i+1]&this[xs],this[re][i]=this[re][i+(this[tr]-this[Ce])]^e>>>1^t[e&1];e=this[re][this[Ce]-1]&this[Es]|this[re][0]&this[xs],this[re][this[Ce]-1]=this[re][this[tr]-1]^e>>>1^t[e&1],this[Ze]=0}return e=this[re][this[Ze]++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,e>>>0}int31(){return this.int32()>>>1}real1(){return this.int32()*(1/4294967295)}random(e=32768,t=0){return Math.floor(this.real2()*(e-t)+t)}real2(){return this.int32()*(1/4294967296)}real3(){return(this.int32()+.5)*(1/4294967296)}res53(){let e=this.int32()>>>5,t=this.int32()>>>6;return(e*67108864+t)*(1/9007199254740992)}};var Os="0123456789",ir="abcdefghijklmnopqrstuvwxyz",Ns=ir.toUpperCase(),no=`${Os}abcdef`;function en(n=""){return n.replace(/ /g,"-").replace(/[^一-龠ぁ-ゔァ-ヴー\w.-]+/g,"")}function vt(n,e={}){let t={};typeof e=="number"?t.max=e:typeof e=="object"&&(t={...e}),typeof t.min!="number"&&(t.min=0),typeof t.max!="number"&&(t.max=99999),typeof t.precision!="number"&&(t.precision=1),t.max>0&&(t.max+=t.precision);let i=Math.floor(n.random(t.max/t.precision,t.min/t.precision));return t.precision===1||(i/=1/t.precision),i}function $s(n,e={}){let t={};return typeof e=="number"?t.precision=e:typeof e=="object"&&(t={...e}),typeof t.precision!="number"&&(t.precision=.01),vt(n,t)}function tn(n,e=10,t){let i=typeof t=="string"?t:Ns+ir,r={min:0,max:i.length-1};return new Array(e).fill("").map(()=>i[vt(n,r)]).join("")}function rn(n,e={}){let t={...e},i;switch(t.casing){case"lower":i=ir;break;case"upper":i=Ns;break;default:i=ir+Ns}if(!t.pool){t.pool="";let r="!@#$%^&*()[]";t.alpha&&(t.pool+=i),t.numeric&&(t.pool+=Os),t.symbols&&(t.pool+=r),t.pool||(t.pool=`${i}${Os}${r}`)}return t.pool.charAt(vt(n,t.pool.length-1))}function sn(n,e={}){let t={};typeof e=="number"?t.max=e:typeof e=="object"&&(t={...e});let i=864e13;(typeof t.min!="number"||t.min<i*-1)&&(t.min=new Date().setFullYear(1970,1,1)),(typeof t.max!="number"||t.max>i)&&(t.max=new Date().setFullYear(2100,1,1));let r=vt(n,t);return new Date(r)}var $i=Symbol("mtValue"),Yt=class{[$i];constructor(e){this[$i]=Xt.fromSeed(e)}seed(e){this[$i]=Xt.fromSeed(e)}pick(e,t){let i=t;typeof i!="number"?i=vt(this[$i],{min:1,max:e.length}):i>e.length?i=e.length:i<0&&(i=0);let r=[...e],s=r.length,a=s-i,o,l;for(;s-- >a;)l=Math.floor((s+1)*$s(this[$i],{min:0,max:.99})),o=r[l],r[l]=r[s],r[s]=o;return r.slice(a)}pickOne(e){let t=vt(this[$i],{max:e.length-1});return e[t]}};var rr=Symbol("randomValue"),wt=Symbol("mtValue"),tt=class{[wt];[rr];constructor(e){this[wt]=Xt.fromSeed(e),this[rr]=new Yt(e)}seed(e){this[wt]=Xt.fromSeed(e),this[rr].seed(e)}number(e={}){return vt(this[wt],e)}float(e={}){return $s(this[wt],e)}datetime(e={}){return sn(this[wt],e)}string(e=10,t){return tn(this[wt],e,t)}character(e={}){return rn(this[wt],e)}uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let i=this.number({min:0,max:15});return(t==="x"?i:i&3|8).toString(16)})}hash(e={}){let{length:t=40,casing:i="lower"}=e,r=i==="upper"?no.toUpperCase():no;return this.string(t,r)}boolean(e={}){let t={};if(typeof e=="number"?t.likelihood=e:typeof e=="object"&&(t={...e}),typeof t.likelihood>"u"&&(t.likelihood=vt(this[wt],{min:0,max:100})),t.likelihood<0||t.likelihood>100)throw new RangeError("Invalid likelihood range. Accepted range is [0, 100].");return this[wt].real2()*100<t.likelihood}falsy(e={}){let t=e.pool||[!1,null,0,NaN,""];return this[rr].pickOne(t)}hexaDecimal(e=1){let t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","A","B","C","D","E","F"];return`0x${this[rr].pick(t,e).join("")}`}};var wd={names:["January","February","March","April","May","June","July","August","September","October","November","December"],abbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},on=wd;var Sd={names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},nn=Sd;var _d={month:on,weekday:nn},ln=_d;var Ad=Object.freeze({consonants:"bcdfghjklmnprstvwz",vowels:"aeiou"}),cn=Ad;var Ed={free:["gmail.com","yahoo.com","hotmail.com"],example:["example.org","example.com","example.net"]},dn=Ed;var xd={suffix:["com","biz","info","name","net","org"]},pn=xd;var Pd=["0therplanet_128.jpg","1markiz_128.jpg","2fockus_128.jpg","8d3k_128.jpg","91bilal_128.jpg","9lessons_128.jpg","AM_Kn2_128.jpg","AlbertoCococi_128.jpg","BenouarradeM_128.jpg","BillSKenney_128.jpg","BrianPurkiss_128.jpg","BroumiYoussef_128.jpg","BryanHorsey_128.jpg","Chakintosh_128.jpg","ChrisFarina78_128.jpg","Elt_n_128.jpg","GavicoInd_128.jpg","HenryHoffman_128.jpg","IsaryAmairani_128.jpg","Karimmove_128.jpg","LucasPerdidao_128.jpg","ManikRathee_128.jpg","RussellBishop_128.jpg","S0ufi4n3_128.jpg","SULiik_128.jpg","Shriiiiimp_128.jpg","Silveredge9_128.jpg","Skyhartman_128.jpg","SlaapMe_128.jpg","Stievius_128.jpg","Talbi_ConSept_128.jpg","VMilescu_128.jpg","VinThomas_128.jpg","YoungCutlass_128.jpg","ZacharyZorbas_128.jpg","_dwite__128.jpg","_kkga_128.jpg","_pedropinho_128.jpg","_ragzor_128.jpg","_scottburgess_128.jpg","_shahedk_128.jpg","_victa_128.jpg","_vojto_128.jpg","_williamguerra_128.jpg","_yardenoon_128.jpg","a1chapone_128.jpg","a_brixen_128.jpg","a_harris88_128.jpg","aaronalfred_128.jpg","aaroni_128.jpg","aaronkwhite_128.jpg","abdots_128.jpg","abdulhyeuk_128.jpg","abdullindenis_128.jpg","abelcabans_128.jpg","abotap_128.jpg","abovefunction_128.jpg","adamawesomeface_128.jpg","adammarsbar_128.jpg","adamnac_128.jpg","adamsxu_128.jpg","adellecharles_128.jpg","ademilter_128.jpg","adhamdannaway_128.jpg","adhiardana_128.jpg","adityasutomo_128.jpg","adobi_128.jpg","adrienths_128.jpg","aeon56_128.jpg","afusinatto_128.jpg","agromov_128.jpg","agustincruiz_128.jpg","ah_lice_128.jpg","ahmadajmi_128.jpg","ahmetalpbalkan_128.jpg","ahmetsulek_128.jpg","aiiaiiaii_128.jpg","ainsleywagon_128.jpg","aio____128.jpg","airskylar_128.jpg","aislinnkelly_128.jpg","ajaxy_ru_128.jpg","aka_james_128.jpg","akashsharma39_128.jpg","akmalfikri_128.jpg","akmur_128.jpg","al_li_128.jpg","alagoon_128.jpg","alan_zhang__128.jpg","albertaugustin_128.jpg","alecarpentier_128.jpg","aleclarsoniv_128.jpg","aleinadsays_128.jpg","alek_djuric_128.jpg","aleksitappura_128.jpg","alessandroribe_128.jpg","alevizio_128.jpg","alexandermayes_128.jpg","alexivanichkin_128.jpg","algunsanabria_128.jpg","allagringaus_128.jpg","allfordesign_128.jpg","allthingssmitty_128.jpg","alsobrooks_128.jpg","alterchuca_128.jpg","aluisio_azevedo_128.jpg","alxleroydeval_128.jpg","alxndrustinov_128.jpg","amandabuzard_128.jpg","amanruzaini_128.jpg","amayvs_128.jpg","amywebbb_128.jpg","anaami_128.jpg","anasnakawa_128.jpg","anatolinicolae_128.jpg","andrea211087_128.jpg","andreas_pr_128.jpg","andresdjasso_128.jpg","andresenfredrik_128.jpg","andrewabogado_128.jpg","andrewarrow_128.jpg","andrewcohen_128.jpg","andrewofficer_128.jpg","andyisonline_128.jpg","andysolomon_128.jpg","andytlaw_128.jpg","angelceballos_128.jpg","angelcolberg_128.jpg","angelcreative_128.jpg","anjhero_128.jpg","ankitind_128.jpg","anoff_128.jpg","anthonysukow_128.jpg","antjanus_128.jpg","antongenkin_128.jpg","antonyryndya_128.jpg","antonyzotov_128.jpg","aoimedia_128.jpg","apriendeau_128.jpg","arashmanteghi_128.jpg","areandacom_128.jpg","areus_128.jpg","ariffsetiawan_128.jpg","ariil_128.jpg","arindam__128.jpg","arishi__128.jpg","arkokoley_128.jpg","aroon_sharma_128.jpg","arpitnj_128.jpg","artd_sign_128.jpg","artem_kostenko_128.jpg","arthurholcombe1_128.jpg","artvavs_128.jpg","ashernatali_128.jpg","ashocka18_128.jpg","atanism_128.jpg","atariboy_128.jpg","ateneupopular_128.jpg","attacks_128.jpg","aviddayentonbay_128.jpg","axel_128.jpg","badlittleduck_128.jpg","bagawarman_128.jpg","baires_128.jpg","balakayuriy_128.jpg","balintorosz_128.jpg","baliomega_128.jpg","baluli_128.jpg","bargaorobalo_128.jpg","barputro_128.jpg","bartjo_128.jpg","bartoszdawydzik_128.jpg","bassamology_128.jpg","batsirai_128.jpg","baumann_alex_128.jpg","baumannzone_128.jpg","bboy1895_128.jpg","bcrad_128.jpg","begreative_128.jpg","belyaev_rs_128.jpg","benefritz_128.jpg","benjamin_knight_128.jpg","bennyjien_128.jpg","benoitboucart_128.jpg","bereto_128.jpg","bergmartin_128.jpg","bermonpainter_128.jpg","bertboerland_128.jpg","besbujupi_128.jpg","beshur_128.jpg","betraydan_128.jpg","beweinreich_128.jpg","bfrohs_128.jpg","bighanddesign_128.jpg","bigmancho_128.jpg","billyroshan_128.jpg","bistrianiosip_128.jpg","blakehawksworth_128.jpg","blakesimkins_128.jpg","bluefx__128.jpg","bluesix_128.jpg","bobbytwoshoes_128.jpg","bobwassermann_128.jpg","bolzanmarco_128.jpg","borantula_128.jpg","borges_marcos_128.jpg","bowbrick_128.jpg","boxmodel_128.jpg","bpartridge_128.jpg","bradenhamm_128.jpg","brajeshwar_128.jpg","brandclay_128.jpg","brandonburke_128.jpg","brandonflatsoda_128.jpg","brandonmorreale_128.jpg","brenmurrell_128.jpg","brenton_clarke_128.jpg","bruno_mart_128.jpg","brunodesign1206_128.jpg","bryan_topham_128.jpg","bu7921_128.jpg","bublienko_128.jpg","buddhasource_128.jpg","buleswapnil_128.jpg","bungiwan_128.jpg","buryaknick_128.jpg","buzzusborne_128.jpg","byrnecore_128.jpg","byryan_128.jpg","cadikkara_128.jpg","calebjoyce_128.jpg","calebogden_128.jpg","canapud_128.jpg","carbontwelve_128.jpg","carlfairclough_128.jpg","carlosblanco_eu_128.jpg","carlosgavina_128.jpg","carlosjgsousa_128.jpg","carlosm_128.jpg","carlyson_128.jpg","caseycavanagh_128.jpg","caspergrl_128.jpg","catadeleon_128.jpg","catarino_128.jpg","cboller1_128.jpg","cbracco_128.jpg","ccinojasso1_128.jpg","cdavis565_128.jpg","cdharrison_128.jpg","ceekaytweet_128.jpg","cemshid_128.jpg","cggaurav_128.jpg","chaabane_wail_128.jpg","chacky14_128.jpg","chadami_128.jpg","chadengle_128.jpg","chaensel_128.jpg","chandlervdw_128.jpg","chanpory_128.jpg","charlesrpratt_128.jpg","charliecwaite_128.jpg","charliegann_128.jpg","chatyrko_128.jpg","cherif_b_128.jpg","chris_frees_128.jpg","chris_witko_128.jpg","chrismj83_128.jpg","chrisslowik_128.jpg","chrisstumph_128.jpg","christianoliff_128.jpg","chrisvanderkooi_128.jpg","ciaranr_128.jpg","cicerobr_128.jpg","claudioguglieri_128.jpg","cloudstudio_128.jpg","clubb3rry_128.jpg","cocolero_128.jpg","codepoet_ru_128.jpg","coderdiaz_128.jpg","codysanfilippo_128.jpg","cofla_128.jpg","colgruv_128.jpg","colirpixoil_128.jpg","collegeman_128.jpg","commadelimited_128.jpg","conspirator_128.jpg","constantx_128.jpg","coreyginnivan_128.jpg","coreyhaggard_128.jpg","coreyweb_128.jpg","craigelimeliah_128.jpg","craighenneberry_128.jpg","craigrcoles_128.jpg","creartinc_128.jpg","croakx_128.jpg","curiousoffice_128.jpg","curiousonaut_128.jpg","cybind_128.jpg","cynthiasavard_128.jpg","cyril_gaillard_128.jpg","d00maz_128.jpg","d33pthought_128.jpg","d_kobelyatsky_128.jpg","d_nny_m_cher_128.jpg","dactrtr_128.jpg","dahparra_128.jpg","dallasbpeters_128.jpg","damenleeturks_128.jpg","danillos_128.jpg","daniloc_128.jpg","danmartin70_128.jpg","dannol_128.jpg","danpliego_128.jpg","danro_128.jpg","dansowter_128.jpg","danthms_128.jpg","danvernon_128.jpg","danvierich_128.jpg","darcystonge_128.jpg","darylws_128.jpg","davecraige_128.jpg","davidbaldie_128.jpg","davidcazalis_128.jpg","davidhemphill_128.jpg","davidmerrique_128.jpg","davidsasda_128.jpg","dawidwu_128.jpg","daykiine_128.jpg","dc_user_128.jpg","dcalonaci_128.jpg","ddggccaa_128.jpg","de_ascanio_128.jpg","deeenright_128.jpg","demersdesigns_128.jpg","denisepires_128.jpg","depaulawagner_128.jpg","derekcramer_128.jpg","derekebradley_128.jpg","derienzo777_128.jpg","desastrozo_128.jpg","designervzm_128.jpg","dev_essentials_128.jpg","devankoshal_128.jpg","deviljho__128.jpg","devinhalladay_128.jpg","dgajjar_128.jpg","dgclegg_128.jpg","dhilipsiva_128.jpg","dhoot_amit_128.jpg","dhooyenga_128.jpg","dhrubo_128.jpg","diansigitp_128.jpg","dicesales_128.jpg","diesellaws_128.jpg","digitalmaverick_128.jpg","dimaposnyy_128.jpg","dingyi_128.jpg","divya_128.jpg","dixchen_128.jpg","djsherman_128.jpg","dmackerman_128.jpg","dmitriychuta_128.jpg","dnezkumar_128.jpg","dnirmal_128.jpg","donjain_128.jpg","doooon_128.jpg","doronmalki_128.jpg","dorphern_128.jpg","dotgridline_128.jpg","dparrelli_128.jpg","dpmachado_128.jpg","dreizle_128.jpg","drewbyreese_128.jpg","dshster_128.jpg","dss49_128.jpg","dudestein_128.jpg","duivvv_128.jpg","dutchnadia_128.jpg","dvdwinden_128.jpg","dzantievm_128.jpg","ecommerceil_128.jpg","eddiechen_128.jpg","edgarchris99_128.jpg","edhenderson_128.jpg","edkf_128.jpg","edobene_128.jpg","eduardostuart_128.jpg","ehsandiary_128.jpg","eitarafa_128.jpg","el_fuertisimo_128.jpg","elbuscainfo_128.jpg","elenadissi_128.jpg","elisabethkjaer_128.jpg","elliotlewis_128.jpg","elliotnolten_128.jpg","embrcecreations_128.jpg","emileboudeling_128.jpg","emmandenn_128.jpg","emmeffess_128.jpg","emsgulam_128.jpg","enda_128.jpg","enjoythetau_128.jpg","enricocicconi_128.jpg","envex_128.jpg","ernestsemerda_128.jpg","erwanhesry_128.jpg","estebanuribe_128.jpg","eugeneeweb_128.jpg","evandrix_128.jpg","evanshajed_128.jpg","exentrich_128.jpg","eyronn_128.jpg","fabbianz_128.jpg","fabbrucci_128.jpg","faisalabid_128.jpg","falconerie_128.jpg","falling_soul_128.jpg","falvarad_128.jpg","felipeapiress_128.jpg","felipecsl_128.jpg","ffbel_128.jpg","finchjke_128.jpg","findingjenny_128.jpg","fiterik_128.jpg","fjaguero_128.jpg","flashmurphy_128.jpg","flexrs_128.jpg","foczzi_128.jpg","fotomagin_128.jpg","fran_mchamy_128.jpg","francis_vega_128.jpg","franciscoamk_128.jpg","frankiefreesbie_128.jpg","fronx_128.jpg","funwatercat_128.jpg","g3d_128.jpg","gaborenton_128.jpg","gabrielizalo_128.jpg","gabrielrosser_128.jpg","ganserene_128.jpg","garand_128.jpg","gauchomatt_128.jpg","gauravjassal_128.jpg","gavr1l0_128.jpg","gcmorley_128.jpg","gearpixels_128.jpg","geneseleznev_128.jpg","geobikas_128.jpg","geran7_128.jpg","geshan_128.jpg","giancarlon_128.jpg","gipsy_raf_128.jpg","giuliusa_128.jpg","gizmeedevil1991_128.jpg","gkaam_128.jpg","gmourier_128.jpg","goddardlewis_128.jpg","gofrasdesign_128.jpg","gojeanyn_128.jpg","gonzalorobaina_128.jpg","grahamkennery_128.jpg","greenbes_128.jpg","gregkilian_128.jpg","gregrwilkinson_128.jpg","gregsqueeb_128.jpg","grrr_nl_128.jpg","gseguin_128.jpg","gt_128.jpg","gu5taf_128.jpg","guiiipontes_128.jpg","guillemboti_128.jpg","guischmitt_128.jpg","gusoto_128.jpg","h1brd_128.jpg","hafeeskhan_128.jpg","hai_ninh_nguyen_128.jpg","haligaliharun_128.jpg","hanna_smi_128.jpg","happypeter1983_128.jpg","harry_sistalam_128.jpg","haruintesettden_128.jpg","hasslunsford_128.jpg","haydn_woods_128.jpg","helderleal_128.jpg","hellofeverrrr_128.jpg","her_ruu_128.jpg","herbigt_128.jpg","herkulano_128.jpg","hermanobrother_128.jpg","herrhaase_128.jpg","heycamtaylor_128.jpg","heyimjuani_128.jpg","heykenneth_128.jpg","hfalucas_128.jpg","hgharrygo_128.jpg","hiemil_128.jpg","hjartstrorn_128.jpg","hoangloi_128.jpg","holdenweb_128.jpg","homka_128.jpg","horaciobella_128.jpg","hota_v_128.jpg","hsinyo23_128.jpg","hugocornejo_128.jpg","hugomano_128.jpg","iamgarth_128.jpg","iamglimy_128.jpg","iamjdeleon_128.jpg","iamkarna_128.jpg","iamkeithmason_128.jpg","iamsteffen_128.jpg","id835559_128.jpg","idiot_128.jpg","iduuck_128.jpg","ifarafonow_128.jpg","igorgarybaldi_128.jpg","illyzoren_128.jpg","ilya_pestov_128.jpg","imammuht_128.jpg","imcoding_128.jpg","imomenui_128.jpg","imsoper_128.jpg","increase_128.jpg","incubo82_128.jpg","instalox_128.jpg","ionuss_128.jpg","ipavelek_128.jpg","iqbalperkasa_128.jpg","iqonicd_128.jpg","irae_128.jpg","isaacfifth_128.jpg","isacosta_128.jpg","ismail_biltagi_128.jpg","isnifer_128.jpg","itolmach_128.jpg","itsajimithing_128.jpg","itskawsar_128.jpg","itstotallyamy_128.jpg","ivanfilipovbg_128.jpg","j04ntoh_128.jpg","j2deme_128.jpg","j_drake__128.jpg","jackiesaik_128.jpg","jacksonlatka_128.jpg","jacobbennett_128.jpg","jagan123_128.jpg","jakemoore_128.jpg","jamiebrittain_128.jpg","janpalounek_128.jpg","jarjan_128.jpg","jarsen_128.jpg","jasonmarkjones_128.jpg","javorszky_128.jpg","jay_wilburn_128.jpg","jayphen_128.jpg","jayrobinson_128.jpg","jcubic_128.jpg","jedbridges_128.jpg","jefffis_128.jpg","jeffgolenski_128.jpg","jehnglynn_128.jpg","jennyshen_128.jpg","jennyyo_128.jpg","jeremery_128.jpg","jeremiaha_128.jpg","jeremiespoken_128.jpg","jeremymouton_128.jpg","jeremyshimko_128.jpg","jeremyworboys_128.jpg","jerrybai1907_128.jpg","jervo_128.jpg","jesseddy_128.jpg","jffgrdnr_128.jpg","jghyllebert_128.jpg","jimmuirhead_128.jpg","jitachi_128.jpg","jjshaw14_128.jpg","jjsiii_128.jpg","jlsolerdeltoro_128.jpg","jm_denis_128.jpg","jmfsocial_128.jpg","jmillspaysbills_128.jpg","jnmnrd_128.jpg","joannefournier_128.jpg","joaoedumedeiros_128.jpg","jodytaggart_128.jpg","joe_black_128.jpg","joelcipriano_128.jpg","joelhelin_128.jpg","joemdesign_128.jpg","joetruesdell_128.jpg","joeymurdah_128.jpg","johannesneu_128.jpg","johncafazza_128.jpg","johndezember_128.jpg","johnriordan_128.jpg","johnsmithagency_128.jpg","joki4_128.jpg","jomarmen_128.jpg","jonathansimmons_128.jpg","jonkspr_128.jpg","jonsgotwood_128.jpg","jordyvdboom_128.jpg","joreira_128.jpg","josecarlospsh_128.jpg","josemarques_128.jpg","josep_martins_128.jpg","josevnclch_128.jpg","joshaustin_128.jpg","joshhemsley_128.jpg","joshmedeski_128.jpg","joshuaraichur_128.jpg","joshuasortino_128.jpg","jpenico_128.jpg","jpscribbles_128.jpg","jqiuss_128.jpg","juamperro_128.jpg","juangomezw_128.jpg","juanmamartinez_128.jpg","juaumlol_128.jpg","judzhin_miles_128.jpg","justinrgraham_128.jpg","justinrhee_128.jpg","justinrob_128.jpg","justme_timothyg_128.jpg","jwalter14_128.jpg","jydesign_128.jpg","kaelifa_128.jpg","kalmerrautam_128.jpg","kamal_chaneman_128.jpg","kanickairaj_128.jpg","kapaluccio_128.jpg","karalek_128.jpg","karlkanall_128.jpg","karolkrakowiak__128.jpg","karsh_128.jpg","karthipanraj_128.jpg","kaspernordkvist_128.jpg","katiemdaly_128.jpg","kaysix_dizzy_128.jpg","kazaky999_128.jpg","kennyadr_128.jpg","kerem_128.jpg","kerihenare_128.jpg","keryilmaz_128.jpg","kevinjohndayy_128.jpg","kevinoh_128.jpg","kevka_128.jpg","keyuri85_128.jpg","kianoshp_128.jpg","kijanmaharjan_128.jpg","kikillo_128.jpg","kimcool_128.jpg","kinday_128.jpg","kirangopal_128.jpg","kiwiupover_128.jpg","kkusaa_128.jpg","klefue_128.jpg","klimmka_128.jpg","knilob_128.jpg","kohette_128.jpg","kojourin_128.jpg","kolage_128.jpg","kolmarlopez_128.jpg","kolsvein_128.jpg","konus_128.jpg","koridhandy_128.jpg","kosmar_128.jpg","kostaspt_128.jpg","krasnoukhov_128.jpg","krystalfister_128.jpg","kucingbelang4_128.jpg","kudretkeskin_128.jpg","kuldarkalvik_128.jpg","kumarrajan12123_128.jpg","kurafire_128.jpg","kurtinc_128.jpg","kushsolitary_128.jpg","kvasnic_128.jpg","ky_128.jpg","kylefoundry_128.jpg","kylefrost_128.jpg","laasli_128.jpg","lanceguyatt_128.jpg","langate_128.jpg","larrybolt_128.jpg","larrygerard_128.jpg","laurengray_128.jpg","lawlbwoy_128.jpg","layerssss_128.jpg","leandrovaranda_128.jpg","lebinoclard_128.jpg","lebronjennan_128.jpg","leehambley_128.jpg","leeiio_128.jpg","leemunroe_128.jpg","leonfedotov_128.jpg","lepetitogre_128.jpg","lepinski_128.jpg","levisan_128.jpg","lewisainslie_128.jpg","lhausermann_128.jpg","liminha_128.jpg","lingeswaran_128.jpg","linkibol_128.jpg","linux29_128.jpg","lisovsky_128.jpg","llun_128.jpg","lmjabreu_128.jpg","loganjlambert_128.jpg","logorado_128.jpg","lokesh_coder_128.jpg","lonesomelemon_128.jpg","longlivemyword_128.jpg","looneydoodle_128.jpg","lososina_128.jpg","louis_currie_128.jpg","low_res_128.jpg","lowie_128.jpg","lu4sh1i_128.jpg","ludwiczakpawel_128.jpg","luxe_128.jpg","lvovenok_128.jpg","m4rio_128.jpg","m_kalibry_128.jpg","ma_tiax_128.jpg","mactopus_128.jpg","macxim_128.jpg","madcampos_128.jpg","madebybrenton_128.jpg","madebyvadim_128.jpg","madewulf_128.jpg","madshensel_128.jpg","madysondesigns_128.jpg","magoo04_128.jpg","magugzbrand2d_128.jpg","mahdif_128.jpg","mahmoudmetwally_128.jpg","maikelk_128.jpg","maiklam_128.jpg","malgordon_128.jpg","malykhinv_128.jpg","mandalareopens_128.jpg","manekenthe_128.jpg","mangosango_128.jpg","manigm_128.jpg","marakasina_128.jpg","marciotoledo_128.jpg","marclgonzales_128.jpg","marcobarbosa_128.jpg","marcomano__128.jpg","marcoramires_128.jpg","marcusgorillius_128.jpg","markjenkins_128.jpg","marklamb_128.jpg","markolschesky_128.jpg","markretzloff_128.jpg","markwienands_128.jpg","marlinjayakody_128.jpg","marosholly_128.jpg","marrimo_128.jpg","marshallchen__128.jpg","martinansty_128.jpg","martip07_128.jpg","mashaaaaal_128.jpg","mastermindesign_128.jpg","matbeedotcom_128.jpg","mateaodviteza_128.jpg","matkins_128.jpg","matt3224_128.jpg","mattbilotti_128.jpg","mattdetails_128.jpg","matthewkay__128.jpg","mattlat_128.jpg","mattsapii_128.jpg","mauriolg_128.jpg","maximseshuk_128.jpg","maximsorokin_128.jpg","maxlinderman_128.jpg","maz_128.jpg","mbilalsiddique1_128.jpg","mbilderbach_128.jpg","mcflydesign_128.jpg","mds_128.jpg","mdsisto_128.jpg","meelford_128.jpg","megdraws_128.jpg","mekal_128.jpg","meln1ks_128.jpg","melvindidit_128.jpg","mfacchinello_128.jpg","mgonto_128.jpg","mhaligowski_128.jpg","mhesslow_128.jpg","mhudobivnik_128.jpg","michaelabehsera_128.jpg","michaelbrooksjr_128.jpg","michaelcolenso_128.jpg","michaelcomiskey_128.jpg","michaelkoper_128.jpg","michaelmartinho_128.jpg","michalhron_128.jpg","michigangraham_128.jpg","michzen_128.jpg","mighty55_128.jpg","miguelkooreman_128.jpg","miguelmendes_128.jpg","mikaeljorhult_128.jpg","mikebeecham_128.jpg","mikemai2awesome_128.jpg","millinet_128.jpg","mirfanqureshi_128.jpg","missaaamy_128.jpg","mizhgan_128.jpg","mizko_128.jpg","mkginfo_128.jpg","mocabyte_128.jpg","mohanrohith_128.jpg","moscoz_128.jpg","motionthinks_128.jpg","moynihan_128.jpg","mr_shiznit_128.jpg","mr_subtle_128.jpg","mrebay007_128.jpg","mrjamesnoble_128.jpg","mrmartineau_128.jpg","mrxloka_128.jpg","mslarkina_128.jpg","msveet_128.jpg","mtolokonnikov_128.jpg","mufaddal_mw_128.jpg","mugukamil_128.jpg","muridrahhal_128.jpg","muringa_128.jpg","murrayswift_128.jpg","mutlu82_128.jpg","mutu_krish_128.jpg","mvdheuvel_128.jpg","mwarkentin_128.jpg","myastro_128.jpg","mylesb_128.jpg","mymyboy_128.jpg","n1ght_coder_128.jpg","n3dmax_128.jpg","n_tassone_128.jpg","nacho_128.jpg","naitanamoreno_128.jpg","namankreative_128.jpg","nandini_m_128.jpg","nasirwd_128.jpg","nastya_mane_128.jpg","nateschulte_128.jpg","nathalie_fs_128.jpg","naupintos_128.jpg","nbirckel_128.jpg","nckjrvs_128.jpg","necodymiconer_128.jpg","nehfy_128.jpg","nellleo_128.jpg","nelshd_128.jpg","nelsonjoyce_128.jpg","nemanjaivanovic_128.jpg","nepdud_128.jpg","nerdgr8_128.jpg","nerrsoft_128.jpg","nessoila_128.jpg","netonet_il_128.jpg","newbrushes_128.jpg","nfedoroff_128.jpg","nickfratter_128.jpg","nicklacke_128.jpg","nicolai_larsen_128.jpg","nicolasfolliot_128.jpg","nicoleglynn_128.jpg","nicollerich_128.jpg","nilshelmersson_128.jpg","nilshoenson_128.jpg","ninjad3m0_128.jpg","nitinhayaran_128.jpg","nomidesigns_128.jpg","normanbox_128.jpg","notbadart_128.jpg","noufalibrahim_128.jpg","noxdzine_128.jpg","nsamoylov_128.jpg","ntfblog_128.jpg","nutzumi_128.jpg","nvkznemo_128.jpg","nwdsha_128.jpg","nyancecom_128.jpg","oaktreemedia_128.jpg","okandungel_128.jpg","okansurreel_128.jpg","okcoker_128.jpg","oksanafrewer_128.jpg","okseanjay_128.jpg","oktayelipek_128.jpg","olaolusoga_128.jpg","olgary_128.jpg","omnizya_128.jpg","ooomz_128.jpg","operatino_128.jpg","opnsrce_128.jpg","orkuncaylar_128.jpg","oscarowusu_128.jpg","oskamaya_128.jpg","oskarlevinson_128.jpg","osmanince_128.jpg","osmond_128.jpg","ostirbu_128.jpg","osvaldas_128.jpg","otozk_128.jpg","ovall_128.jpg","overcloacked_128.jpg","overra_128.jpg","panchajanyag_128.jpg","panghal0_128.jpg","patrickcoombe_128.jpg","paulfarino_128.jpg","pcridesagain_128.jpg","peachananr_128.jpg","pechkinator_128.jpg","peejfancher_128.jpg","pehamondello_128.jpg","perfectflow_128.jpg","perretmagali_128.jpg","petar_prog_128.jpg","petebernardo_128.jpg","peter576_128.jpg","peterlandt_128.jpg","petrangr_128.jpg","phillapier_128.jpg","picard102_128.jpg","pierre_nel_128.jpg","pierrestoffe_128.jpg","pifagor_128.jpg","pixage_128.jpg","plasticine_128.jpg","plbabin_128.jpg","pmeissner_128.jpg","polarity_128.jpg","ponchomendivil_128.jpg","poormini_128.jpg","popey_128.jpg","posterjob_128.jpg","praveen_vijaya_128.jpg","prheemo_128.jpg","primozcigler_128.jpg","prinzadi_128.jpg","privetwagner_128.jpg","prrstn_128.jpg","psaikali_128.jpg","psdesignuk_128.jpg","puzik_128.jpg","pyronite_128.jpg","quailandquasar_128.jpg","r_garcia_128.jpg","r_oy_128.jpg","rachelreveley_128.jpg","rahmeen_128.jpg","ralph_lam_128.jpg","ramanathan_pdy_128.jpg","randomlies_128.jpg","rangafangs_128.jpg","raphaelnikson_128.jpg","raquelwilson_128.jpg","ratbus_128.jpg","rawdiggie_128.jpg","rdbannon_128.jpg","rdsaunders_128.jpg","reabo101_128.jpg","reetajayendra_128.jpg","rehatkathuria_128.jpg","reideiredale_128.jpg","renbyrd_128.jpg","rez___a_128.jpg","ricburton_128.jpg","richardgarretts_128.jpg","richwild_128.jpg","rickdt_128.jpg","rickyyean_128.jpg","rikas_128.jpg","ripplemdk_128.jpg","rmlewisuk_128.jpg","rob_thomas10_128.jpg","robbschiller_128.jpg","robergd_128.jpg","robinclediere_128.jpg","robinlayfield_128.jpg","robturlinckx_128.jpg","rodnylobos_128.jpg","rohixx_128.jpg","romanbulah_128.jpg","roxanejammet_128.jpg","roybarberuk_128.jpg","rpatey_128.jpg","rpeezy_128.jpg","rtgibbons_128.jpg","rtyukmaev_128.jpg","rude_128.jpg","ruehldesign_128.jpg","runningskull_128.jpg","russell_baylis_128.jpg","russoedu_128.jpg","ruzinav_128.jpg","rweve_128.jpg","ryandownie_128.jpg","ryanjohnson_me_128.jpg","ryankirkman_128.jpg","ryanmclaughlin_128.jpg","ryhanhassan_128.jpg","ryuchi311_128.jpg","s4f1_128.jpg","saarabpreet_128.jpg","sachacorazzi_128.jpg","sachingawas_128.jpg","safrankov_128.jpg","sainraja_128.jpg","salimianoff_128.jpg","salleedesign_128.jpg","salvafc_128.jpg","samgrover_128.jpg","samihah_128.jpg","samscouto_128.jpg","samuelkraft_128.jpg","sandywoodruff_128.jpg","sangdth_128.jpg","santi_urso_128.jpg","saschadroste_128.jpg","saschamt_128.jpg","sasha_shestakov_128.jpg","saulihirvi_128.jpg","sawalazar_128.jpg","sawrb_128.jpg","sbtransparent_128.jpg","scips_128.jpg","scott_riley_128.jpg","scottfeltham_128.jpg","scottgallant_128.jpg","scottiedude_128.jpg","scottkclark_128.jpg","scrapdnb_128.jpg","sdidonato_128.jpg","sebashton_128.jpg","sementiy_128.jpg","serefka_128.jpg","sergeyalmone_128.jpg","sergeysafonov_128.jpg","sethlouey_128.jpg","seyedhossein1_128.jpg","sgaurav_baghel_128.jpg","shadeed9_128.jpg","shalt0ni_128.jpg","shaneIxD_128.jpg","shanehudson_128.jpg","sharvin_128.jpg","shesgared_128.jpg","shinze_128.jpg","shoaib253_128.jpg","shojberg_128.jpg","shvelo96_128.jpg","silv3rgvn_128.jpg","silvanmuhlemann_128.jpg","simobenso_128.jpg","sindresorhus_128.jpg","sircalebgrove_128.jpg","skkirilov_128.jpg","slowspock_128.jpg","smaczny_128.jpg","smalonso_128.jpg","smenov_128.jpg","snowshade_128.jpg","snowwrite_128.jpg","sokaniwaal_128.jpg","solid_color_128.jpg","souperphly_128.jpg","souuf_128.jpg","sovesove_128.jpg","soyjavi_128.jpg","spacewood__128.jpg","spbroma_128.jpg","spedwig_128.jpg","sprayaga_128.jpg","sreejithexp_128.jpg","ssbb_me_128.jpg","ssiskind_128.jpg","sta1ex_128.jpg","stalewine_128.jpg","stan_128.jpg","stayuber_128.jpg","stefanotirloni_128.jpg","stefanozoffoli_128.jpg","stefooo_128.jpg","stefvdham_128.jpg","stephcoue_128.jpg","sterlingrules_128.jpg","stevedesigner_128.jpg","steynviljoen_128.jpg","strikewan_128.jpg","stushona_128.jpg","sulaqo_128.jpg","sunlandictwin_128.jpg","sunshinedgirl_128.jpg","superoutman_128.jpg","supervova_128.jpg","supjoey_128.jpg","suprb_128.jpg","sur4dye_128.jpg","surgeonist_128.jpg","suribbles_128.jpg","svenlen_128.jpg","swaplord_128.jpg","sweetdelisa_128.jpg","switmer777_128.jpg","swooshycueb_128.jpg","sydlawrence_128.jpg","syropian_128.jpg","tanveerrao_128.jpg","taybenlor_128.jpg","taylorling_128.jpg","tbakdesigns_128.jpg","teddyzetterlund_128.jpg","teeragit_128.jpg","tereshenkov_128.jpg","terpimost_128.jpg","terrorpixel_128.jpg","terryxlife_128.jpg","teylorfeliz_128.jpg","tgerken_128.jpg","tgormtx_128.jpg","thaisselenator__128.jpg","thaodang17_128.jpg","thatonetommy_128.jpg","the_purplebunny_128.jpg","the_winslet_128.jpg","thedamianhdez_128.jpg","thedjpetersen_128.jpg","thehacker_128.jpg","thekevinjones_128.jpg","themadray_128.jpg","themikenagle_128.jpg","themrdave_128.jpg","theonlyzeke_128.jpg","therealmarvin_128.jpg","thewillbeard_128.jpg","thiagovernetti_128.jpg","thibaut_re_128.jpg","thierrykoblentz_128.jpg","thierrymeier__128.jpg","thimo_cz_128.jpg","thinkleft_128.jpg","thomasgeisen_128.jpg","thomasschrijer_128.jpg","timgthomas_128.jpg","timmillwood_128.jpg","timothycd_128.jpg","timpetricola_128.jpg","tjrus_128.jpg","to_soham_128.jpg","tobysaxon_128.jpg","toddrew_128.jpg","tom_even_128.jpg","tomas_janousek_128.jpg","tonymillion_128.jpg","traneblow_128.jpg","travis_arnold_128.jpg","travishines_128.jpg","tristanlegros_128.jpg","trubeatto_128.jpg","trueblood_33_128.jpg","tumski_128.jpg","tur8le_128.jpg","turkutuuli_128.jpg","tweetubhai_128.jpg","twittypork_128.jpg","txcx_128.jpg","uberschizo_128.jpg","ultragex_128.jpg","umurgdk_128.jpg","unterdreht_128.jpg","urrutimeoli_128.jpg","uxalex_128.jpg","uxpiper_128.jpg","uxward_128.jpg","vanchesz_128.jpg","vaughanmoffitt_128.jpg","vc27_128.jpg","vicivadeline_128.jpg","victorDubugras_128.jpg","victor_haydin_128.jpg","victordeanda_128.jpg","victorerixon_128.jpg","victorquinn_128.jpg","victorstuber_128.jpg","vigobronx_128.jpg","vijaykarthik_128.jpg","vikashpathak18_128.jpg","vikasvinfotech_128.jpg","vimarethomas_128.jpg","vinciarts_128.jpg","vitor376_128.jpg","vitorleal_128.jpg","vivekprvr_128.jpg","vj_demien_128.jpg","vladarbatov_128.jpg","vladimirdevic_128.jpg","vladyn_128.jpg","vlajki_128.jpg","vm_f_128.jpg","vocino_128.jpg","vonachoo_128.jpg","vovkasolovev_128.jpg","vytautas_a_128.jpg","waghner_128.jpg","wake_gs_128.jpg","we_social_128.jpg","wearesavas_128.jpg","weavermedia_128.jpg","webtanya_128.jpg","weglov_128.jpg","wegotvices_128.jpg","wesleytrankin_128.jpg","wikiziner_128.jpg","wiljanslofstra_128.jpg","wim1k_128.jpg","wintopia_128.jpg","woodsman001_128.jpg","woodydotmx_128.jpg","wtrsld_128.jpg","xadhix_128.jpg","xalionmalik_128.jpg","xamorep_128.jpg","xiel_128.jpg","xilantra_128.jpg","xravil_128.jpg","xripunov_128.jpg","xtopherpaul_128.jpg","y2graphic_128.jpg","yalozhkin_128.jpg","yassiryahya_128.jpg","yayteejay_128.jpg","yecidsm_128.jpg","yehudab_128.jpg","yesmeck_128.jpg","yigitpinarbasi_128.jpg","zackeeler_128.jpg","zaki3d_128.jpg","zauerkraut_128.jpg","zforrester_128.jpg","zvchkelly_128.jpg"],un=Pd;var Od={email:dn,domain:pn,avatar:un},mn=Od;var Nd={female:["Mary","Patricia","Linda","Barbara","Elizabeth","Jennifer","Maria","Susan","Margaret","Dorothy","Lisa","Nancy","Karen","Betty","Helen","Sandra","Donna","Carol","Ruth","Sharon","Michelle","Laura","Sarah","Kimberly","Deborah","Jessica","Shirley","Cynthia","Angela","Melissa","Brenda","Amy","Anna","Rebecca","Virginia","Kathleen","Pamela","Martha","Debra","Amanda","Stephanie","Carolyn","Christine","Marie","Janet","Catherine","Frances","Ann","Joyce","Diane","Alice","Julie","Heather","Teresa","Doris","Gloria","Evelyn","Jean","Cheryl","Mildred","Katherine","Joan","Ashley","Judith","Rose","Janice","Kelly","Nicole","Judy","Christina","Kathy","Theresa","Beverly","Denise","Tammy","Irene","Jane","Lori","Rachel","Marilyn","Andrea","Kathryn","Louise","Sara","Anne","Jacqueline","Wanda","Bonnie","Julia","Ruby","Lois","Tina","Phyllis","Norma","Paula","Diana","Annie","Lillian","Emily","Robin","Peggy","Crystal","Gladys","Rita","Dawn","Connie","Florence","Tracy","Edna","Tiffany","Carmen","Rosa","Cindy","Grace","Wendy","Victoria","Edith","Kim","Sherry","Sylvia","Josephine","Thelma","Shannon","Sheila","Ethel","Ellen","Elaine","Marjorie","Carrie","Charlotte","Monica","Esther","Pauline","Emma","Juanita","Anita","Rhonda","Hazel","Amber","Eva","Debbie","April","Leslie","Clara","Lucille","Jamie","Joanne","Eleanor","Valerie","Danielle","Megan","Alicia","Suzanne","Michele","Gail","Bertha","Darlene","Veronica","Jill","Erin","Geraldine","Lauren","Cathy","Joann","Lorraine","Lynn","Sally","Regina","Erica","Beatrice","Dolores","Bernice","Audrey","Yvonne","Annette","June","Samantha","Marion","Dana","Stacy","Ana","Renee","Ida","Vivian","Roberta","Holly","Brittany","Melanie","Loretta","Yolanda","Jeanette","Laurie","Katie","Kristen","Vanessa","Alma","Sue","Elsie","Beth","Jeanne","Vicki","Carla","Tara","Rosemary","Eileen","Terri","Gertrude","Lucy","Tonya","Ella","Stacey","Wilma","Gina","Kristin","Jessie","Natalie","Agnes","Vera","Willie","Charlene","Bessie","Delores","Melinda","Pearl","Arlene","Maureen","Colleen","Allison","Tamara","Joy","Georgia","Constance","Lillie","Claudia","Jackie","Marcia","Tanya","Nellie","Minnie","Marlene","Heidi","Glenda","Lydia","Viola","Courtney","Marian","Stella","Caroline","Dora","Jo","Vickie","Mattie","Terry","Maxine","Irma","Mabel","Marsha","Myrtle","Lena","Christy","Deanna","Patsy","Hilda","Gwendolyn","Jennie","Nora","Margie","Nina","Cassandra","Leah","Penny","Kay","Priscilla","Naomi","Carole","Brandy","Olga","Billie","Dianne","Tracey","Leona","Jenny","Felicia","Sonia","Miriam","Velma","Becky","Bobbie","Violet","Kristina","Toni","Misty","Mae","Shelly","Daisy","Ramona","Sherri","Erika","Katrina","Claire","Lindsey","Lindsay","Geneva","Guadalupe","Belinda","Margarita","Sheryl","Cora","Faye","Ada","Natasha","Sabrina","Isabel","Marguerite","Hattie","Harriet","Molly","Cecilia","Kristi","Brandi","Blanche","Sandy","Rosie","Joanna","Iris","Eunice","Angie","Inez","Lynda","Madeline","Amelia","Alberta","Genevieve","Monique","Jodi","Janie","Maggie","Kayla","Sonya","Jan","Lee","Kristine","Candace","Fannie","Maryann","Opal","Alison","Yvette","Melody","Luz","Susie","Olivia","Flora","Shelley","Kristy","Mamie","Lula","Lola","Verna","Beulah","Antoinette","Candice","Juana","Jeannette","Pam","Kelli","Hannah","Whitney","Bridget","Karla","Celia","Latoya","Patty","Shelia","Gayle","Della","Vicky","Lynne","Sheri","Marianne","Kara","Jacquelyn","Erma","Blanca","Myra","Leticia","Pat","Krista","Roxanne","Angelica","Johnnie","Robyn","Francis","Adrienne","Rosalie","Alexandra","Brooke","Bethany","Sadie","Bernadette","Traci","Jody","Kendra","Jasmine","Nichole","Rachael","Chelsea","Mable","Ernestine","Muriel","Marcella","Elena","Krystal","Angelina","Nadine","Kari","Estelle","Dianna","Paulette","Lora","Mona","Doreen","Rosemarie","Angel","Desiree","Antonia","Hope","Ginger","Janis","Betsy","Christie","Freda","Mercedes","Meredith","Lynette","Teri","Cristina","Eula","Leigh","Meghan","Sophia","Eloise","Rochelle","Gretchen","Cecelia","Raquel","Henrietta","Alyssa","Jana","Kelley","Gwen","Kerry","Jenna","Tricia","Laverne","Olive","Alexis","Tasha","Silvia","Elvira","Casey","Delia","Sophie","Kate","Patti","Lorena","Kellie","Sonja","Lila","Lana","Darla","May","Mindy","Essie","Mandy","Lorene","Elsa","Josefina","Jeannie","Miranda","Dixie","Lucia","Marta","Faith","Lela","Johanna","Shari","Camille","Tami","Shawna","Elisa","Ebony","Melba","Ora","Nettie","Tabitha","Ollie","Jaime","Winifred","Kristie"],male:["James","John","Robert","Michael","William","David","Richard","Charles","Joseph","Thomas","Christopher","Daniel","Paul","Mark","Donald","George","Kenneth","Steven","Edward","Brian","Ronald","Anthony","Kevin","Jason","Matthew","Gary","Timothy","Jose","Larry","Jeffrey","Frank","Scott","Eric","Stephen","Andrew","Raymond","Gregory","Joshua","Jerry","Dennis","Walter","Patrick","Peter","Harold","Douglas","Henry","Carl","Arthur","Ryan","Roger","Joe","Juan","Jack","Albert","Jonathan","Justin","Terry","Gerald","Keith","Samuel","Willie","Ralph","Lawrence","Nicholas","Roy","Benjamin","Bruce","Brandon","Adam","Harry","Fred","Wayne","Billy","Steve","Louis","Jeremy","Aaron","Randy","Howard","Eugene","Carlos","Russell","Bobby","Victor","Martin","Ernest","Phillip","Todd","Jesse","Craig","Alan","Shawn","Clarence","Sean","Philip","Chris","Johnny","Earl","Jimmy","Antonio","Danny","Bryan","Tony","Luis","Mike","Stanley","Leonard","Nathan","Dale","Manuel","Rodney","Curtis","Norman","Allen","Marvin","Vincent","Glenn","Jeffery","Travis","Jeff","Chad","Jacob","Lee","Melvin","Alfred","Kyle","Francis","Bradley","Jesus","Herbert","Frederick","Ray","Joel","Edwin","Don","Eddie","Ricky","Troy","Randall","Barry","Alexander","Bernard","Mario","Leroy","Francisco","Marcus","Micheal","Theodore","Clifford","Miguel","Oscar","Jay","Jim","Tom","Calvin","Alex","Jon","Ronnie","Bill","Lloyd","Tommy","Leon","Derek","Warren","Darrell","Jerome","Floyd","Leo","Alvin","Tim","Wesley","Gordon","Dean","Greg","Jorge","Dustin","Pedro","Derrick","Dan","Lewis","Zachary","Corey","Herman","Maurice","Vernon","Roberto","Clyde","Glen","Hector","Shane","Ricardo","Sam","Rick","Lester","Brent","Ramon","Charlie","Tyler","Gilbert","Gene","Marc","Reginald","Ruben","Brett","Angel","Nathaniel","Rafael","Leslie","Edgar","Milton","Raul","Ben","Chester","Cecil","Duane","Franklin","Andre","Elmer","Brad","Gabriel","Ron","Mitchell","Roland","Arnold","Harvey","Jared","Adrian","Karl","Cory","Claude","Erik","Darryl","Jamie","Neil","Jessie","Christian","Javier","Fernando","Clinton","Ted","Mathew","Tyrone","Darren","Lonnie","Lance","Cody","Julio","Kelly","Kurt","Allan","Nelson","Guy","Clayton","Hugh","Max","Dwayne","Dwight","Armando","Felix","Jimmie","Everett","Jordan","Ian","Wallace","Ken","Bob","Jaime","Casey","Alfredo","Alberto","Dave","Ivan","Johnnie","Sidney","Byron","Julian","Isaac","Morris","Clifton","Willard","Daryl","Ross","Virgil","Andy","Marshall","Salvador","Perry","Kirk","Sergio","Marion","Tracy","Seth","Kent","Terrance","Rene","Eduardo","Terrence","Enrique","Freddie","Wade","Austin","Stuart","Fredrick","Arturo","Alejandro","Jackie","Joey","Nick","Luther","Wendell","Jeremiah","Evan","Julius","Dana","Donnie","Otis","Shannon","Trevor","Oliver","Luke","Homer","Gerard","Doug","Kenny","Hubert","Angelo","Shaun","Lyle","Matt","Lynn","Alfonso","Orlando","Rex","Carlton","Ernesto","Cameron","Neal","Pablo","Lorenzo","Omar","Wilbur","Blake","Grant","Horace","Roderick","Kerry","Abraham","Willis","Rickey","Jean","Ira","Andres","Cesar","Johnathan","Malcolm","Rudolph","Damon","Kelvin","Rudy","Preston","Alton","Archie","Marco","Wm","Pete","Randolph","Garry","Geoffrey","Jonathon","Felipe","Bennie","Gerardo","Ed","Dominic","Robin","Loren","Delbert","Colin","Guillermo","Earnest","Lucas","Benny","Noel","Spencer","Rodolfo","Myron","Edmund","Garrett","Salvatore","Cedric","Lowell","Gregg","Sherman","Wilson","Devin","Sylvester","Kim","Roosevelt","Israel","Jermaine","Forrest","Wilbert","Leland","Simon","Guadalupe","Clark","Irving","Carroll","Bryant","Owen","Rufus","Woodrow","Sammy","Kristopher","Mack","Levi","Marcos","Gustavo","Jake","Lionel","Marty","Taylor","Ellis","Dallas","Gilberto","Clint","Nicolas","Laurence","Ismael","Orville","Drew","Jody","Ervin","Dewey","Al","Wilfred","Josh","Hugo","Ignacio","Caleb","Tomas","Sheldon","Erick","Frankie","Stewart","Doyle","Darrel","Rogelio","Terence","Santiago","Alonzo","Elias","Bert","Elbert","Ramiro","Conrad","Pat","Noah","Grady","Phil","Cornelius","Lamar","Rolando","Clay","Percy","Dexter","Bradford","Merle","Darin","Amos","Terrell","Moses","Irvin","Saul","Roman","Darnell","Randal","Tommie","Timmy","Darrin","Winston","Brendan","Toby","Van","Abel","Dominick","Boyd","Courtney","Jan","Emilio","Elijah","Cary","Domingo","Santos","Aubrey","Emmett","Marlon","Emanuel","Jerald","Edmond"]},hn=Nd;var lo=["Abbott","Abernathy","Abshire","Adams","Altenwerth","Anderson","Ankunding","Armstrong","Auer","Aufderhar","Bahringer","Bailey","Balistreri","Barrows","Bartell","Bartoletti","Barton","Bashirian","Batz","Bauch","Baumbach","Bayer","Beahan","Beatty","Bechtelar","Becker","Bednar","Beer","Beier","Berge","Bergnaum","Bergstrom","Bernhard","Bernier","Bins","Blanda","Blick","Block","Bode","Boehm","Bogan","Bogisich","Borer","Bosco","Botsford","Boyer","Boyle","Bradtke","Brakus","Braun","Breitenberg","Brekke","Brown","Bruen","Buckridge","Carroll","Carter","Cartwright","Casper","Cassin","Champlin","Christiansen","Cole","Collier","Collins","Conn","Connelly","Conroy","Considine","Corkery","Cormier","Corwin","Cremin","Crist","Crona","Cronin","Crooks","Cruickshank","Cummerata","Cummings","Dach","D'Amore","Daniel","Dare","Daugherty","Davis","Deckow","Denesik","Dibbert","Dickens","Dicki","Dickinson","Dietrich","Donnelly","Dooley","Douglas","Doyle","DuBuque","Durgan","Ebert","Effertz","Emard","Emmerich","Erdman","Ernser","Fadel","Fahey","Farrell","Fay","Feeney","Feest","Feil","Ferry","Fisher","Flatley","Frami","Franecki","Friesen","Fritsch","Funk","Gaylord","Gerhold","Gerlach","Gibson","Gislason","Gleason","Gleichner","Glover","Goldner","Goodwin","Gorczany","Gottlieb","Goyette","Grady","Graham","Grant","Green","Greenfelder","Greenholt","Grimes","Gulgowski","Gusikowski","Gutkowski","Gutmann","Haag","Hackett","Hagenes","Hahn","Haley","Halvorson","Hamill","Hammes","Hand","Hane","Hansen","Harber","Harris","Hartmann","Harvey","Hauck","Hayes","Heaney","Heathcote","Hegmann","Heidenreich","Heller","Herman","Hermann","Hermiston","Herzog","Hessel","Hettinger","Hickle","Hilll","Hills","Hilpert","Hintz","Hirthe","Hodkiewicz","Hoeger","Homenick","Hoppe","Howe","Howell","Hudson","Huel","Huels","Hyatt","Jacobi","Jacobs","Jacobson","Jakubowski","Jaskolski","Jast","Jenkins","Jerde","Johns","Johnson","Johnston","Jones","Kassulke","Kautzer","Keebler","Keeling","Kemmer","Kerluke","Kertzmann","Kessler","Kiehn","Kihn","Kilback","King","Kirlin","Klein","Kling","Klocko","Koch","Koelpin","Koepp","Kohler","Konopelski","Koss","Kovacek","Kozey","Krajcik","Kreiger","Kris","Kshlerin","Kub","Kuhic","Kuhlman","Kuhn","Kulas","Kunde","Kunze","Kuphal","Kutch","Kuvalis","Labadie","Lakin","Lang","Langosh","Langworth","Larkin","Larson","Leannon","Lebsack","Ledner","Leffler","Legros","Lehner","Lemke","Lesch","Leuschke","Lind","Lindgren","Littel","Little","Lockman","Lowe","Lubowitz","Lueilwitz","Luettgen","Lynch","Macejkovic","MacGyver","Maggio","Mann","Mante","Marks","Marquardt","Marvin","Mayer","Mayert","McClure","McCullough","McDermott","McGlynn","McKenzie","McLaughlin","Medhurst","Mertz","Metz","Miller","Mills","Mitchell","Moen","Mohr","Monahan","Moore","Morar","Morissette","Mosciski","Mraz","Mueller","Muller","Murazik","Murphy","Murray","Nader","Nicolas","Nienow","Nikolaus","Nitzsche","Nolan","Oberbrunner","O'Connell","O'Conner","O'Hara","O'Keefe","O'Kon","Okuneva","Olson","Ondricka","O'Reilly","Orn","Ortiz","Osinski","Pacocha","Padberg","Pagac","Parisian","Parker","Paucek","Pfannerstill","Pfeffer","Pollich","Pouros","Powlowski","Predovic","Price","Prohaska","Prosacco","Purdy","Quigley","Quitzon","Rath","Ratke","Rau","Raynor","Reichel","Reichert","Reilly","Reinger","Rempel","Renner","Reynolds","Rice","Rippin","Ritchie","Robel","Roberts","Rodriguez","Rogahn","Rohan","Rolfson","Romaguera","Roob","Rosenbaum","Rowe","Ruecker","Runolfsdottir","Runolfsson","Runte","Russel","Rutherford","Ryan","Sanford","Satterfield","Sauer","Sawayn","Schaden","Schaefer","Schamberger","Schiller","Schimmel","Schinner","Schmeler","Schmidt","Schmitt","Schneider","Schoen","Schowalter","Schroeder","Schulist","Schultz","Schumm","Schuppe","Schuster","Senger","Shanahan","Shields","Simonis","Sipes","Skiles","Smith","Smitham","Spencer","Spinka","Sporer","Stamm","Stanton","Stark","Stehr","Steuber","Stiedemann","Stokes","Stoltenberg","Stracke","Streich","Stroman","Strosin","Swaniawski","Swift","Terry","Thiel","Thompson","Tillman","Torp","Torphy","Towne","Toy","Trantow","Tremblay","Treutel","Tromp","Turcotte","Turner","Ullrich","Upton","Vandervort","Veum","Volkman","Von","VonRueden","Waelchi","Walker","Walsh","Walter","Ward","Waters","Watsica","Weber","Wehner","Weimann","Weissnat","Welch","West","White","Wiegand","Wilderman","Wilkinson","Will","Williamson","Willms","Windler","Wintheiser","Wisoky","Wisozk","Witting","Wiza","Wolf","Wolff","Wuckert","Wunsch","Wyman","Yost","Yundt","Zboncak","Zemlak","Ziemann","Zieme","Zulauf"],$d={general:lo,female:lo,male:lo},fn=$d;var Id={binary:["Female","Male"],pool:["Asexual","Female to male trans man","Female to male transgender man","Female to male transsexual man","F2M","Gender neutral","Hermaphrodite","Intersex man","Intersex person","Intersex woman","Male to female trans woman","Male to female transgender woman","Male to female transsexual woman","Man","M2F","Polygender","T* man","T* woman","Two* person","Two-spirit person","Woman","Agender","Androgyne","Androgynes","Androgynous","Bigender","Cis","Cis Female","Cis Male","Cis Man","Cis Woman","Cisgender","Cisgender Female","Cisgender Male","Cisgender Man","Cisgender Woman","Female to Male","FTM","Gender Fluid","Gender Nonconforming","Gender Questioning","Gender Variant","Genderqueer","Intersex","Male to Female","MTF","Neither","Neutrois","Non-binary","Other","Pangender","Trans","Trans Female","Trans Male","Trans Man","Trans Person","Trans*Female","Trans*Male","Trans*Man","Trans*Person","Trans*Woman","Transexual","Transexual Female","Transexual Male","Transexual Man","Transexual Person","Transexual Woman","Transgender Female","Transgender Person","Transmasculine","Two-spirit"]},gn=Id;var jd={descriptor:["Lead","Senior","Direct","Corporate","Dynamic","Future","Product","National","Regional","District","Central","Global","Customer","Investor","Dynamic","International","Legacy","Forward","Internal","Human","Chief","Principal"],level:["Solutions","Program","Brand","Security","Research","Marketing","Directives","Implementation","Integration","Functionality","Response","Paradigm","Tactics","Identity","Markets","Group","Division","Applications","Optimization","Operations","Infrastructure","Intranet","Communications","Web","Branding","Quality","Assurance","Mobility","Accounts","Data","Creative","Configuration","Accountability","Interactions","Factors","Usability","Metrics"],job:["Supervisor","Associate","Executive","Liaison","Officer","Manager","Engineer","Specialist","Director","Coordinator","Administrator","Architect","Analyst","Designer","Planner","Orchestrator","Technician","Developer","Producer","Consultant","Assistant","Facilitator","Agent","Representative","Strategist"]},yn=jd;var co=["Jr.","Sr.","I","II","III","IV","V","MD","DDS","PhD","DVM"],Rd={gender:gn,firstName:hn,lastName:fn,title:yn,suffix:{general:co,female:co,male:co},prefix:{general:["Mr.","Mrs.","Ms.","Miss","Dr."],female:["Mrs.","Ms.","Miss"],male:["Mr.","Dr."]},templates:["#{prefix} #{first_name} #{last_name}","#{first_name} #{last_name} #{suffix}","#{first_name} #{last_name}","#{first_name} #{last_name}","#{male_first_name} #{last_name}","#{female_first_name} #{last_name}"]},bn=Rd;var kn=["abandoned","able","absolute","adorable","adventurous","academic","acceptable","acclaimed","accomplished","accurate","aching","acidic","acrobatic","active","actual","adept","admirable","admired","adolescent","adorable","adored","advanced","afraid","affectionate","aged","aggravating","aggressive","agile","agitated","agonizing","agreeable","ajar","alarmed","alarming","alert","alienated","alive","all","altruistic","amazing","ambitious","ample","amused","amusing","anchored","ancient","angelic","angry","anguished","animated","annual","another","antique","anxious","any","apprehensive","appropriate","apt","arctic","arid","aromatic","artistic","ashamed","assured","astonishing","athletic","attached","attentive","attractive","austere","authentic","authorized","automatic","avaricious","average","aware","awesome","awful","awkward","babyish","bad","back","baggy","bare","barren","basic","beautiful","belated","beloved","beneficial","better","best","bewitched","big","big-hearted","biodegradable","bite-sized","bitter","black","black-and-white","bland","blank","blaring","bleak","blind","blissful","blond","blue","blushing","bogus","boiling","bold","bony","boring","bossy","both","bouncy","bountiful","bowed","brave","breakable","brief","bright","brilliant","brisk","broken","bronze","brown","bruised","bubbly","bulky","bumpy","buoyant","burdensome","burly","bustling","busy","buttery","buzzing","calculating","calm","candid","canine","capital","carefree","careful","careless","caring","cautious","cavernous","celebrated","charming","cheap","cheerful","cheery","chief","chilly","chubby","circular","classic","clean","clear","clear-cut","clever","close","closed","cloudy","clueless","clumsy","cluttered","coarse","cold","colorful","colorless","colossal","comfortable","common","compassionate","competent","complete","complex","complicated","composed","concerned","concrete","confused","conscious","considerate","constant","content","conventional","cooked","cool","cooperative","coordinated","corny","corrupt","costly","courageous","courteous","crafty","crazy","creamy","creative","creepy","criminal","crisp","critical","crooked","crowded","cruel","crushing","cuddly","cultivated","cultured","cumbersome","curly","curvy","cute","cylindrical","damaged","damp","dangerous","dapper","daring","darling","dark","dazzling","dead","deadly","deafening","dear","dearest","decent","decimal","decisive","deep","defenseless","defensive","defiant","deficient","definite","definitive","delayed","delectable","delicious","delightful","delirious","demanding","dense","dental","dependable","dependent","descriptive","deserted","detailed","determined","devoted","different","difficult","digital","diligent","dim","dimpled","dimwitted","direct","disastrous","discrete","disfigured","disgusting","disloyal","dismal","distant","downright","dreary","dirty","disguised","dishonest","dismal","distant","distinct","distorted","dizzy","dopey","doting","double","downright","drab","drafty","dramatic","dreary","droopy","dry","dual","dull","dutiful","each","eager","earnest","early","easy","easy-going","ecstatic","edible","educated","elaborate","elastic","elated","elderly","electric","elegant","elementary","elliptical","embarrassed","embellished","eminent","emotional","empty","enchanted","enchanting","energetic","enlightened","enormous","enraged","entire","envious","equal","equatorial","essential","esteemed","ethical","euphoric","even","evergreen","everlasting","every","evil","exalted","excellent","exemplary","exhausted","excitable","excited","exciting","exotic","expensive","experienced","expert","extraneous","extroverted","extra-large","extra-small","fabulous","failing","faint","fair","faithful","fake","false","familiar","famous","fancy","fantastic","far","faraway","far-flung","far-off","fast","fat","fatal","fatherly","favorable","favorite","fearful","fearless","feisty","feline","female","feminine","few","fickle","filthy","fine","finished","firm","first","firsthand","fitting","fixed","flaky","flamboyant","flashy","flat","flawed","flawless","flickering","flimsy","flippant","flowery","fluffy","fluid","flustered","focused","fond","foolhardy","foolish","forceful","forked","formal","forsaken","forthright","fortunate","fragrant","frail","frank","frayed","free","french","fresh","frequent","friendly","frightened","frightening","frigid","frilly","frizzy","frivolous","front","frosty","frozen","frugal","fruitful","full","fumbling","functional","funny","fussy","fuzzy","gargantuan","gaseous","general","generous","gentle","genuine","giant","giddy","gigantic","gifted","giving","glamorous","glaring","glass","gleaming","gleeful","glistening","glittering","gloomy","glorious","glossy","glum","golden","good","good-natured","gorgeous","graceful","gracious","grand","grandiose","granular","grateful","grave","gray","great","greedy","green","gregarious","grim","grimy","gripping","grizzled","gross","grotesque","grouchy","grounded","growing","growling","grown","grubby","gruesome","grumpy","guilty","gullible","gummy","hairy","half","handmade","handsome","handy","happy","happy-go-lucky","hard","hard-to-find","harmful","harmless","harmonious","harsh","hasty","hateful","haunting","healthy","heartfelt","hearty","heavenly","heavy","hefty","helpful","helpless","hidden","hideous","high","high-level","hilarious","hoarse","hollow","homely","honest","honorable","honored","hopeful","horrible","hospitable","hot","huge","humble","humiliating","humming","humongous","hungry","hurtful","husky","icky","icy","ideal","idealistic","identical","idle","idiotic","idolized","ignorant","ill","illegal","ill-fated","ill-informed","illiterate","illustrious","imaginary","imaginative","immaculate","immaterial","immediate","immense","impassioned","impeccable","impartial","imperfect","imperturbable","impish","impolite","important","impossible","impractical","impressionable","impressive","improbable","impure","inborn","incomparable","incompatible","incomplete","inconsequential","incredible","indelible","inexperienced","indolent","infamous","infantile","infatuated","inferior","infinite","informal","innocent","insecure","insidious","insignificant","insistent","instructive","insubstantial","intelligent","intent","intentional","interesting","internal","international","intrepid","ironclad","irresponsible","irritating","itchy","jaded","jagged","jam-packed","jaunty","jealous","jittery","joint","jolly","jovial","joyful","joyous","jubilant","judicious","juicy","jumbo","junior","jumpy","juvenile","kaleidoscopic","keen","key","kind","kindhearted","kindly","klutzy","knobby","knotty","knowledgeable","knowing","known","kooky","kosher","lame","lanky","large","last","lasting","late","lavish","lawful","lazy","leading","lean","leafy","left","legal","legitimate","light","lighthearted","likable","likely","limited","limp","limping","linear","lined","liquid","little","live","lively","livid","loathsome","lone","lonely","long","long-term","loose","lopsided","lost","loud","lovable","lovely","loving","low","loyal","lucky","lumbering","luminous","lumpy","lustrous","luxurious","mad","made-up","magnificent","majestic","major","male","mammoth","married","marvelous","masculine","massive","mature","meager","mealy","mean","measly","meaty","medical","mediocre","medium","meek","mellow","melodic","memorable","menacing","merry","messy","metallic","mild","milky","mindless","miniature","minor","minty","miserable","miserly","misguided","misty","mixed","modern","modest","moist","monstrous","monthly","monumental","moral","mortified","motherly","motionless","mountainous","muddy","muffled","multicolored","mundane","murky","mushy","musty","muted","mysterious","naive","narrow","nasty","natural","naughty","nautical","near","neat","necessary","needy","negative","neglected","negligible","neighboring","nervous","new","next","nice","nifty","nimble","nippy","nocturnal","noisy","nonstop","normal","notable","noted","noteworthy","novel","noxious","numb","nutritious","nutty","obedient","obese","oblong","oily","oblong","obvious","occasional","odd","oddball","offbeat","offensive","official","old","old-fashioned","only","open","optimal","optimistic","opulent","orange","orderly","organic","ornate","ornery","ordinary","original","other","our","outlying","outgoing","outlandish","outrageous","outstanding","oval","overcooked","overdue","overjoyed","overlooked","palatable","pale","paltry","parallel","parched","partial","passionate","past","pastel","peaceful","peppery","perfect","perfumed","periodic","perky","personal","pertinent","pesky","pessimistic","petty","phony","physical","piercing","pink","pitiful","plain","plaintive","plastic","playful","pleasant","pleased","pleasing","plump","plush","polished","polite","political","pointed","pointless","poised","poor","popular","portly","posh","positive","possible","potable","powerful","powerless","practical","precious","present","prestigious","pretty","precious","previous","pricey","prickly","primary","prime","pristine","private","prize","probable","productive","profitable","profuse","proper","proud","prudent","punctual","pungent","puny","pure","purple","pushy","putrid","puzzled","puzzling","quaint","qualified","quarrelsome","quarterly","queasy","querulous","questionable","quick","quick-witted","quiet","quintessential","quirky","quixotic","quizzical","radiant","ragged","rapid","rare","rash","raw","recent","reckless","rectangular","ready","real","realistic","reasonable","red","reflecting","regal","regular","reliable","relieved","remarkable","remorseful","remote","repentant","required","respectful","responsible","repulsive","revolving","rewarding","rich","rigid","right","ringed","ripe","roasted","robust","rosy","rotating","rotten","rough","round","rowdy","royal","rubbery","rundown","ruddy","rude","runny","rural","rusty","sad","safe","salty","same","sandy","sane","sarcastic","sardonic","satisfied","scaly","scarce","scared","scary","scented","scholarly","scientific","scornful","scratchy","scrawny","second","secondary","second-hand","secret","self-assured","self-reliant","selfish","sentimental","separate","serene","serious","serpentine","several","severe","shabby","shadowy","shady","shallow","shameful","shameless","sharp","shimmering","shiny","shocked","shocking","shoddy","short","short-term","showy","shrill","shy","sick","silent","silky","silly","silver","similar","simple","simplistic","sinful","single","sizzling","skeletal","skinny","sleepy","slight","slim","slimy","slippery","slow","slushy","small","smart","smoggy","smooth","smug","snappy","snarling","sneaky","sniveling","snoopy","sociable","soft","soggy","solid","somber","some","spherical","sophisticated","sore","sorrowful","soulful","soupy","sour","spanish","sparkling","sparse","specific","spectacular","speedy","spicy","spiffy","spirited","spiteful","splendid","spotless","spotted","spry","square","squeaky","squiggly","stable","staid","stained","stale","standard","starchy","stark","starry","steep","sticky","stiff","stimulating","stingy","stormy","straight","strange","steel","strict","strident","striking","striped","strong","studious","stunning","stupendous","stupid","sturdy","stylish","subdued","submissive","substantial","subtle","suburban","sudden","sugary","sunny","super","superb","superficial","superior","supportive","sure-footed","surprised","suspicious","svelte","sweaty","sweet","sweltering","swift","sympathetic","tall","talkative","tame","tan","tangible","tart","tasty","tattered","taut","tedious","teeming","tempting","tender","tense","tepid","terrible","terrific","testy","thankful","that","these","thick","thin","third","thirsty","this","thorough","thorny","those","thoughtful","threadbare","thrifty","thunderous","tidy","tight","timely","tinted","tiny","tired","torn","total","tough","traumatic","treasured","tremendous","tragic","trained","tremendous","triangular","tricky","trifling","trim","trivial","troubled","true","trusting","trustworthy","trusty","truthful","tubby","turbulent","twin","ugly","ultimate","unacceptable","unaware","uncomfortable","uncommon","unconscious","understated","unequaled","uneven","unfinished","unfit","unfolded","unfortunate","unhappy","unhealthy","uniform","unimportant","unique","united","unkempt","unknown","unlawful","unlined","unlucky","unnatural","unpleasant","unrealistic","unripe","unruly","unselfish","unsightly","unsteady","unsung","untidy","untimely","untried","untrue","unused","unusual","unwelcome","unwieldy","unwilling","unwitting","unwritten","upbeat","upright","upset","urban","usable","used","useful","useless","utilized","utter","vacant","vague","vain","valid","valuable","vapid","variable","vast","velvety","venerated","vengeful","verifiable","vibrant","vicious","victorious","vigilant","vigorous","villainous","violet","violent","virtual","virtuous","visible","vital","vivacious","vivid","voluminous","wan","warlike","warm","warmhearted","warped","wary","wasteful","watchful","waterlogged","watery","wavy","wealthy","weak","weary","webbed","wee","weekly","weepy","weighty","weird","welcome","well-documented","well-groomed","well-informed","well-lit","well-made","well-off","well-to-do","well-worn","wet","which","whimsical","whirlwind","whispered","white","whole","whopping","wicked","wide","wide-eyed","wiggly","wild","willing","wilted","winding","windy","winged","wiry","wise","witty","wobbly","woeful","wonderful","wooden","woozy","wordy","worldly","worn","worried","worrisome","worse","worst","worthless","worthwhile","worthy","wrathful","wretched","writhing","wrong","wry","yawning","yearly","yellow","yellowish","young","youthful","yummy","zany","zealous","zesty","zigzag"];var vn=["abnormally","absentmindedly","accidentally","acidly","actually","adventurously","afterwards","almost","always","angrily","annually","anxiously","arrogantly","awkwardly","badly","bashfully","beautifully","bitterly","bleakly","blindly","blissfully","boastfully","boldly","bravely","briefly","brightly","briskly","broadly","busily","calmly","carefully","carelessly","cautiously","certainly","cheerfully","clearly","cleverly","closely","coaxingly","colorfully","commonly","continually","coolly","correctly","courageously","crossly","cruelly","curiously","daily","daintily","dearly","deceivingly","deeply","defiantly","deliberately","delightfully","diligently","dimly","doubtfully","dreamily","easily","elegantly","energetically","enormously","enthusiastically","equally","especially","even","evenly","eventually","exactly","excitedly","extremely","fairly","faithfully","famously","far","fast","fatally","ferociously","fervently","fiercely","fondly","foolishly","fortunately","frankly","frantically","freely","frenetically","frightfully","fully","furiously","generally","generously","gently","gladly","gleefully","gracefully","gratefully","greatly","greedily","happily","hastily","healthily","heavily","helpfully","helplessly","highly","honestly","hopelessly","hourly","hungrily","immediately","innocently","inquisitively","instantly","intensely","intently","interestingly","inwardly","irritably","jaggedly","jealously","joshingly","jovially","joyfully","joyously","jubilantly","judgementally","justly","keenly","kiddingly","kindheartedly","kindly","kissingly","knavishly","knottily","knowingly","knowledgeably","kookily","lazily","less","lightly","likely","limply","lively","loftily","longingly","loosely","loudly","lovingly","loyally","madly","majestically","meaningfully","mechanically","merrily","miserably","mockingly","monthly","more","mortally","mostly","mysteriously","naturally","nearly","neatly","needily","nervously","never","nicely","noisily","not","obediently","obnoxiously","oddly","offensively","officially","often","only","openly","optimistically","overconfidently","owlishly","painfully","partially","patiently","perfectly","physically","playfully","politely","poorly","positively","potentially","powerfully","promptly","properly","punctually","quaintly","quarrelsomely","queasily","queerly","questionably","questioningly","quicker","quickly","quietly","quirkily","quizzically","rapidly","rarely","readily","really","reassuringly","recklessly","regularly","reluctantly","repeatedly","reproachfully","restfully","righteously","rightfully","rigidly","roughly","rudely","sadly","safely","scarcely","scarily","searchingly","sedately","seemingly","seldom","selfishly","separately","seriously","shakily","sharply","sheepishly","shrilly","shyly","silently","sleepily","slowly","smoothly","softly","solemnly","solidly","sometimes","soon","speedily","stealthily","sternly","strictly","successfully","suddenly","surprisingly","suspiciously","sweetly","swiftly","sympathetically","tenderly","tensely","terribly","thankfully","thoroughly","thoughtfully","tightly","tomorrow","too","tremendously","triumphantly","truly","truthfully","ultimately","unabashedly","unaccountably","unbearably","unethically","unexpectedly","unfortunately","unimpressively","unnaturally","unnecessarily","upbeat","upliftingly","upright","upside-down","upward","upwardly","urgently","usefully","uselessly","usually","utterly","vacantly","vaguely","vainly","valiantly","vastly","verbally","very","viciously","victoriously","violently","vivaciously","voluntarily","warmly","weakly","wearily","well","wetly","wholly","wildly","willfully","wisely","woefully","wonderfully","worriedly","wrongly","yawningly","yearly","yearningly","yesterday","yieldingly","youthfully"];var wn=["after","after all","although","and","as","as a result","as if","as long as","as much as","as soon as","as though","because","before","but","consequently","even","even if","even though","finally","for","for example","furthermore","hence","however","if","if only","if then","if when","in addition","in fact","in order that","inasmuch","incidentally","indeed","instead","just as","lest","likewise","meanwhile","nor","now","now since","now that","now when","once","or","provided","provided that","rather than","since","so","so that","supposing","that","though","until","whenever","whereas","wherever","which","who","yet"];var Sn=["yuck","oh","phooey","blah","boo","whoa","yowza","huzzah","boo hoo","fooey","geez","pfft","ew","ah","yum","brr","hm","yahoo","aha","woot","drat","gah","meh","psst","aw","ugh","yippee","eek","gee","bah","gadzooks","duh","ha","mmm","tsk tsk","ouch","phew","ack","uh-huh","gosh","hmph","pish","zowie","er","ick","oof","um"];var _n=["ATM","CD","SUV","TV","aardvark","abacus","abbey","abbreviation","abdomen","ability","abnormality","abolishment","abortion","abrogation","absence","abundance","abuse","academics","academy","accelerant","accelerator","accent","acceptance","access","accessory","accident","accommodation","accompanist","accomplishment","accord","accordance","accordion","account","accountability","accountant","accounting","accuracy","accusation","acetate","achievement","achiever","acid","acknowledgment","acorn","acoustics","acquaintance","acquisition","acre","acrylic","act","action","activation","activist","activity","actor","actress","acupuncture","ad","adaptation","adapter","addiction","addition","address","adjective","adjustment","admin","administration","administrator","admire","admission","adobe","adoption","adrenalin","adrenaline","adult","adulthood","advance","advancement","advantage","advent","adverb","advertisement","advertising","advice","adviser","advocacy","advocate","affair","affect","affidavit","affiliate","affinity","afoul","afterlife","aftermath","afternoon","aftershave","aftershock","afterthought","age","agency","agenda","agent","aggradation","aggression","aglet","agony","agreement","agriculture","aid","aide","aim","air","airbag","airbus","aircraft","airfare","airfield","airforce","airline","airmail","airman","airplane","airport","airship","airspace","alarm","alb","albatross","album","alcohol","alcove","alder","ale","alert","alfalfa","algebra","algorithm","alias","alibi","alien","allegation","allergist","alley","alliance","alligator","allocation","allowance","alloy","alluvium","almanac","almighty","almond","alpaca","alpenglow","alpenhorn","alpha","alphabet","altar","alteration","alternative","altitude","alto","aluminium","aluminum","amazement","amazon","ambassador","amber","ambience","ambiguity","ambition","ambulance","amendment","amenity","ammunition","amnesty","amount","amusement","anagram","analgesia","analog","analogue","analogy","analysis","analyst","analytics","anarchist","anarchy","anatomy","ancestor","anchovy","android","anesthesiologist","anesthesiology","angel","anger","angina","angiosperm","angle","angora","angstrom","anguish","animal","anime","anise","ankle","anklet","anniversary","announcement","annual","anorak","answer","ant","anteater","antecedent","antechamber","antelope","antennae","anterior","anthropology","antibody","anticipation","anticodon","antigen","antique","antiquity","antler","antling","anxiety","anybody","anyone","anything","anywhere","apartment","ape","aperitif","apology","app","apparatus","apparel","appeal","appearance","appellation","appendix","appetiser","appetite","appetizer","applause","apple","applewood","appliance","application","appointment","appreciation","apprehension","approach","appropriation","approval","apricot","apron","apse","aquarium","aquifer","arcade","arch","arch-rival","archaeologist","archaeology","archeology","archer","architect","architecture","archives","area","arena","argument","arithmetic","ark","arm","arm-rest","armadillo","armament","armchair","armoire","armor","armour","armpit","armrest","army","arrangement","array","arrest","arrival","arrogance","arrow","art","artery","arthur","artichoke","article","artifact","artificer","artist","ascend","ascent","ascot","ash","ashram","ashtray","aside","asparagus","aspect","asphalt","aspic","ass","assassination","assault","assembly","assertion","assessment","asset","assignment","assist","assistance","assistant","associate","association","assumption","assurance","asterisk","astrakhan","astrolabe","astrologer","astrology","astronomy","asymmetry","atelier","atheist","athlete","athletics","atmosphere","atom","atrium","attachment","attack","attacker","attainment","attempt","attendance","attendant","attention","attenuation","attic","attitude","attorney","attraction","attribute","auction","audience","audit","auditorium","aunt","authentication","authenticity","author","authorisation","authority","authorization","auto","autoimmunity","automation","automaton","autumn","availability","avalanche","avenue","average","avocado","award","awareness","awe","axis","azimuth","babe","baboon","babushka","baby","bachelor","back","back-up","backbone","backburn","backdrop","background","backpack","backup","backyard","bacon","bacterium","badge","badger","bafflement","bag","bagel","baggage","baggie","baggy","bagpipe","bail","bait","bake","baker","bakery","bakeware","balaclava","balalaika","balance","balcony","ball","ballet","balloon","balloonist","ballot","ballpark","bamboo","ban","banana","band","bandana","bandanna","bandolier","bandwidth","bangle","banjo","bank","bankbook","banker","banking","bankruptcy","banner","banquette","banyan","baobab","bar","barbecue","barbeque","barber","barbiturate","bargain","barge","baritone","barium","bark","barley","barn","barometer","barracks","barrage","barrel","barrier","barstool","bartender","base","baseball","baseboard","baseline","basement","basics","basil","basin","basis","basket","basketball","bass","bassinet","bassoon","bat","bath","bather","bathhouse","bathrobe","bathroom","bathtub","battalion","batter","battery","batting","battle","battleship","bay","bayou","beach","bead","beak","beam","bean","beancurd","beanie","beanstalk","bear","beard","beast","beastie","beat","beating","beauty","beaver","beck","bed","bedrock","bedroom","bee","beech","beef","beer","beet","beetle","beggar","beginner","beginning","begonia","behalf","behavior","behaviour","beheading","behest","behold","being","belfry","belief","believer","bell","belligerency","bellows","belly","belt","bench","bend","beneficiary","benefit","beret","berry","best-seller","bestseller","bet","beverage","beyond","bias","bibliography","bicycle","bid","bidder","bidding","bidet","bifocals","bijou","bike","bikini","bill","billboard","billing","billion","bin","binoculars","biology","biopsy","biosphere","biplane","birch","bird","bird-watcher","birdbath","birdcage","birdhouse","birth","birthday","biscuit","bit","bite","bitten","bitter","black","blackberry","blackbird","blackboard","blackfish","blackness","bladder","blade","blame","blank","blanket","blast","blazer","blend","blessing","blight","blind","blinker","blister","blizzard","block","blocker","blog","blogger","blood","bloodflow","bloom","bloomer","blossom","blouse","blow","blowgun","blowhole","blue","blueberry","blush","boar","board","boat","boatload","boatyard","bob","bobcat","body","bog","bolero","bolt","bomb","bomber","bombing","bond","bonding","bondsman","bone","bonfire","bongo","bonnet","bonsai","bonus","boogeyman","book","bookcase","bookend","booking","booklet","bookmark","boolean","boom","boon","boost","booster","boot","bootee","bootie","booty","border","bore","borrower","borrowing","bosom","boss","botany","bother","bottle","bottling","bottom","bottom-line","boudoir","bough","boulder","boulevard","boundary","bouquet","bourgeoisie","bout","boutique","bow","bower","bowl","bowler","bowling","bowtie","box","boxer","boxspring","boy","boycott","boyfriend","boyhood","boysenberry","bra","brace","bracelet","bracket","brain","brake","bran","branch","brand","brandy","brass","brassiere","bratwurst","bread","breadcrumb","breadfruit","break","breakdown","breakfast","breakpoint","breakthrough","breast","breastplate","breath","breeze","brewer","bribery","brick","bricklaying","bride","bridge","brief","briefing","briefly","briefs","brilliant","brink","brisket","broad","broadcast","broccoli","brochure","brocolli","broiler","broker","bronchitis","bronco","bronze","brooch","brood","brook","broom","brother","brother-in-law","brow","brown","brownie","browser","browsing","brunch","brush","brushfire","brushing","bubble","buck","bucket","buckle","buckwheat","bud","buddy","budget","buffalo","buffer","buffet","bug","buggy","bugle","builder","building","bulb","bulk","bull","bull-fighter","bulldozer","bullet","bump","bumper","bun","bunch","bungalow","bunghole","bunkhouse","burden","bureau","burglar","burial","burlesque","burn","burn-out","burning","burrito","burro","burrow","burst","bus","bush","business","businessman","bust","bustle","butane","butcher","butler","butter","butterfly","button","buy","buyer","buying","buzz","buzzard","c-clamp","cabana","cabbage","cabin","cabinet","cable","caboose","cacao","cactus","caddy","cadet","cafe","caffeine","caftan","cage","cake","calcification","calculation","calculator","calculus","calendar","calf","caliber","calibre","calico","call","calm","calorie","camel","cameo","camera","camp","campaign","campaigning","campanile","camper","campus","can","canal","cancer","candelabra","candidacy","candidate","candle","candy","cane","cannibal","cannon","canoe","canon","canopy","cantaloupe","canteen","canvas","cap","capability","capacity","cape","caper","capital","capitalism","capitulation","capon","cappelletti","cappuccino","captain","caption","captor","car","carabao","caramel","caravan","carbohydrate","carbon","carboxyl","card","cardboard","cardigan","care","career","cargo","caribou","carload","carnation","carnival","carol","carotene","carp","carpenter","carpet","carpeting","carport","carriage","carrier","carrot","carry","cart","cartel","carter","cartilage","cartload","cartoon","cartridge","carving","cascade","case","casement","cash","cashew","cashier","casino","casket","cassava","casserole","cassock","cast","castanet","castle","casualty","cat","catacomb","catalogue","catalysis","catalyst","catamaran","catastrophe","catch","catcher","category","caterpillar","cathedral","cation","catsup","cattle","cauliflower","causal","cause","causeway","caution","cave","caviar","cayenne","ceiling","celebration","celebrity","celeriac","celery","cell","cellar","cello","celsius","cement","cemetery","cenotaph","census","cent","center","centimeter","centre","centurion","century","cephalopod","ceramic","ceramics","cereal","ceremony","certainty","certificate","certification","cesspool","chafe","chain","chainstay","chair","chairlift","chairman","chairperson","chaise","chalet","chalice","chalk","challenge","chamber","champagne","champion","championship","chance","chandelier","change","channel","chaos","chap","chapel","chaplain","chapter","character","characteristic","characterization","chard","charge","charger","charity","charlatan","charm","charset","chart","charter","chasm","chassis","chastity","chasuble","chateau","chatter","chauffeur","chauvinist","check","checkbook","checking","checkout","checkroom","cheddar","cheek","cheer","cheese","cheesecake","cheetah","chef","chem","chemical","chemistry","chemotaxis","cheque","cherry","chess","chest","chestnut","chick","chicken","chicory","chief","chiffonier","child","childbirth","childhood","chili","chill","chime","chimpanzee","chin","chinchilla","chino","chip","chipmunk","chit-chat","chivalry","chive","chives","chocolate","choice","choir","choker","cholesterol","choosing","chop","chops","chopstick","chopsticks","chord","chorus","chow","chowder","chrome","chromolithograph","chronicle","chronograph","chronometer","chrysalis","chub","chuck","chug","church","churn","chutney","cicada","cigarette","cilantro","cinder","cinema","cinnamon","circadian","circle","circuit","circulation","circumference","circumstance","cirrhosis","cirrus","citizen","citizenship","citron","citrus","city","civilian","civilisation","civilization","claim","clam","clamp","clan","clank","clapboard","clarification","clarinet","clarity","clasp","class","classic","classification","classmate","classroom","clause","clave","clavicle","clavier","claw","clay","cleaner","clearance","clearing","cleat","cleavage","clef","cleft","clergyman","cleric","clerk","click","client","cliff","climate","climb","clinic","clip","clipboard","clipper","cloak","cloakroom","clock","clockwork","clogs","cloister","clone","close","closet","closing","closure","cloth","clothes","clothing","cloud","cloudburst","clove","clover","cloves","club","clue","cluster","clutch","co-producer","coach","coal","coalition","coast","coaster","coat","cob","cobbler","cobweb","cock","cockpit","cockroach","cocktail","cocoa","coconut","cod","code","codepage","codling","codon","codpiece","coevolution","cofactor","coffee","coffin","cohesion","cohort","coil","coin","coincidence","coinsurance","coke","cold","coleslaw","coliseum","collaboration","collagen","collapse","collar","collard","collateral","colleague","collection","collectivisation","collectivization","collector","college","collision","colloquy","colon","colonial","colonialism","colonisation","colonization","colony","color","colorlessness","colt","column","columnist","comb","combat","combination","combine","comeback","comedy","comestible","comfort","comfortable","comic","comics","comma","command","commander","commandment","comment","commerce","commercial","commission","commitment","committee","commodity","common","commonsense","commotion","communicant","communication","communion","communist","community","commuter","company","comparison","compass","compassion","compassionate","compensation","competence","competition","competitor","complaint","complement","completion","complex","complexity","compliance","complication","complicity","compliment","component","comportment","composer","composite","composition","compost","comprehension","compress","compromise","comptroller","compulsion","computer","comradeship","con","concentrate","concentration","concept","conception","concern","concert","conclusion","concrete","condition","conditioner","condominium","condor","conduct","conductor","cone","confectionery","conference","confidence","confidentiality","configuration","confirmation","conflict","conformation","confusion","conga","congo","congregation","congress","congressman","congressperson","conifer","connection","connotation","conscience","consciousness","consensus","consent","consequence","conservation","conservative","consideration","consignment","consist","consistency","console","consonant","conspiracy","conspirator","constant","constellation","constitution","constraint","construction","consul","consulate","consulting","consumer","consumption","contact","contact lens","contagion","container","content","contention","contest","context","continent","contingency","continuity","contour","contract","contractor","contrail","contrary","contrast","contribution","contributor","control","controller","controversy","convection","convenience","convention","conversation","conversion","convert","convertible","conviction","cook","cookbook","cookie","cooking","coonskin","cooperation","coordination","coordinator","cop","cop-out","cope","copper","copy","copying","copyright","copywriter","coral","cord","corduroy","core","cork","cormorant","corn","corner","cornerstone","cornet","cornflakes","cornmeal","corporal","corporation","corporatism","corps","corral","correspondence","correspondent","corridor","corruption","corsage","cosset","cost","costume","cot","cottage","cotton","couch","cougar","cough","council","councilman","councilor","councilperson","counsel","counseling","counselling","counsellor","counselor","count","counter","counter-force","counterpart","counterterrorism","countess","country","countryside","county","couple","coupon","courage","course","court","courthouse","courtroom","cousin","covariate","cover","coverage","coverall","cow","cowbell","cowboy","coyote","crab","crack","cracker","crackers","cradle","craft","craftsman","cranberry","crane","cranky","crap","crash","crate","cravat","craw","crawdad","crayfish","crayon","crazy","cream","creation","creationism","creationist","creative","creativity","creator","creature","creche","credential","credenza","credibility","credit","creditor","creek","creme brulee","crepe","crest","crew","crewman","crewmate","crewmember","crewmen","cria","crib","cribbage","cricket","cricketer","crime","criminal","crinoline","crisis","crisp","criteria","criterion","critic","criticism","crocodile","crocus","croissant","crook","crop","cross","cross-contamination","cross-stitch","crotch","croup","crow","crowd","crown","crucifixion","crude","cruelty","cruise","crumb","crunch","crusader","crush","crust","cry","crystal","crystallography","cub","cube","cuckoo","cucumber","cue","cuff-link","cuisine","cultivar","cultivator","culture","culvert","cummerbund","cup","cupboard","cupcake","cupola","curd","cure","curio","curiosity","curl","curler","currant","currency","current","curriculum","curry","curse","cursor","curtailment","curtain","curve","cushion","custard","custody","custom","customer","cut","cuticle","cutlet","cutover","cutting","cyclamen","cycle","cyclone","cyclooxygenase","cygnet","cylinder","cymbal","cynic","cyst","cytokine","cytoplasm","dad","daddy","daffodil","dagger","dahlia","daikon","daily","dairy","daisy","dam","damage","dame","damn","dance","dancer","dancing","dandelion","danger","dare","dark","darkness","darn","dart","dash","dashboard","data","database","date","daughter","dawn","day","daybed","daylight","dead","deadline","deal","dealer","dealing","dearest","death","deathwatch","debate","debris","debt","debtor","decade","decadence","decency","decimal","decision","decision-making","deck","declaration","declination","decline","decoder","decongestant","decoration","decrease","decryption","dedication","deduce","deduction","deed","deep","deer","default","defeat","defendant","defender","defense","deficit","definition","deformation","degradation","degree","delay","deliberation","delight","delivery","demand","democracy","democrat","demon","demur","den","denim","denominator","density","dentist","deodorant","department","departure","dependency","dependent","deployment","deposit","deposition","depot","depression","depressive","depth","deputy","derby","derivation","derivative","derrick","descendant","descent","description","desert","design","designation","designer","desire","desk","desktop","dessert","destination","destiny","destroyer","destruction","detail","detainee","detainment","detection","detective","detector","detention","determination","detour","devastation","developer","developing","development","developmental","deviance","deviation","device","devil","dew","dhow","diabetes","diadem","diagnosis","diagram","dial","dialect","dialogue","diam","diamond","diaper","diaphragm","diarist","diary","dibble","dick","dickey","dictaphone","dictator","diction","dictionary","die","diesel","diet","difference","differential","difficulty","diffuse","dig","digestion","digestive","digger","digging","digit","dignity","dilapidation","dill","dilution","dime","dimension","dimple","diner","dinghy","dining","dinner","dinosaur","dioxide","dip","diploma","diplomacy","dipstick","direction","directive","director","directory","dirndl","dirt","disability","disadvantage","disagreement","disappointment","disarmament","disaster","discharge","discipline","disclaimer","disclosure","disco","disconnection","discount","discourse","discovery","discrepancy","discretion","discrimination","discussion","disdain","disease","disembodiment","disengagement","disguise","disgust","dish","dishwasher","disk","disparity","dispatch","displacement","display","disposal","disposer","disposition","dispute","disregard","disruption","dissemination","dissonance","distance","distinction","distortion","distribution","distributor","district","divalent","divan","diver","diversity","divide","dividend","divider","divine","diving","division","divorce","doc","dock","doctor","doctorate","doctrine","document","documentary","documentation","doe","dog","doggie","dogsled","dogwood","doing","doll","dollar","dollop","dolman","dolor","dolphin","domain","dome","domination","donation","donkey","donor","donut","door","doorbell","doorknob","doorpost","doorway","dory","dose","dot","double","doubling","doubt","doubter","dough","doughnut","down","downfall","downforce","downgrade","download","downstairs","downtown","downturn","dozen","draft","drag","dragon","dragonfly","dragonfruit","dragster","drain","drainage","drake","drama","dramaturge","drapes","draw","drawbridge","drawer","drawing","dream","dreamer","dredger","dress","dresser","dressing","drill","drink","drinking","drive","driver","driveway","driving","drizzle","dromedary","drop","drudgery","drug","drum","drummer","drunk","dryer","duck","duckling","dud","dude","due","duel","dueling","duffel","dugout","dulcimer","dumbwaiter","dump","dump truck","dune","dune buggy","dungarees","dungeon","duplexer","duration","durian","dusk","dust","dust storm","duster","duty","dwarf","dwell","dwelling","dynamics","dynamite","dynamo","dynasty","dysfunction","e-book","e-mail","e-reader","eagle","eaglet","ear","eardrum","earmuffs","earnings","earplug","earring","earrings","earth","earthquake","earthworm","ease","easel","east","eating","eaves","eavesdropper","ecclesia","echidna","eclipse","ecliptic","ecology","economics","economy","ecosystem","ectoderm","ectodermal","ecumenist","eddy","edge","edger","edible","editing","edition","editor","editorial","education","eel","effacement","effect","effective","effectiveness","effector","efficacy","efficiency","effort","egg","egghead","eggnog","eggplant","ego","eicosanoid","ejector","elbow","elderberry","election","electricity","electrocardiogram","electronics","element","elephant","elevation","elevator","eleventh","elf","elicit","eligibility","elimination","elite","elixir","elk","ellipse","elm","elongation","elver","email","emanate","embarrassment","embassy","embellishment","embossing","embryo","emerald","emergence","emergency","emergent","emery","emission","emitter","emotion","emphasis","empire","employ","employee","employer","employment","empowerment","emu","enactment","encirclement","enclave","enclosure","encounter","encouragement","encyclopedia","end","endive","endoderm","endorsement","endothelium","endpoint","enemy","energy","enforcement","engagement","engine","engineer","engineering","enigma","enjoyment","enquiry","enrollment","enterprise","entertainment","enthusiasm","entirety","entity","entrance","entree","entrepreneur","entry","envelope","environment","envy","enzyme","epauliere","epee","ephemera","ephemeris","ephyra","epic","episode","epithelium","epoch","eponym","epoxy","equal","equality","equation","equinox","equipment","equity","equivalent","era","eraser","erection","erosion","error","escalator","escape","escort","espadrille","espalier","essay","essence","essential","establishment","estate","estimate","estrogen","estuary","eternity","ethernet","ethics","ethnicity","ethyl","euphonium","eurocentrism","evaluation","evaluator","evaporation","eve","evening","evening-wear","event","everybody","everyone","everything","eviction","evidence","evil","evocation","evolution","ex-husband","ex-wife","exaggeration","exam","examination","examiner","example","exasperation","excellence","exception","excerpt","excess","exchange","excitement","exclamation","excursion","excuse","execution","executive","executor","exercise","exhaust","exhaustion","exhibit","exhibition","exile","existence","exit","exocrine","expansion","expansionism","expectancy","expectation","expedition","expense","experience","experiment","experimentation","expert","expertise","explanation","exploration","explorer","explosion","export","expose","exposition","exposure","expression","extension","extent","exterior","external","extinction","extreme","extremist","eye","eyeball","eyebrow","eyebrows","eyeglasses","eyelash","eyelashes","eyelid","eyelids","eyeliner","eyestrain","eyrie","fabric","face","facelift","facet","facility","facsimile","fact","factor","factory","faculty","fahrenheit","fail","failure","fairness","fairy","faith","faithful","fall","fallacy","falling-out","fame","familiar","familiarity","family","fan","fang","fanlight","fanny","fanny-pack","fantasy","farm","farmer","farming","farmland","farrow","fascia","fashion","fat","fate","father","father-in-law","fatigue","fatigues","faucet","fault","fav","fava","favor","favorite","fawn","fax","fear","feast","feather","feature","fedelini","federation","fedora","fee","feed","feedback","feeding","feel","feeling","fellow","felony","female","fen","fence","fencing","fender","feng","fennel","ferret","ferry","ferryboat","fertilizer","festival","fetus","few","fiber","fiberglass","fibre","fibroblast","fibrosis","ficlet","fiction","fiddle","field","fiery","fiesta","fifth","fig","fight","fighter","figure","figurine","file","filing","fill","fillet","filly","film","filter","filth","final","finance","financing","finding","fine","finer","finger","fingerling","fingernail","finish","finisher","fir","fire","fireman","fireplace","firewall","firm","first","fish","fishbone","fisherman","fishery","fishing","fishmonger","fishnet","fisting","fit","fitness","fix","fixture","flag","flair","flame","flan","flanker","flare","flash","flat","flatboat","flavor","flax","fleck","fledgling","fleece","flesh","flexibility","flick","flicker","flight","flint","flintlock","flip-flops","flock","flood","floodplain","floor","floozie","flour","flow","flower","flu","flugelhorn","fluke","flume","flung","flute","fly","flytrap","foal","foam","fob","focus","fog","fold","folder","folk","folklore","follower","following","fondue","font","food","foodstuffs","fool","foot","footage","football","footnote","footprint","footrest","footstep","footstool","footwear","forage","forager","foray","force","ford","forearm","forebear","forecast","forehead","foreigner","forelimb","forest","forestry","forever","forgery","fork","form","formal","formamide","format","formation","former","formicarium","formula","fort","forte","fortnight","fortress","fortune","forum","foundation","founder","founding","fountain","fourths","fowl","fox","foxglove","fraction","fragrance","frame","framework","fratricide","fraud","fraudster","freak","freckle","freedom","freelance","freezer","freezing","freight","freighter","frenzy","freon","frequency","fresco","friction","fridge","friend","friendship","fries","frigate","fright","fringe","fritter","frock","frog","front","frontier","frost","frosting","frown","fruit","frustration","fry","fuck","fuel","fugato","fulfillment","full","fun","function","functionality","fund","funding","fundraising","funeral","fur","furnace","furniture","furry","fusarium","futon","future","gadget","gaffe","gaffer","gain","gaiters","gale","gall-bladder","gallery","galley","gallon","galoshes","gambling","game","gamebird","gaming","gamma-ray","gander","gang","gap","garage","garb","garbage","garden","garlic","garment","garter","gas","gasket","gasoline","gasp","gastronomy","gastropod","gate","gateway","gather","gathering","gator","gauge","gauntlet","gavel","gazebo","gazelle","gear","gearshift","geek","gel","gelatin","gelding","gem","gemsbok","gender","gene","general","generation","generator","generosity","genetics","genie","genius","genocide","genre","gentleman","geography","geology","geometry","geranium","gerbil","gesture","geyser","gherkin","ghost","giant","gift","gig","gigantism","giggle","ginger","gingerbread","ginseng","giraffe","girdle","girl","girlfriend","git","glacier","gladiolus","glance","gland","glass","glasses","glee","glen","glider","gliding","glimpse","globe","glockenspiel","gloom","glory","glove","glow","glucose","glue","glut","glutamate","gnat","gnu","go-kart","goal","goat","gobbler","god","goddess","godfather","godmother","godparent","goggles","going","gold","goldfish","golf","gondola","gong","good","good-bye","goodbye","goodie","goodness","goodnight","goodwill","goose","gopher","gorilla","gosling","gossip","governance","government","governor","gown","grab-bag","grace","grade","gradient","graduate","graduation","graffiti","graft","grain","gram","grammar","gran","grand","grandchild","granddaughter","grandfather","grandma","grandmom","grandmother","grandpa","grandparent","grandson","granny","granola","grant","grape","grapefruit","graph","graphic","grasp","grass","grasshopper","grassland","gratitude","gravel","gravitas","gravity","gravy","gray","grease","great-grandfather","great-grandmother","greatness","greed","green","greenhouse","greens","grenade","grey","grid","grief","grill","grin","grip","gripper","grit","grocery","ground","group","grouper","grouse","grove","growth","grub","guacamole","guarantee","guard","guava","guerrilla","guess","guest","guestbook","guidance","guide","guideline","guilder","guilt","guilty","guinea","guitar","guitarist","gum","gumshoe","gun","gunpowder","gutter","guy","gym","gymnast","gymnastics","gynaecology","gyro","habit","habitat","hacienda","hacksaw","hackwork","hail","hair","haircut","hake","half","half-brother","half-sister","halibut","hall","halloween","hallway","halt","ham","hamburger","hammer","hammock","hamster","hand","hand-holding","handball","handful","handgun","handicap","handle","handlebar","handmaiden","handover","handrail","handsaw","hanger","happening","happiness","harald","harbor","harbour","hard-hat","hardboard","hardcover","hardening","hardhat","hardship","hardware","hare","harm","harmonica","harmonise","harmonize","harmony","harp","harpooner","harpsichord","harvest","harvester","hash","hashtag","hassock","haste","hat","hatbox","hatchet","hatchling","hate","hatred","haunt","haven","haversack","havoc","hawk","hay","haze","hazel","hazelnut","head","headache","headlight","headline","headphones","headquarters","headrest","health","health-care","hearing","hearsay","heart","heart-throb","heartache","heartbeat","hearth","hearthside","heartwood","heat","heater","heating","heaven","heavy","hectare","hedge","hedgehog","heel","heifer","height","heir","heirloom","helicopter","helium","hell","hellcat","hello","helmet","helo","help","hemisphere","hemp","hen","hepatitis","herb","herbs","heritage","hermit","hero","heroine","heron","herring","hesitation","heterosexual","hexagon","heyday","hiccups","hide","hierarchy","high","high-rise","highland","highlight","highway","hike","hiking","hill","hint","hip","hippodrome","hippopotamus","hire","hiring","historian","history","hit","hive","hobbit","hobby","hockey","hoe","hog","hold","holder","hole","holiday","home","homeland","homeownership","hometown","homework","homicide","homogenate","homonym","homosexual","homosexuality","honesty","honey","honeybee","honeydew","honor","honoree","hood","hoof","hook","hop","hope","hops","horde","horizon","hormone","horn","hornet","horror","horse","horseradish","horst","hose","hosiery","hospice","hospital","hospitalisation","hospitality","hospitalization","host","hostel","hostess","hotdog","hotel","hound","hour","hourglass","house","houseboat","household","housewife","housework","housing","hovel","hovercraft","howard","howitzer","hub","hubcap","hubris","hug","hugger","hull","human","humanity","humidity","hummus","humor","humour","hunchback","hundred","hunger","hunt","hunter","hunting","hurdle","hurdler","hurricane","hurry","hurt","husband","hut","hutch","hyacinth","hybridisation","hybridization","hydrant","hydraulics","hydrocarb","hydrocarbon","hydrofoil","hydrogen","hydrolyse","hydrolysis","hydrolyze","hydroxyl","hyena","hygienic","hype","hyphenation","hypochondria","hypothermia","hypothesis","ice","ice-cream","iceberg","icebreaker","icecream","icicle","icing","icon","icy","id","idea","ideal","identification","identity","ideology","idiom","idiot","igloo","ignorance","ignorant","ikebana","illegal","illiteracy","illness","illusion","illustration","image","imagination","imbalance","imitation","immigrant","immigration","immortal","impact","impairment","impala","impediment","implement","implementation","implication","import","importance","impostor","impress","impression","imprisonment","impropriety","improvement","impudence","impulse","in-joke","in-laws","inability","inauguration","inbox","incandescence","incarnation","incense","incentive","inch","incidence","incident","incision","inclusion","income","incompetence","inconvenience","increase","incubation","independence","independent","index","indication","indicator","indigence","individual","industrialisation","industrialization","industry","inequality","inevitable","infancy","infant","infarction","infection","infiltration","infinite","infix","inflammation","inflation","influence","influx","info","information","infrastructure","infusion","inglenook","ingrate","ingredient","inhabitant","inheritance","inhibition","inhibitor","initial","initialise","initialize","initiative","injunction","injury","injustice","ink","inlay","inn","innervation","innocence","innocent","innovation","input","inquiry","inscription","insect","insectarium","insert","inside","insight","insolence","insomnia","inspection","inspector","inspiration","installation","instance","instant","instinct","institute","institution","instruction","instructor","instrument","instrumentalist","instrumentation","insulation","insurance","insurgence","insurrection","integer","integral","integration","integrity","intellect","intelligence","intensity","intent","intention","intentionality","interaction","interchange","interconnection","intercourse","interest","interface","interferometer","interior","interject","interloper","internet","interpretation","interpreter","interval","intervenor","intervention","interview","interviewer","intestine","introduction","intuition","invader","invasion","invention","inventor","inventory","inverse","inversion","investigation","investigator","investment","investor","invitation","invite","invoice","involvement","iridescence","iris","iron","ironclad","irony","irrigation","ischemia","island","isogloss","isolation","issue","item","itinerary","ivory","jack","jackal","jacket","jackfruit","jade","jaguar","jail","jailhouse","jalape\xC3\xB1o","jam","jar","jasmine","jaw","jazz","jealousy","jeans","jeep","jelly","jellybeans","jellyfish","jerk","jet","jewel","jeweller","jewellery","jewelry","jicama","jiffy","job","jockey","jodhpurs","joey","jogging","joint","joke","jot","journal","journalism","journalist","journey","joy","judge","judgment","judo","jug","juggernaut","juice","julienne","jumbo","jump","jumper","jumpsuit","jungle","junior","junk","junker","junket","jury","justice","justification","jute","kale","kamikaze","kangaroo","karate","kayak","kazoo","kebab","keep","keeper","kendo","kennel","ketch","ketchup","kettle","kettledrum","key","keyboard","keyboarding","keystone","kick","kick-off","kid","kidney","kielbasa","kill","killer","killing","kilogram","kilometer","kilt","kimono","kinase","kind","kindness","king","kingdom","kingfish","kiosk","kiss","kit","kitchen","kite","kitsch","kitten","kitty","kiwi","knee","kneejerk","knickers","knife","knife-edge","knight","knitting","knock","knot","know-how","knowledge","knuckle","koala","kohlrabi","kumquat","lab","label","labor","laboratory","laborer","labour","labourer","lace","lack","lacquerware","lad","ladder","ladle","lady","ladybug","lag","lake","lamb","lambkin","lament","lamp","lanai","land","landform","landing","landmine","landscape","lane","language","lantern","lap","laparoscope","lapdog","laptop","larch","lard","larder","lark","larva","laryngitis","lasagna","lashes","last","latency","latex","lathe","latitude","latte","latter","laugh","laughter","laundry","lava","law","lawmaker","lawn","lawsuit","lawyer","lay","layer","layout","lead","leader","leadership","leading","leaf","league","leaker","leap","learning","leash","leather","leave","leaver","lecture","leek","leeway","left","leg","legacy","legal","legend","legging","legislation","legislator","legislature","legitimacy","legume","leisure","lemon","lemonade","lemur","lender","lending","length","lens","lentil","leopard","leprosy","leptocephalus","lesbian","lesson","letter","lettuce","level","lever","leverage","leveret","liability","liar","liberty","libido","library","licence","license","licensing","licorice","lid","lie","lieu","lieutenant","life","lifestyle","lifetime","lift","ligand","light","lighting","lightning","lightscreen","ligula","likelihood","likeness","lilac","lily","limb","lime","limestone","limit","limitation","limo","line","linen","liner","linguist","linguistics","lining","link","linkage","linseed","lion","lip","lipid","lipoprotein","lipstick","liquid","liquidity","liquor","list","listening","listing","literate","literature","litigation","litmus","litter","littleneck","liver","livestock","living","lizard","llama","load","loading","loaf","loafer","loan","lobby","lobotomy","lobster","local","locality","location","lock","locker","locket","locomotive","locust","lode","loft","log","loggia","logic","login","logistics","logo","loincloth","lollipop","loneliness","longboat","longitude","look","lookout","loop","loophole","loquat","lord","loss","lot","lotion","lottery","lounge","louse","lout","love","lover","lox","loyalty","luck","luggage","lumber","lumberman","lunch","luncheonette","lunchmeat","lunchroom","lung","lunge","lust","lute","luxury","lychee","lycra","lye","lymphocyte","lynx","lyocell","lyre","lyrics","lysine","mRNA","macadamia","macaroni","macaroon","macaw","machine","machinery","macrame","macro","macrofauna","madam","maelstrom","maestro","magazine","maggot","magic","magnet","magnitude","maid","maiden","mail","mailbox","mailer","mailing","mailman","main","mainland","mainstream","maintainer","maintenance","maize","major","major-league","majority","makeover","maker","makeup","making","male","malice","mall","mallard","mallet","malnutrition","mama","mambo","mammoth","man","manacle","management","manager","manatee","mandarin","mandate","mandolin","mangle","mango","mangrove","manhunt","maniac","manicure","manifestation","manipulation","mankind","manner","manor","mansard","manservant","mansion","mantel","mantle","mantua","manufacturer","manufacturing","many","map","maple","mapping","maracas","marathon","marble","march","mare","margarine","margin","mariachi","marimba","marines","marionberry","mark","marker","market","marketer","marketing","marketplace","marksman","markup","marmalade","marriage","marsh","marshland","marshmallow","marten","marxism","mascara","mask","masonry","mass","massage","mast","master","masterpiece","mastication","mastoid","mat","match","matchmaker","mate","material","maternity","math","mathematics","matrix","matter","mattock","mattress","max","maximum","maybe","mayonnaise","mayor","meadow","meal","mean","meander","meaning","means","meantime","measles","measure","measurement","meat","meatball","meatloaf","mecca","mechanic","mechanism","med","medal","media","median","medication","medicine","medium","meet","meeting","melatonin","melody","melon","member","membership","membrane","meme","memo","memorial","memory","men","menopause","menorah","mention","mentor","menu","merchandise","merchant","mercury","meridian","meringue","merit","mesenchyme","mess","message","messenger","messy","metabolite","metal","metallurgist","metaphor","meteor","meteorology","meter","methane","method","methodology","metric","metro","metronome","mezzanine","microlending","micronutrient","microphone","microwave","mid-course","midden","middle","middleman","midline","midnight","midwife","might","migrant","migration","mile","mileage","milepost","milestone","military","milk","milkshake","mill","millennium","millet","millimeter","million","millisecond","millstone","mime","mimosa","min","mincemeat","mind","mine","mineral","mineshaft","mini","mini-skirt","minibus","minimalism","minimum","mining","minion","minister","mink","minnow","minor","minor-league","minority","mint","minute","miracle","mirror","miscarriage","miscommunication","misfit","misnomer","misogyny","misplacement","misreading","misrepresentation","miss","missile","mission","missionary","mist","mistake","mister","misunderstand","miter","mitten","mix","mixer","mixture","moai","moat","mob","mobile","mobility","mobster","moccasins","mocha","mochi","mode","model","modeling","modem","modernist","modernity","modification","molar","molasses","molding","mole","molecule","mom","moment","monastery","monasticism","money","monger","monitor","monitoring","monk","monkey","monocle","monopoly","monotheism","monsoon","monster","month","monument","mood","moody","moon","moonlight","moonscape","moonshine","moose","mop","morale","morbid","morbidity","morning","moron","morphology","morsel","mortal","mortality","mortgage","mortise","mosque","mosquito","most","motel","moth","mother","mother-in-law","motion","motivation","motive","motor","motorboat","motorcar","motorcycle","mound","mountain","mouse","mouser","mousse","moustache","mouth","mouton","movement","mover","movie","mower","mozzarella","mud","muffin","mug","mukluk","mule","multimedia","murder","muscat","muscatel","muscle","musculature","museum","mushroom","music","music-box","music-making","musician","muskrat","mussel","mustache","mustard","mutation","mutt","mutton","mycoplasma","mystery","myth","mythology","nail","name","naming","nanoparticle","napkin","narrative","nasal","nation","nationality","native","naturalisation","nature","navigation","necessity","neck","necklace","necktie","nectar","nectarine","need","needle","neglect","negligee","negotiation","neighbor","neighborhood","neighbour","neighbourhood","neologism","neon","neonate","nephew","nerve","nest","nestling","nestmate","net","netball","netbook","netsuke","network","networking","neurobiologist","neuron","neuropathologist","neuropsychiatry","news","newsletter","newspaper","newsprint","newsstand","nexus","nibble","nicety","niche","nick","nickel","nickname","niece","night","nightclub","nightgown","nightingale","nightlife","nightlight","nightmare","ninja","nit","nitrogen","nobody","nod","node","noir","noise","nonbeliever","nonconformist","nondisclosure","nonsense","noodle","noodles","noon","norm","normal","normalisation","normalization","north","nose","notation","note","notebook","notepad","nothing","notice","notion","notoriety","nougat","noun","nourishment","novel","nucleotidase","nucleotide","nudge","nuke","number","numeracy","numeric","numismatist","nun","nurse","nursery","nursing","nurture","nut","nutmeg","nutrient","nutrition","nylon","nymph","oak","oar","oasis","oat","oatmeal","oats","obedience","obesity","obi","object","objection","objective","obligation","oboe","observation","observatory","obsession","obsidian","obstacle","occasion","occupation","occurrence","ocean","ocelot","octagon","octave","octavo","octet","octopus","odometer","odyssey","oeuvre","off-ramp","offence","offense","offer","offering","office","officer","official","offset","oil","okra","oldie","oleo","olive","omega","omelet","omission","omnivore","oncology","onion","online","onset","opening","opera","operating","operation","operator","ophthalmologist","opinion","opium","opossum","opponent","opportunist","opportunity","opposite","opposition","optimal","optimisation","optimist","optimization","option","orange","orangutan","orator","orchard","orchestra","orchid","order","ordinary","ordination","ore","oregano","organ","organisation","organising","organization","organizing","orient","orientation","origin","original","originality","ornament","osmosis","osprey","ostrich","other","otter","ottoman","ounce","outback","outcome","outfielder","outfit","outhouse","outlaw","outlay","outlet","outline","outlook","output","outrage","outrigger","outrun","outset","outside","oval","ovary","oven","overcharge","overclocking","overcoat","overexertion","overflight","overhead","overheard","overload","overnighter","overshoot","oversight","overview","overweight","owl","owner","ownership","ox","oxford","oxygen","oyster","ozone","pace","pacemaker","pack","package","packaging","packet","pad","paddle","paddock","pagan","page","pagoda","pail","pain","paint","painter","painting","paintwork","pair","pajamas","palace","palate","palm","pamphlet","pan","pancake","pancreas","panda","panel","panic","pannier","panpipe","pansy","panther","panties","pantologist","pantology","pantry","pants","pantsuit","panty","pantyhose","papa","papaya","paper","paperback","paperwork","parable","parachute","parade","paradise","paragraph","parallelogram","paramecium","paramedic","parameter","paranoia","parcel","parchment","pard","pardon","parent","parenthesis","parenting","park","parka","parking","parliament","parole","parrot","parser","parsley","parsnip","part","participant","participation","particle","particular","partner","partnership","partridge","party","pass","passage","passbook","passenger","passing","passion","passive","passport","password","past","pasta","paste","pastor","pastoralist","pastry","pasture","pat","patch","pate","patent","patentee","path","pathogenesis","pathology","pathway","patience","patient","patina","patio","patriarch","patrimony","patriot","patrol","patroller","patrolling","patron","pattern","patty","pattypan","pause","pavement","pavilion","paw","pawnshop","pay","payee","payment","payoff","pea","peace","peach","peacoat","peacock","peak","peanut","pear","pearl","peasant","pecan","pecker","pedal","peek","peen","peer","peer-to-peer","pegboard","pelican","pelt","pen","penalty","pence","pencil","pendant","pendulum","penguin","penicillin","peninsula","penis","pennant","penny","pension","pentagon","peony","people","pepper","pepperoni","percent","percentage","perception","perch","perennial","perfection","performance","perfume","period","periodical","peripheral","permafrost","permission","permit","perp","perpendicular","persimmon","person","personal","personality","personnel","perspective","pest","pet","petal","petition","petitioner","petticoat","pew","pharmacist","pharmacopoeia","phase","pheasant","phenomenon","phenotype","pheromone","philanthropy","philosopher","philosophy","phone","phosphate","photo","photodiode","photograph","photographer","photography","photoreceptor","phrase","phrasing","physical","physics","physiology","pianist","piano","piccolo","pick","pickax","pickaxe","picket","pickle","pickup","picnic","picture","picturesque","pie","piece","pier","piety","pig","pigeon","piglet","pigpen","pigsty","pike","pilaf","pile","pilgrim","pilgrimage","pill","pillar","pillbox","pillow","pilot","pimp","pimple","pin","pinafore","pince-nez","pine","pineapple","pinecone","ping","pink","pinkie","pinot","pinstripe","pint","pinto","pinworm","pioneer","pipe","pipeline","piracy","pirate","piss","pistol","pit","pita","pitch","pitcher","pitching","pith","pizza","place","placebo","placement","placode","plagiarism","plain","plaintiff","plan","plane","planet","planning","plant","plantation","planter","planula","plaster","plasterboard","plastic","plate","platelet","platform","platinum","platter","platypus","play","player","playground","playroom","playwright","plea","pleasure","pleat","pledge","plenty","plier","pliers","plight","plot","plough","plover","plow","plowman","plug","plugin","plum","plumber","plume","plunger","plywood","pneumonia","pocket","pocket-watch","pocketbook","pod","podcast","poem","poet","poetry","poignance","point","poison","poisoning","poker","polarisation","polarization","pole","polenta","police","policeman","policy","polish","politician","politics","poll","polliwog","pollutant","pollution","polo","polyester","polyp","pomegranate","pomelo","pompom","poncho","pond","pony","pool","poor","pop","popcorn","poppy","popsicle","popularity","population","populist","porcelain","porch","porcupine","pork","porpoise","port","porter","portfolio","porthole","portion","portrait","position","possession","possibility","possible","post","postage","postbox","poster","posterior","postfix","pot","potato","potential","pottery","potty","pouch","poultry","pound","pounding","poverty","powder","power","practice","practitioner","prairie","praise","pray","prayer","precedence","precedent","precipitation","precision","predecessor","preface","preference","prefix","pregnancy","prejudice","prelude","premeditation","premier","premise","premium","preoccupation","preparation","prescription","presence","present","presentation","preservation","preserves","presidency","president","press","pressroom","pressure","pressurisation","pressurization","prestige","presume","pretzel","prevalence","prevention","prey","price","pricing","pride","priest","priesthood","primary","primate","prince","princess","principal","principle","print","printer","printing","prior","priority","prison","prisoner","privacy","private","privilege","prize","prizefight","probability","probation","probe","problem","procedure","proceedings","process","processing","processor","proctor","procurement","produce","producer","product","production","productivity","profession","professional","professor","profile","profit","progenitor","program","programme","programming","progress","progression","prohibition","project","proliferation","promenade","promise","promotion","prompt","pronoun","pronunciation","proof","proof-reader","propaganda","propane","property","prophet","proponent","proportion","proposal","proposition","proprietor","prose","prosecution","prosecutor","prospect","prosperity","prostacyclin","prostanoid","prostrate","protection","protein","protest","protocol","providence","provider","province","provision","prow","proximal","proximity","prune","pruner","pseudocode","pseudoscience","psychiatrist","psychoanalyst","psychologist","psychology","ptarmigan","pub","public","publication","publicity","publisher","publishing","pudding","puddle","puffin","pug","puggle","pulley","pulse","puma","pump","pumpernickel","pumpkin","pumpkinseed","pun","punch","punctuation","punishment","pup","pupa","pupil","puppet","puppy","purchase","puritan","purity","purple","purpose","purr","purse","pursuit","push","pusher","put","puzzle","pyramid","pyridine","quadrant","quail","qualification","quality","quantity","quart","quarter","quartet","quartz","queen","query","quest","question","questioner","questionnaire","quiche","quicksand","quiet","quill","quilt","quince","quinoa","quit","quiver","quota","quotation","quote","rabbi","rabbit","raccoon","race","racer","racing","racism","racist","rack","radar","radiator","radio","radiosonde","radish","raffle","raft","rag","rage","raid","rail","railing","railroad","railway","raiment","rain","rainbow","raincoat","rainmaker","rainstorm","rainy","raise","raisin","rake","rally","ram","rambler","ramen","ramie","ranch","rancher","randomisation","randomization","range","ranger","rank","rap","rape","raspberry","rat","rate","ratepayer","rating","ratio","rationale","rations","raven","ravioli","rawhide","ray","rayon","razor","reach","reactant","reaction","read","reader","readiness","reading","real","reality","realization","realm","reamer","rear","reason","reasoning","rebel","rebellion","reboot","recall","recapitulation","receipt","receiver","reception","receptor","recess","recession","recipe","recipient","reciprocity","reclamation","recliner","recognition","recollection","recommendation","reconsideration","record","recorder","recording","recovery","recreation","recruit","rectangle","red","redesign","redhead","redirect","rediscovery","reduction","reef","refectory","reference","referendum","reflection","reform","refreshments","refrigerator","refuge","refund","refusal","refuse","regard","regime","region","regionalism","register","registration","registry","regret","regulation","regulator","rehospitalisation","rehospitalization","reindeer","reinscription","reject","relation","relationship","relative","relaxation","relay","release","reliability","relief","religion","relish","reluctance","remains","remark","reminder","remnant","remote","removal","renaissance","rent","reorganisation","reorganization","repair","reparation","repayment","repeat","replacement","replica","replication","reply","report","reporter","reporting","repository","representation","representative","reprocessing","republic","republican","reputation","request","requirement","resale","rescue","research","researcher","resemblance","reservation","reserve","reservoir","reset","residence","resident","residue","resist","resistance","resolution","resolve","resort","resource","respect","respite","response","responsibility","rest","restaurant","restoration","restriction","restroom","restructuring","result","resume","retailer","retention","rethinking","retina","retirement","retouching","retreat","retrospect","retrospective","retrospectivity","return","reunion","revascularisation","revascularization","reveal","revelation","revenant","revenge","revenue","reversal","reverse","review","revitalisation","revitalization","revival","revolution","revolver","reward","rhetoric","rheumatism","rhinoceros","rhubarb","rhyme","rhythm","rib","ribbon","rice","riddle","ride","rider","ridge","riding","rifle","right","rim","ring","ringworm","riot","rip","ripple","rise","riser","risk","rite","ritual","river","riverbed","rivulet","road","roadway","roar","roast","robe","robin","robot","robotics","rock","rocker","rocket","rocket-ship","rod","role","roll","roller","romaine","romance","roof","room","roommate","rooster","root","rope","rose","rosemary","roster","rostrum","rotation","round","roundabout","route","router","routine","row","rowboat","rowing","rubber","rubbish","rubric","ruby","ruckus","rudiment","ruffle","rug","rugby","ruin","rule","ruler","ruling","rum","rumor","run","runaway","runner","running","runway","rush","rust","rutabaga","rye","sabre","sac","sack","saddle","sadness","safari","safe","safeguard","safety","saffron","sage","sail","sailboat","sailing","sailor","saint","sake","salad","salami","salary","sale","salesman","salmon","salon","saloon","salsa","salt","salute","samovar","sampan","sample","samurai","sanction","sanctity","sanctuary","sand","sandal","sandbar","sandpaper","sandwich","sanity","sardine","sari","sarong","sash","satellite","satin","satire","satisfaction","sauce","saucer","sauerkraut","sausage","savage","savannah","saving","savings","savior","saviour","savory","saw","saxophone","scaffold","scale","scallion","scallops","scalp","scam","scanner","scarecrow","scarf","scarification","scenario","scene","scenery","scent","schedule","scheduling","schema","scheme","schizophrenic","schnitzel","scholar","scholarship","school","schoolhouse","schooner","science","scientist","scimitar","scissors","scooter","scope","score","scorn","scorpion","scotch","scout","scow","scrambled","scrap","scraper","scratch","screamer","screen","screening","screenwriting","screw","screw-up","screwdriver","scrim","scrip","script","scripture","scrutiny","sculpting","sculptural","sculpture","sea","seabass","seafood","seagull","seal","seaplane","search","seashore","seaside","season","seat","seaweed","second","secrecy","secret","secretariat","secretary","secretion","section","sectional","sector","security","sediment","seed","seeder","seeker","seep","segment","seizure","selection","self","self-confidence","self-control","self-esteem","seller","selling","semantics","semester","semicircle","semicolon","semiconductor","seminar","senate","senator","sender","senior","sense","sensibility","sensitive","sensitivity","sensor","sentence","sentencing","sentiment","sepal","separation","septicaemia","sequel","sequence","serial","series","sermon","serum","serval","servant","server","service","servitude","sesame","session","set","setback","setting","settlement","settler","severity","sewer","sex","sexuality","shack","shackle","shade","shadow","shadowbox","shakedown","shaker","shallot","shallows","shame","shampoo","shanty","shape","share","shareholder","shark","shaw","shawl","shear","shearling","sheath","shed","sheep","sheet","shelf","shell","shelter","sherbet","sherry","shield","shift","shin","shine","shingle","ship","shipper","shipping","shipyard","shirt","shirtdress","shit","shoat","shock","shoe","shoe-horn","shoehorn","shoelace","shoemaker","shoes","shoestring","shofar","shoot","shootdown","shop","shopper","shopping","shore","shoreline","short","shortage","shorts","shortwave","shot","shoulder","shout","shovel","show","show-stopper","shower","shred","shrimp","shrine","shutdown","sibling","sick","sickness","side","sideboard","sideburns","sidecar","sidestream","sidewalk","siding","siege","sigh","sight","sightseeing","sign","signal","signature","signet","significance","signify","signup","silence","silica","silicon","silk","silkworm","sill","silly","silo","silver","similarity","simple","simplicity","simplification","simvastatin","sin","singer","singing","singular","sink","sinuosity","sip","sir","sister","sister-in-law","sitar","site","situation","size","skate","skating","skean","skeleton","ski","skiing","skill","skin","skirt","skull","skullcap","skullduggery","skunk","sky","skylight","skyline","skyscraper","skywalk","slang","slapstick","slash","slate","slave","slavery","slaw","sled","sledge","sleep","sleepiness","sleeping","sleet","sleuth","slice","slide","slider","slime","slip","slipper","slippers","slope","slot","sloth","slump","smell","smelting","smile","smith","smock","smog","smoke","smoking","smolt","smuggling","snack","snail","snake","snakebite","snap","snarl","sneaker","sneakers","sneeze","sniffle","snob","snorer","snow","snowboarding","snowflake","snowman","snowmobiling","snowplow","snowstorm","snowsuit","snuck","snug","snuggle","soap","soccer","socialism","socialist","society","sociology","sock","socks","soda","sofa","softball","softdrink","softening","software","soil","soldier","sole","solicitation","solicitor","solidarity","solidity","soliloquy","solitaire","solution","solvency","sombrero","somebody","someone","someplace","somersault","something","somewhere","son","sonar","sonata","song","songbird","sonnet","soot","sophomore","soprano","sorbet","sorghum","sorrel","sorrow","sort","soul","soulmate","sound","soundness","soup","source","sourwood","sousaphone","south","southeast","souvenir","sovereignty","sow","soy","soybean","space","spacing","spade","spaghetti","span","spandex","spank","sparerib","spark","sparrow","spasm","spat","spatula","spawn","speaker","speakerphone","speaking","spear","spec","special","specialist","specialty","species","specification","spectacle","spectacles","spectrograph","spectrum","speculation","speech","speed","speedboat","spell","spelling","spelt","spending","sphere","sphynx","spice","spider","spiderling","spike","spill","spinach","spine","spiral","spirit","spiritual","spirituality","spit","spite","spleen","splendor","split","spokesman","spokeswoman","sponge","sponsor","sponsorship","spool","spoon","spork","sport","sportsman","spot","spotlight","spouse","sprag","sprat","spray","spread","spreadsheet","spree","spring","sprinkles","sprinter","sprout","spruce","spud","spume","spur","spy","spyglass","square","squash","squatter","squeegee","squid","squirrel","stab","stability","stable","stack","stacking","stadium","staff","stag","stage","stain","stair","staircase","stake","stalk","stall","stallion","stamen","stamina","stamp","stance","stand","standard","standardisation","standardization","standing","standoff","standpoint","star","starboard","start","starter","state","statement","statin","station","station-wagon","statistic","statistics","statue","status","statute","stay","steak","stealth","steam","steamroller","steel","steeple","stem","stench","stencil","step","step-aunt","step-brother","step-daughter","step-father","step-grandfather","step-grandmother","step-mother","step-sister","step-son","step-uncle","stepdaughter","stepmother","stepping-stone","stepson","stereo","stew","steward","stick","sticker","stiletto","still","stimulation","stimulus","sting","stinger","stir-fry","stitch","stitcher","stock","stock-in-trade","stockings","stole","stomach","stone","stonework","stool","stop","stopsign","stopwatch","storage","store","storey","storm","story","story-telling","storyboard","stot","stove","strait","strand","stranger","strap","strategy","straw","strawberry","strawman","stream","street","streetcar","strength","stress","stretch","strife","strike","string","strip","stripe","strobe","stroke","structure","strudel","struggle","stucco","stud","student","studio","study","stuff","stumbling","stump","stupidity","sturgeon","sty","style","styling","stylus","sub","subcomponent","subconscious","subcontractor","subexpression","subgroup","subject","submarine","submitter","subprime","subroutine","subscription","subsection","subset","subsidence","subsidiary","subsidy","substance","substitution","subtitle","suburb","subway","success","succotash","suck","sucker","suede","suet","suffocation","sugar","suggestion","suicide","suit","suitcase","suite","sulfur","sultan","sum","summary","summer","summit","sun","sunbeam","sunbonnet","sundae","sunday","sundial","sunflower","sunglasses","sunlamp","sunlight","sunrise","sunroom","sunset","sunshine","superiority","supermarket","supernatural","supervision","supervisor","supper","supplement","supplier","supply","support","supporter","suppression","supreme","surface","surfboard","surge","surgeon","surgery","surname","surplus","surprise","surround","surroundings","surrounds","survey","survival","survivor","sushi","suspect","suspenders","suspension","sustainment","sustenance","swallow","swamp","swan","swanling","swath","sweat","sweater","sweatshirt","sweatshop","sweatsuit","sweets","swell","swim","swimming","swimsuit","swine","swing","switch","switchboard","switching","swivel","sword","swordfight","swordfish","sycamore","symbol","symmetry","sympathy","symptom","syndicate","syndrome","synergy","synod","synonym","synthesis","syrup","system","t-shirt","tab","tabby","tabernacle","table","tablecloth","tablet","tabletop","tachometer","tackle","taco","tactics","tactile","tadpole","tag","tail","tailbud","tailor","tailspin","take-out","takeover","tale","talent","talk","talking","tam-o'-shanter","tamale","tambour","tambourine","tan","tandem","tangerine","tank","tank-top","tanker","tankful","tap","tape","tapioca","target","taro","tarragon","tart","task","tassel","taste","tatami","tattler","tattoo","tavern","tax","taxi","taxicab","taxpayer","tea","teacher","teaching","team","teammate","teapot","tear","tech","technician","technique","technologist","technology","tectonics","teen","teenager","teepee","telephone","telescreen","teletype","television","tell","teller","temp","temper","temperature","temple","tempo","temporariness","temporary","temptation","temptress","tenant","tendency","tender","tenement","tenet","tennis","tenor","tension","tensor","tent","tentacle","tenth","tepee","teriyaki","term","terminal","termination","terminology","termite","terrace","terracotta","terrapin","terrarium","territory","terror","terrorism","terrorist","test","testament","testimonial","testimony","testing","text","textbook","textual","texture","thanks","thaw","theater","theft","theism","theme","theology","theory","therapist","therapy","thermals","thermometer","thermostat","thesis","thickness","thief","thigh","thing","thinking","thirst","thistle","thong","thongs","thorn","thought","thousand","thread","threat","threshold","thrift","thrill","throat","throne","thrush","thrust","thug","thumb","thump","thunder","thunderbolt","thunderhead","thunderstorm","thyme","tiara","tic","tick","ticket","tide","tie","tiger","tights","tile","till","tilt","timbale","timber","time","timeline","timeout","timer","timetable","timing","timpani","tin","tinderbox","tinkle","tintype","tip","tire","tissue","titanium","title","toad","toast","toaster","tobacco","today","toe","toenail","toffee","tofu","tog","toga","toilet","tolerance","tolerant","toll","tom-tom","tomatillo","tomato","tomb","tomography","tomorrow","ton","tonality","tone","tongue","tonic","tonight","tool","toot","tooth","toothbrush","toothpaste","toothpick","top","top-hat","topic","topsail","toque","toreador","tornado","torso","torte","tortellini","tortilla","tortoise","tosser","total","tote","touch","tough-guy","tour","tourism","tourist","tournament","tow-truck","towel","tower","town","townhouse","township","toy","trace","trachoma","track","tracking","tracksuit","tract","tractor","trade","trader","trading","tradition","traditionalism","traffic","trafficker","tragedy","trail","trailer","trailpatrol","train","trainer","training","trait","tram","tramp","trance","transaction","transcript","transfer","transformation","transit","transition","translation","transmission","transom","transparency","transplantation","transport","transportation","trap","trapdoor","trapezium","trapezoid","trash","travel","traveler","tray","treasure","treasury","treat","treatment","treaty","tree","trek","trellis","tremor","trench","trend","triad","trial","triangle","tribe","tributary","trick","trigger","trigonometry","trillion","trim","trinket","trip","tripod","tritone","triumph","trolley","trombone","troop","trooper","trophy","trouble","trousers","trout","trove","trowel","truck","trumpet","trunk","trust","trustee","truth","try","tsunami","tub","tuba","tube","tuber","tug","tugboat","tuition","tulip","tumbler","tummy","tuna","tune","tune-up","tunic","tunnel","turban","turf","turkey","turmeric","turn","turning","turnip","turnover","turnstile","turret","turtle","tusk","tussle","tutu","tuxedo","tweet","tweezers","twig","twilight","twine","twins","twist","twister","twitter","type","typeface","typewriter","typhoon","ukulele","ultimatum","umbrella","unblinking","uncertainty","uncle","underclothes","underestimate","underground","underneath","underpants","underpass","undershirt","understanding","understatement","undertaker","underwear","underweight","underwire","underwriting","unemployment","unibody","uniform","uniformity","union","unique","unit","unity","universe","university","update","upgrade","uplift","upper","upstairs","upward","urge","urgency","urn","usage","use","user","usher","usual","utensil","utilisation","utility","utilization","vacation","vaccine","vacuum","vagrant","valance","valentine","validate","validity","valley","valuable","value","vampire","van","vanadyl","vane","vanilla","vanity","variability","variable","variant","variation","variety","vascular","vase","vault","vaulting","veal","vector","vegetable","vegetarian","vegetarianism","vegetation","vehicle","veil","vein","veldt","vellum","velocity","velodrome","velvet","vendor","veneer","vengeance","venison","venom","venti","venture","venue","veranda","verb","verdict","verification","vermicelli","vernacular","verse","version","vertigo","verve","vessel","vest","vestment","vet","veteran","veterinarian","veto","viability","vibe","vibraphone","vibration","vibrissae","vice","vicinity","victim","victory","video","view","viewer","vignette","villa","village","vine","vinegar","vineyard","vintage","vintner","vinyl","viola","violation","violence","violet","violin","virginal","virtue","virus","visa","viscose","vise","vision","visit","visitor","visor","vista","visual","vitality","vitamin","vitro","vivo","vixen","vodka","vogue","voice","void","vol","volatility","volcano","volleyball","volume","volunteer","volunteering","vomit","vote","voter","voting","voyage","vulture","wad","wafer","waffle","wage","wagon","waist","waistband","wait","waiter","waiting","waitress","waiver","wake","walk","walker","walking","walkway","wall","wallaby","wallet","walnut","walrus","wampum","wannabe","want","war","warden","wardrobe","warfare","warlock","warlord","warm-up","warming","warmth","warning","warrant","warren","warrior","wasabi","wash","washbasin","washcloth","washer","washtub","wasp","waste","wastebasket","wasting","watch","watcher","watchmaker","water","waterbed","watercress","waterfall","waterfront","watermelon","waterskiing","waterspout","waterwheel","wave","waveform","wax","way","weakness","wealth","weapon","wear","weasel","weather","web","webinar","webmail","webpage","website","wedding","wedge","weed","weeder","weedkiller","week","weekend","weekender","weight","weird","welcome","welfare","well","well-being","west","western","wet-bar","wetland","wetsuit","whack","whale","wharf","wheat","wheel","whelp","whey","whip","whirlpool","whirlwind","whisker","whiskey","whisper","whistle","white","whole","wholesale","wholesaler","whorl","wick","widget","widow","width","wife","wifi","wild","wildebeest","wilderness","wildlife","will","willingness","willow","win","wind","wind-chime","windage","window","windscreen","windshield","wine","winery","wing","wingman","wingtip","wink","winner","winter","wire","wiretap","wiring","wisdom","wiseguy","wish","wisteria","wit","witch","witch-hunt","withdrawal","witness","wok","wolf","woman","wombat","wonder","wont","wood","woodchuck","woodland","woodshed","woodwind","wool","woolens","word","wording","work","workbench","worker","workforce","workhorse","working","workout","workplace","workshop","world","worm","worry","worship","worshiper","worth","wound","wrap","wraparound","wrapper","wrapping","wreck","wrecker","wren","wrench","wrestler","wriggler","wrinkle","wrist","writer","writing","wrong","xylophone","yacht","yahoo","yak","yam","yang","yard","yarmulke","yarn","yawl","year","yeast","yellow","yellowjacket","yesterday","yew","yin","yoga","yogurt","yoke","yolk","young","youngster","yourself","youth","yoyo","yurt","zampone","zebra","zebrafish","zen","zephyr","zero","ziggurat","zinc","zipper","zither","zombie","zone","zoo","zoologist","zoology","zoot-suit","zucchini"];var An=["a","abaft","aboard","about","above","absent","across","afore","after","against","along","alongside","amid","amidst","among","amongst","an","anenst","anti","apropos","apud","around","as","aside","astride","at","athwart","atop","barring","before","behind","below","beneath","beside","besides","between","beyond","but","by","circa","concerning","considering","despite","down","during","except","excepting","excluding","failing","following","for","forenenst","from","given","in","including","inside","into","lest","like","mid","midst","minus","modulo","near","next","notwithstanding","of","off","on","onto","opposite","out","outside","over","pace","past","per","plus","pro","qua","regarding","round","sans","save","since","than","the","through","throughout","till","times","to","toward","towards","under","underneath","unlike","until","unto","up","upon","versus","via","vice","with","within","without","worth"];var En=["abandon","abase","abate","abbreviate","abdicate","abduct","abet","abhor","abide","abjure","abnegate","abolish","abominate","abort","abound","abrade","abridge","abrogate","abscond","abseil","absent","absolve","absorb","abstain","abstract","abuse","abut","accede","accelerate","accent","accentuate","accept","access","accessorise","accessorize","acclaim","acclimate","acclimatise","acclimatize","accommodate","accompany","accomplish","accord","accost","account","accouter","accoutre","accredit","accrue","acculturate","accumulate","accuse","accustom","ace","ache","achieve","acidify","acknowledge","acquaint","acquiesce","acquire","acquit","act","action","activate","actualise","actualize","actuate","adapt","add","addle","address","adduce","adhere","adjoin","adjourn","adjudge","adjudicate","adjure","adjust","administer","admire","admit","admonish","adopt","adore","adorn","adsorb","adulterate","adumbrate","advance","advantage","advertise","advise","advocate","aerate","affect","affiliate","affirm","affix","afflict","afford","afforest","affront","age","agglomerate","aggravate","aggregate","agitate","agonise","agonize","agree","aid","ail","aim","air","airbrush","airdrop","airfreight","airlift","alarm","alert","alienate","alight","align","allay","allege","alleviate","allocate","allot","allow","alloy","allude","ally","alphabetise","alphabetize","alter","alternate","amalgamate","amass","amaze","amble","ambush","ameliorate","amend","amortise","amortize","amount","amplify","amputate","amuse","anaesthetise","anaesthetize","analyse","anchor","anesthetize","anger","angle","anglicise","anglicize","animate","anneal","annex","annihilate","annotate","announce","annoy","annul","anodise","anodize","anoint","anonymise","anonymize","answer","antagonise","antagonize","antedate","anthologise","anthologize","anticipate","ape","apologise","apologize","apostrophise","apostrophize","appal","appall","appeal","appear","appease","append","appertain","applaud","apply","appoint","apportion","appraise","appreciate","apprehend","apprentice","apprise","approach","appropriate","approve","approximate","aquaplane","arbitrate","arc","arch","archive","argue","arise","arm","arouse","arraign","arrange","array","arrest","arrive","arrogate","arse","art","articulate","ascend","ascertain","ascribe","ask","asphyxiate","aspirate","aspire","assail","assassinate","assault","assay","assemble","assent","assert","assess","assign","assimilate","assist","associate","assuage","assume","assure","asterisk","astonish","astound","atomise","atomize","atone","atrophy","attach","attack","attain","attempt","attend","attenuate","attest","attract","attribute","auction","audit","audition","augment","augur","authenticate","author","authorise","authorize","autograph","automate","autosave","autowind","avail","avenge","aver","average","avert","avoid","avow","await","awake","awaken","award","awe","ax","axe","baa","babble","baby","babysit","back","backcomb","backdate","backfill","backfire","backlight","backpack","backspace","backtrack","badger","baffle","bag","bail","bait","bake","balance","bale","ball","balloon","ballot","balls","bamboozle","ban","band","bandage","bandy","bang","bangs","banish","bank","bankroll","bankrupt","banter","baptise","baptize","bar","barbecue","bare","barf","bargain","barge","bark","barnstorm","barrack","barrel","barricade","barter","base","bash","bask","bastardise","bastardize","baste","bat","batch","bath","bathe","batten","batter","battle","baulk","bawl","bay","bayonet","be","beach","beam","bean","bear","beard","beat","beatbox","beatboxer","beatify","beautify","beaver","beckon","become","bed","bedazzle","bedeck","bedevil","beef","beep","beetle","befall","befit","befog","befriend","beg","beget","beggar","begin","begrudge","beguile","behave","behead","behold","behoove","behove","belabor","belabour","belay","belch","belie","believe","belittle","bellow","belly","bellyache","belong","belt","bemoan","bemuse","benchmark","bend","benefit","bequeath","berate","bereave","berth","beseech","beset","besiege","besmirch","bespatter","bespeak","best","bestir","bestow","bestride","bet","betake","betide","betoken","betray","better","bewail","beware","bewilder","bewitch","bias","bicker","bicycle","bid","bide","biff","bifurcate","big","bike","bilk","bill","billet","billow","bin","bind","binge","biodegrade","bird","bisect","bitch","bite","bitmap","bivouac","bivvy","blab","blabber","black","blackball","blacken","blacklist","blackmail","blag","blame","blanch","blank","blanket","blare","blaspheme","blast","blather","blaze","blazon","bleach","bleat","bleed","bleep","blemish","blench","blend","bless","blight","blind","blindfold","blindfolded","blindside","blink","bliss","blister","blitz","bloat","block","blockade","blog","blood","bloom","bloop","blossom","blot","blow","blub","blubber","bludge","bludgeon","bluff","blunder","blunt","blur","blurt","blush","bluster","board","boast","bob","bobble","bode","bodge","bog","boggle","boil","bolster","bolt","bomb","bombard","bond","bone","bonk","boo","boob","boogie","book","bookmark","boom","boomerang","boost","boot","bootleg","booze","bop","border","bore","born","borrow","boss","botch","bother","bottle","bottleful","bottom","bounce","bound","bow","bowdlerise","bowdlerize","bowl","bowlful","box","boycott","braai","brace","braces","bracket","brag","braid","brain","brainstorm","brainwash","braise","brake","branch","brand","brandish","brave","brawl","bray","brazen","breach","break","breakfast","breast","breastfeed","breathalyse","breathalyze","breathe","breed","breeze","brew","bribe","brick","bridge","bridle","brief","brighten","brim","bring","bristle","broach","broadcast","broaden","broadside","broil","broker","brood","brook","browbeat","brown","browse","bruise","bruit","brush","brutalise","brutalize","bubble","buck","bucket","bucketful","buckle","bud","buddy","budge","budget","buff","buffer","buffet","bug","bugger","build","bulge","bulk","bulldoze","bullshit","bully","bum","bumble","bump","bunch","bundle","bung","bungle","bunk","bunker","bunt","buoy","burble","burden","burgeon","burglarize","burgle","burn","burnish","burp","burrow","burst","bury","bus","bushwhack","busk","bust","bustle","busy","butcher","butt","butter","button","buttonhole","buttress","buy","buzz","buzzing","bypass","cable","cache","cackle","caddie","cadge","cage","cajole","cake","calcify","calculate","calibrate","call","calm","calve","camouflage","camp","campaign","can","canalise","canalize","cancel","cane","cannibalise","cannibalize","cannon","cannulate","canoe","canonise","canonize","canoodle","canst","cant","canter","canvass","cap","caper","capitalise","capitalize","capitulate","capsize","captain","caption","captivate","capture","caramelise","caramelize","carbonise","carbonize","carburise","carburize","card","care","careen","career","caress","caricature","carjack","carol","carom","carouse","carp","carpet","carpool","carry","cart","cartwheel","carve","cascade","case","cash","cashier","casserole","cast","castigate","castrate","catalog","catalogue","catalyse","catalyze","catapult","catch","categorise","categorize","cater","caterwaul","catnap","caucus","caulk","cause","cauterise","cauterize","caution","cave","cavil","cavort","caw","cc","cease","cede","celebrate","cement","censor","censure","centralise","centralize","centre","certificate","certify","chafe","chaff","chain","chair","chalk","challenge","champ","champion","chance","change","channel","chant","chaperon","chaperone","char","characterise","characterize","charbroil","charge","chargesheet","chargrill","charm","chart","charter","chase","chasten","chastise","chat","chatter","chauffeur","cheapen","cheat","cheater","check","checkmate","cheek","cheep","cheer","cherish","chew","chicken","chide","chill","chillax","chime","chink","chip","chirp","chisel","chivvy","chlorinate","choke","chomp","choose","chop","choreograph","chortle","chorus","christen","chromakey","chronicle","chuck","chuckle","chug","chunder","chunter","churn","cinch","circle","circulate","circumcise","circumnavigate","circumscribe","circumvent","cite","civilise","civilize","clack","claim","clam","clamber","clamor","clamour","clamp","clang","clank","clap","clarify","clash","clasp","class","classify","clatter","claw","clean","cleanse","clear","cleave","clench","clerk","click","climax","climb","clinch","cling","clink","clinking","clip","cloak","clobber","clock","clog","clone","clonk","close","closet","clot","clothe","cloud","clout","clown","club","cluck","clue","clump","clunk","cluster","clutch","clutter","coach","coagulate","coalesce","coarsen","coast","coat","coax","cobble","cock","cocoon","coddle","code","codify","coerce","coexist","cogitate","cohabit","cohere","coil","coin","coincide","collaborate","collapse","collar","collate","collect","collectivise","collectivize","collide","colligate","collocate","collude","colonise","colonize","colorize","colour","comb","combat","combine","combust","come","comfort","command","commandeer","commemorate","commence","commend","comment","commentate","commercialise","commercialize","commingle","commiserate","commission","commit","commune","communicate","commute","compact","compare","compartmentalise","compartmentalize","compel","compensate","compete","compile","complain","complement","complete","complicate","compliment","comply","comport","compose","compost","compound","comprehend","compress","comprise","compromise","compute","computerise","computerize","con","conceal","concede","conceive","concentrate","conceptualise","conceptualize","concern","concertina","conciliate","conclude","concoct","concrete","concur","concuss","condemn","condense","condescend","condition","condone","conduct","cone","confer","confess","confide","configure","confine","confirm","confiscate","conflate","conflict","conform","confound","confront","confuse","confute","congeal","congratulate","congregate","conjecture","conjoin","conjugate","conjure","conk","connect","connive","connote","conquer","conscientise","conscientize","conscript","consecrate","consent","conserve","consider","consign","consist","console","consolidate","consort","conspire","constitute","constrain","constrict","construct","construe","consult","consume","consummate","contact","contain","contaminate","contemplate","contend","content","contest","contextualise","contextualize","continue","contort","contract","contradict","contraindicate","contrast","contravene","contribute","contrive","control","controvert","convalesce","convene","converge","converse","convert","convey","convict","convince","convoke","convulse","coo","cook","cool","coop","cooperate","coordinate","cop","cope","coppice","copulate","copy","copyright","cordon","core","cork","corkscrew","corner","corral","correct","correlate","correspond","corrode","corrupt","coruscate","cosh","cosset","cost","cosy","cotton","couch","cough","counsel","count","countenance","counter","counteract","counterbalance","counterfeit","countermand","counterpoint","countersign","couple","courier","course","court","covenant","cover","covet","cow","cower","cox","cozy","crack","crackle","cradle","craft","cram","cramp","crane","crank","crap","crash","crate","crave","crawl","crayon","creak","creaking","cream","crease","create","credential","credit","creep","cremate","creolise","creolize","creosote","crest","crew","crib","crick","criminalise","criminalize","crimp","cringe","crinkle","cripple","crisp","criticise","criticize","critique","croak","crochet","crook","croon","crop","cross","crouch","crow","crowd","crown","crucify","cruise","crumble","crumple","crunch","crusade","crush","cry","crystallise","crystallize","cube","cuckold","cuddle","cudgel","cue","cuff","cull","culminate","cultivate","culture","cup","curate","curb","curdle","cure","curl","curry","curse","curtail","curtain","curtsy","curve","cushion","cuss","customise","customize","cut","cwtch","cycle","dab","dabble","dally","dam","damage","dammit","damn","damp","dampen","dance","dandle","dangle","dare","darken","darn","dart","dash","date","daub","daunt","dawdle","dawn","daydream","dazzle","deactivate","deaden","deadhead","deafen","deal","debar","debase","debate","debilitate","debit","debrief","debug","debunk","debut","decamp","decant","decapitate","decay","deceive","decelerate","decentralise","decentralize","decide","decimalise","decimalize","decimate","decipher","deck","declaim","declare","declassify","decline","declutter","decode","decommission","decompose","decompress","deconsecrate","deconstruct","decontaminate","decontrol","decorate","decouple","decoy","decrease","decree","decriminalise","decriminalize","decry","decrypt","dedicate","deduce","deduct","deejay","deem","deepen","deface","defame","default","defeat","defecate","defect","defend","defer","defile","define","deflate","deflect","deflower","defog","defoliate","deforest","deform","defrag","defragment","defraud","defray","defrock","defrost","defuse","defy","degenerate","deglaze","degrade","degrease","dehumanise","dehumanize","dehydrate","deify","deign","delay","delegate","delete","deliberate","delight","delimit","delineate","deliquesce","deliver","delouse","delude","deluge","delve","demand","demarcate","demean","demerge","demilitarise","demilitarize","demineralise","demineralize","demist","demo","demob","demobilise","demobilize","democratise","democratize","demolish","demonise","demonize","demonstrate","demoralise","demoralize","demote","demotivate","demur","demystify","denationalise","denationalize","denigrate","denitrify","denominate","denote","denounce","dent","denude","deny","depart","depend","depersonalise","depersonalize","depict","deplane","deplete","deplore","deploy","depopulate","deport","depose","deposit","deprave","deprecate","depreciate","depress","depressurise","depressurize","deprive","depute","deputise","deputize","deracinate","derail","dereference","deregulate","deride","derive","derogate","descale","descend","describe","descry","desecrate","desegregate","deselect","desensitise","desensitize","desert","deserve","design","designate","desire","desist","deskill","desolate","despair","despise","despoil","destabilise","destabilize","destock","destroy","detach","detail","detain","detect","deter","deteriorate","determine","detest","dethrone","detonate","detour","detoxify","detract","detrain","devalue","devastate","develop","deviate","devise","devoice","devolve","devote","devour","diagnose","dial","dice","dicker","dictate","diddle","die","diet","differ","differentiate","diffract","diffuse","dig","digest","digitalise","digitalize","digitise","digitize","dignify","digress","dilate","dilute","diluted","dim","diminish","dimple","dine","ding","dink","dip","diphthongise","diphthongize","direct","dirty","dis","disable","disabuse","disadvantage","disaffiliate","disafforest","disagree","disallow","disambiguate","disappear","disappoint","disapprove","disarm","disarrange","disassemble","disassociate","disavow","disband","disbar","disbelieve","disburse","discard","discern","discharge","discipline","disclaim","disclose","discolor","discolour","discomfit","discomfort","discompose","disconcert","disconnect","discontinue","discount","discourage","discourse","discover","discredit","discriminate","discuss","disdain","disembark","disembowel","disenfranchise","disengage","disentangle","disestablish","disfigure","disgorge","disgrace","disguise","disgust","dish","dishearten","dishonor","dishonour","disillusion","disincentivise","disincentivize","disinfect","disinherit","disinhibit","disintegrate","disinter","disinvest","dislike","dislocate","dislodge","dismantle","dismay","dismember","dismiss","dismount","disobey","disorient","disorientate","disown","disparage","dispatch","dispel","dispense","disperse","displace","display","displease","disport","dispose","dispossess","disprove","dispute","disqualify","disregard","disrespect","disrobe","disrupt","dissect","dissemble","disseminate","dissent","dissimulate","dissipate","dissociate","dissolve","dissuade","distance","distend","distil","distill","distinguish","distort","distract","distress","distribute","distrust","disturb","disunite","ditch","dither","dive","diverge","diversify","divert","divest","divide","divine","divorce","divulge","divvy","do","dob","dock","doctor","document","dodge","doff","dog","dole","doll","dollarise","dollarize","domesticate","dominate","don","donate","doodle","doom","doorstep","dop","dope","dose","doss","dot","dote","double","doubt","douche","douse","dovetail","down","downchange","downgrade","downlink","download","downplay","downshift","downsize","dowse","doze","draft","drag","dragoon","drain","dramatise","dramatize","drape","draught","draw","drawl","dread","dream","dredge","drench","dress","dribble","drift","drill","drink","drip","drive","drivel","drizzle","drone","drool","droop","drop","drown","drowse","drug","drum","dry","dub","duck","duckie","ducks","duel","duff","dull","dumb","dumbfound","dummy","dump","dunk","dunt","dupe","duplicate","dust","dwarf","dwell","dwindle","dye","dynamite","earmark","earn","earth","ease","eat","eavesdrop","ebb","echo","eclipse","economise","economize","eddy","edge","edify","edit","editorialise","editorialize","educate","eff","efface","effect","effectuate","egg","ejaculate","eject","eke","elaborate","elapse","elbow","elect","electrify","electrocute","electroplate","elevate","elicit","elide","eliminate","elongate","elope","elucidate","elude","email","emanate","emancipate","emasculate","embalm","embargo","embark","embarrass","embed","embellish","embezzle","embitter","emblazon","embody","embolden","emboss","embrace","embroider","embroil","emcee","emend","emerge","emigrate","emit","emote","empathise","empathize","emphasise","emphasize","employ","empower","empty","emulate","emulsify","enable","enact","encamp","encapsulate","encase","encash","enchant","encircle","enclose","encode","encompass","encounter","encourage","encroach","encrypt","encumber","end","endanger","endear","endeavor","endeavour","endorse","endow","endure","energise","energize","enervate","enfeeble","enfold","enforce","enfranchise","engage","engender","engineer","engorge","engrave","engross","engulf","enhance","enjoin","enjoy","enlarge","enlighten","enlist","enliven","enmesh","ennoble","enquire","enrage","enrapture","enrich","enrol","enroll","ensconce","enshrine","enshroud","enslave","ensnare","ensue","ensure","entail","entangle","enter","entertain","enthral","enthrall","enthrone","enthuse","entice","entitle","entomb","entrance","entrap","entreat","entrench","entrust","entwine","enumerate","enunciate","envelop","envisage","envision","envy","epitomise","epitomize","equal","equalise","equalize","equate","equip","equivocate","eradicate","erase","erect","erode","err","erupt","escalate","escape","eschew","escort","espouse","espy","essay","establish","esteem","estimate","etch","eulogise","eulogize","euthanise","euthanize","evacuate","evade","evaluate","evangelise","evangelize","evaporate","even","eventuate","evict","evidence","evince","eviscerate","evoke","evolve","exacerbate","exact","exaggerate","exalt","examine","exasperate","excavate","exceed","excel","except","excerpt","exchange","excise","excite","exclaim","exclude","excommunicate","excoriate","excrete","exculpate","excuse","execute","exemplify","exempt","exercise","exert","exeunt","exfoliate","exhale","exhaust","exhibit","exhilarate","exhort","exhume","exile","exist","exit","exonerate","exorcise","exorcize","expand","expatiate","expect","expectorate","expedite","expel","expend","experience","experiment","expiate","expire","explain","explicate","explode","exploit","explore","export","expose","expostulate","expound","express","expropriate","expunge","expurgate","extemporise","extemporize","extend","exterminate","externalise","externalize","extinguish","extirpate","extol","extort","extract","extradite","extrapolate","extricate","extrude","exude","exult","eye","eyeball","eyeglasses","fabricate","face","facilitate","factor","factorise","factorize","fade","faff","fail","faint","fake","fall","falsify","falter","familiarise","familiarize","fan","fancy","fantasise","fantasize","fare","farewell","farm","farrow","fart","fascinate","fashion","fast","fasten","father","fathom","fatten","fault","favor","favour","fawn","fax","faze","fear","feast","feather","feature","federate","feed","feel","feign","feint","fell","fellate","feminise","feminize","fence","fend","ferment","ferret","ferry","fertilise","fertilize","fess","fester","festoon","fetch","fete","fetishise","fetishize","fetter","feud","fib","fictionalise","fictionalize","fiddle","fidget","field","fight","figure","filch","file","filibuster","fill","fillet","film","filter","finagle","finalise","finalize","finance","find","fine","finesse","finger","fingerprint","finish","fire","firebomb","firm","fish","fishtail","fit","fix","fizz","fizzle","flag","flagellate","flail","flake","flame","flank","flap","flare","flash","flat","flatline","flatten","flatter","flaunt","flavour","flay","fleck","flee","fleece","flesh","flex","flick","flicker","flight","flinch","fling","flip","flirt","flit","float","flock","flog","flood","floodlight","floor","flop","floss","flounce","flounder","flour","flourish","flout","flow","flower","flub","fluctuate","fluff","flummox","flunk","flush","fluster","flutter","fly","foal","foam","fob","focalise","focalize","focus","fog","foil","foist","fold","follow","foment","fondle","fool","foot","forage","forbear","forbid","force","ford","forearm","forecast","foreclose","foregather","foreground","foresee","foreshadow","foreshorten","forestall","foretell","forewarn","forfeit","forfend","forgather","forge","forget","forgive","forgo","fork","form","formalise","formalize","format","formulate","fornicate","forsake","forswear","fortify","forward","forwards","fossick","fossilise","fossilize","foster","foul","found","founder","fox","fracture","fragment","frame","franchise","frank","fraternise","fraternize","fray","freak","free","freelance","freeload","freestyle","freewheel","freeze","freight","frequent","freshen","fret","frighten","fringe","frisk","fritter","frizz","frizzle","frogmarch","frolic","front","frost","froth","frown","fruit","frustrate","fry","fuck","fudge","fuel","fulfil","fulfill","fulminate","fumble","fume","fumigate","function","fund","funk","funnel","furl","furlough","furnish","furrow","further","fuse","fuss","gab","gabble","gad","gag","gain","gainsay","gall","gallivant","gallop","galumph","galvanise","galvanize","gamble","gambol","gang","gape","garage","garden","gargle","garland","garner","garnish","garrison","garrote","garrotte","gas","gash","gasp","gatecrash","gather","gauge","gawk","gawp","gaze","gazump","gazunder","gear","gee","gel","geld","gen","generalise","generalize","generate","gentrify","genuflect","germinate","gerrymander","gestate","gesticulate","gesture","get","ghost","ghostwrite","gibber","gift","giggle","gild","ginger","gird","girdle","give","gladden","glamorise","glamorize","glance","glare","glass","glaze","gleam","glean","glide","glimmer","glimmering","glimpse","glint","glisten","glister","glitter","gloat","globalise","globalize","glom","glorify","glory","gloss","glow","glower","glue","glug","glut","gnash","gnaw","go","goad","gob","gobble","goggle","goldbrick","goof","google","goose","gore","gorge","gossip","gouge","govern","grab","grace","grade","graduate","graft","grant","grapple","grasp","grass","grate","gratify","gravitate","graze","grease","green","greet","grey","grieve","grill","grimace","grin","grind","grip","gripe","grit","grizzle","groan","grok","groom","grope","gross","grouch","ground","group","grouse","grout","grovel","grow","growl","grub","grudge","grumble","grunt","guarantee","guard","guess","guest","guffaw","guide","guillotine","guilt","gulp","gum","gun","gurgle","gurn","gush","gussy","gust","gut","gutter","guzzle","gybe","gyp","gyrate","hack","haemorrhage","haggle","hail","hallmark","halloo","hallucinate","halt","halve","ham","hammer","hamper","hamstring","hand","handcuff","handicap","handle","hang","hanker","happen","harangue","harass","harbor","harbour","harden","hare","hark","harm","harmonise","harmonize","harness","harp","harpoon","harrow","harrumph","harry","harvest","hash","hassle","hasten","hatch","hate","haul","haunt","have","haw","hawk","hazard","haze","head","headbutt","headhunt","headline","heal","heap","hear","hearken","hearten","heat","heave","heckle","hector","hedge","heed","heel","heft","heighten","heist","help","hem","hemorrhage","herald","herd","hesitate","hew","hex","hibernate","hiccough","hiccup","hide","hie","highball","highlight","hightail","hijack","hike","hinder","hinge","hint","hire","hiss","hit","hitch","hitchhike","hive","hoard","hoax","hobble","hobnob","hock","hoe","hog","hoick","hoist","hold","hole","holiday","holler","hollow","holster","home","homeschool","homestead","hone","honeymoon","honk","honour","hoodwink","hoof","hook","hoon","hoot","hoover","hop","hope","horn","horrify","horse","horsewhip","hose","hosepipe","hospitalise","hospitalize","host","hot","hotfoot","hound","house","hover","howl","huddle","huff","hug","hull","hum","humanise","humanize","humble","humiliate","humour","hump","hunch","hunger","hunker","hunt","hurdle","hurl","hurry","hurt","hurtle","husband","hush","husk","hustle","hybridise","hybridize","hydrate","hydroplane","hype","hyperventilate","hyphenate","hypnotise","hypnotize","hypothesise","hypothesize","ice","iconify","idealise","idealize","ideate","identify","idle","idolise","idolize","ignite","ignore","illuminate","illumine","illustrate","imagine","imagineer","imbibe","imbue","imitate","immerse","immigrate","immobilise","immobilize","immolate","immortalise","immortalize","immunise","immunize","immure","impact","impair","impale","impanel","impart","impeach","impede","impel","imperil","impersonate","impinge","implant","implement","implicate","implode","implore","imply","import","importune","impose","impound","impoverish","impregnate","impress","imprint","imprison","improve","improvise","impugn","inactivate","inaugurate","incapacitate","incarcerate","incarnate","incense","incentivise","incentivize","inch","incinerate","incise","incite","incline","include","incommode","inconvenience","incorporate","increase","incriminate","incubate","inculcate","incur","indemnify","indent","index","indicate","indict","individualise","individualize","individuate","indoctrinate","induce","induct","indulge","industrialise","industrialize","infantilise","infantilize","infect","infer","infest","infill","infiltrate","inflame","inflate","inflect","inflict","influence","inform","infringe","infuriate","infuse","ingest","ingratiate","inhabit","inhale","inhere","inherit","inhibit","initial","initialise","initialize","initiate","inject","injure","ink","inlay","innovate","inoculate","input","inscribe","inseminate","insert","inset","insinuate","insist","inspect","inspire","install","instance","instigate","instil","instill","institute","institutionalise","institutionalize","instruct","insulate","insult","insure","integrate","intend","intensify","inter","interact","interbreed","intercede","intercept","interchange","interconnect","intercut","interest","interface","interfere","interject","interlace","interleave","interlink","interlock","intermarry","intermesh","intermingle","intermix","intern","internalise","internalize","internationalise","internationalize","interpenetrate","interpolate","interpose","interpret","interrelate","interrogate","interrupt","intersect","intersperse","intertwine","intervene","interview","interweave","interwork","intimate","intimidate","intone","intoxicate","intrigue","introduce","intrude","intubate","intuit","inundate","inure","invade","invalid","invalidate","inveigh","inveigle","invent","inventory","invert","invest","investigate","invigilate","invigorate","invite","invoice","invoke","involve","ionise","ionize","irk","iron","irradiate","irrigate","irritate","irrupt","isolate","issue","italicise","italicize","itch","itemise","itemize","iterate","jab","jabber","jack","jackknife","jail","jam","jangle","jar","jaw","jaywalk","jazz","jeer","jell","jeopardise","jeopardize","jerk","jest","jet","jettison","jib","jibe","jig","jiggle","jilt","jingle","jink","jinx","jive","jockey","jog","joggle","join","joint","joke","jol","jolly","jolt","josh","jostle","jot","journey","joust","judder","judge","juggle","juice","jumble","jump","junk","justify","jut","juxtapose","keel","keelhaul","keen","keep","ken","key","keyboard","kibitz","kick","kid","kidnap","kill","kindle","kink","kip","kiss","kit","kite","klap","kludge","knacker","knead","knee","kneecap","kneel","knife","knight","knit","knock","knot","know","knuckle","kowtow","kvetch","label","labour","lace","lacerate","lack","lacquer","lactate","ladder","ladle","lag","lam","lamb","lambast","lambaste","lament","lamp","lampoon","lance","land","lands","landscape","languish","lap","lapse","lard","large","lark","lash","lasso","last","latch","lather","laud","laugh","launch","launder","lavish","lay","layer","laze","leach","lead","leaf","leaflet","leak","lean","leap","leapfrog","learn","lease","leash","leave","leaven","lech","lecture","leer","leg","legalise","legalize","legislate","legitimise","legitimize","lend","lengthen","lessen","let","letter","letterbox","level","lever","leverage","levitate","levy","liaise","libel","liberalise","liberalize","liberate","license","lick","lie","lift","ligate","light","lighten","like","liken","limber","lime","limit","limp","line","linger","link","lionise","lionize","liquefy","liquidate","liquidise","liquidize","lisp","list","listen","litigate","litter","live","liven","load","loads","loaf","loan","loathe","lob","lobby","lobotomise","lobotomize","localise","localize","locate","lock","lodge","loft","log","loiter","loll","lollop","long","look","looks","loom","loop","loose","loosen","loot","lop","lope","lord","lose","lounge","lour","louse","love","low","lowball","lower","lubricate","luck","lug","lull","lumber","lump","lunch","lunge","lurch","lure","lurk","lust","luxuriate","lynch","macerate","machine","madden","magic","magnetise","magnetize","magnify","mail","maim","mainline","mainstream","maintain","major","make","malfunction","malign","malinger","maltreat","man","manacle","manage","mandate","mangle","manhandle","manicure","manifest","manipulate","manoeuvre","mantle","manufacture","manure","map","mar","march","marginalise","marginalize","marinate","mark","market","maroon","marry","marshal","martyr","marvel","masculinise","masculinize","mash","mask","masquerade","mass","massacre","massage","master","mastermind","masticate","masturbate","match","mate","materialise","materialize","matriculate","matter","mature","maul","maunder","max","maximise","maximize","mean","meander","measure","mechanise","mechanize","medal","meddle","mediate","medicate","meditate","meet","meld","mellow","melt","memorialise","memorialize","memorise","memorize","menace","mend","menstruate","mention","meow","mercerise","mercerize","merchandise","merge","merit","mesh","mesmerise","mesmerize","mess","message","metabolise","metabolize","metamorphose","mete","meter","methinks","mew","mewl","miaow","microblog","microchip","micromanage","microwave","micturate","migrate","militarise","militarize","militate","milk","mill","mime","mimic","mince","mind","mine","mingle","miniaturise","miniaturize","minimise","minimize","minister","minor","mint","minute","mirror","misapply","misappropriate","misbehave","miscalculate","miscarry","miscast","misconceive","misconstrue","miscount","misdiagnose","misdial","misdirect","misfile","misfire","misgovern","mishandle","mishear","mishit","misinform","misinterpret","misjudge","miskey","mislay","mislead","mismanage","mismatch","misname","misplace","misplay","mispronounce","misquote","misread","misreport","misrepresent","miss","mission","misspell","misspend","mist","mistake","mistime","mistreat","mistrust","misunderstand","misuse","mitigate","mitre","mix","moan","mob","mobilise","mobilize","mock","mod","model","moderate","modernise","modernize","modify","modulate","moisten","moisturise","moisturize","mold","molder","molest","mollify","mollycoddle","molt","monitor","monopolise","monopolize","moo","mooch","moon","moonlight","moonwalk","moor","moot","mop","mope","moralise","moralize","morph","mortar","mortgage","mortify","mosey","mosh","mothball","mother","motion","motivate","motor","mould","moulder","moult","mount","mourn","mouse","mouth","move","movies","mow","muck","muddle","muddy","muff","muffle","mug","mulch","mull","multicast","multiply","multitask","mumble","mumbling","mummify","munch","murder","murmur","murmuring","murmurings","muscle","muse","mushroom","muss","muster","mutate","mute","mutilate","mutiny","mutter","muzzle","mystify","nab","nag","nail","name","namecheck","nap","narrate","narrow","narrowcast","nasalise","nasalize","nationalise","nationalize","natter","naturalise","naturalize","nauseate","navigate","near","nearer","nearest","neaten","necessitate","neck","necklace","need","needle","negate","negative","neglect","negotiate","neigh","nerve","nest","nestle","net","nettle","network","neuter","neutralise","neutralize","nibble","nick","nickname","niggle","nip","nitrify","nix","nobble","nod","nominalize","nominate","norm","normalise","normalize","nose","nosedive","nosh","notarise","notarize","notch","note","notice","notify","nourish","nudge","nuke","nullify","numb","number","nurse","nurture","nut","nuzzle","obey","obfuscate","object","objectify","oblige","obliterate","obscure","observe","obsess","obstruct","obtain","obtrude","obviate","occasion","occlude","occupy","occur","off","offend","offer","officiate","offload","offset","offshore","ogle","oil","okay","omit","ooze","open","operate","opine","oppose","oppress","opt","optimise","optimize","option","orbit","orchestrate","ordain","order","organise","organize","orient","orientate","originate","ornament","orphan","oscillate","ossify","ostracise","ostracize","oust","out","outbid","outclass","outdistance","outdo","outface","outfit","outflank","outfox","outgrow","outgun","outlast","outlaw","outline","outlive","outmaneuver","outmanoeuvre","outnumber","outpace","outperform","outplay","outpoint","output","outrage","outrank","outrun","outsell","outshine","outsmart","outsource","outstay","outstrip","outvote","outweigh","outwit","overachieve","overact","overawe","overbalance","overbook","overburden","overcharge","overcome","overcompensate","overcook","overdevelop","overdo","overdose","overdraw","overdub","overeat","overemphasize","overestimate","overexpose","overextend","overfeed","overflow","overfly","overgeneralise","overgeneralize","overgraze","overhang","overhaul","overhear","overheat","overindulge","overlap","overlay","overlie","overload","overlook","overpay","overplay","overpower","overprint","overproduce","overrate","overreach","overreact","override","overrule","overrun","oversee","oversell","overshadow","overshoot","oversimplify","oversleep","overspend","overstate","overstay","overstep","overstock","overstretch","overtake","overtax","overthrow","overtrain","overturn","overuse","overvalue","overwhelm","overwinter","overwork","overwrite","ovulate","owe","own","oxidise","oxidize","oxygenate","pace","pacify","pack","package","packetise","packetize","pad","paddle","padlock","page","paginate","pailful","pain","paint","pair","pal","palatalise","palatalize","pale","pall","palliate","palm","palpate","palpitate","pamper","pan","pander","panel","panhandle","panic","pant","paper","parachute","parade","parallel","paralyse","paralyze","paraphrase","parboil","parcel","parch","pardon","pare","park","parlay","parley","parody","parole","parrot","parry","parse","part","partake","participate","particularise","particularize","partition","partner","party","pass","passivise","passivize","paste","pasteurise","pasteurize","pasture","pat","patch","patent","patrol","patronise","patronize","patter","pattern","pause","pave","paw","pawn","pay","peak","peal","peck","pedal","peddle","pedestrianise","pedestrianize","pee","peek","peel","peep","peer","peg","pelt","pen","penalise","penalize","pencil","penetrate","pension","people","pep","pepper","perambulate","perceive","perch","percolate","perfect","perforate","perform","perfume","perish","perjure","perk","perm","permeate","permit","perpetrate","perpetuate","perplex","persecute","persevere","persist","personalise","personalize","personify","perspire","persuade","pertain","perturb","peruse","pervade","pervert","pester","pet","peter","petition","petrify","phase","philosophise","philosophize","phone","photocopy","photograph","photoshop","photosynthesise","photosynthesize","phrase","pick","picket","pickle","picnic","picture","picturise","picturize","piddle","piece","pierce","pig","pigeonhole","piggyback","pike","pile","pilfer","pill","pillage","pillory","pillow","pilot","pimp","pin","pinch","pine","ping","pinion","pink","pinpoint","pioneer","pip","pipe","pique","pirate","pirouette","piss","pit","pitch","pity","pivot","pixelate","pixellate","placate","place","plagiarise","plagiarize","plague","plait","plan","plane","plant","plaster","plasticise","plasticize","plate","plateau","play","plead","please","pledge","plight","plod","plonk","plop","plot","plough","pluck","plug","plumb","plummet","plump","plunder","plunge","plunk","pluralise","pluralize","ply","poach","pocket","point","poise","poison","poke","polarise","polarize","pole","poleax","poleaxe","police","polish","politicise","politicize","poll","pollard","pollinate","pollute","polymerise","polymerize","ponce","ponder","pong","pontificate","pony","poo","pooh","pool","poop","pootle","pop","popularise","popularize","populate","pore","port","portend","portion","portray","pose","posit","position","possess","posset","post","postmark","postpone","postulate","posture","pot","potter","pounce","pound","pour","pout","powder","power","practice","practise","praise","praises","prance","prang","prate","prattle","pray","preach","precede","precipitate","precis","preclude","predate","predecease","predetermine","predicate","predict","predispose","predominate","preen","preface","prefer","prefigure","prefix","preheat","prejudge","prejudice","preload","premaster","premiere","preoccupy","prep","prepare","prepone","preregister","presage","prescind","prescribe","preselect","presell","present","preserve","preset","preside","press","pressure","pressurise","pressurize","presume","presuppose","pretend","pretest","prettify","prevail","prevaricate","prevent","preview","prey","price","prick","prickle","pride","prime","primp","print","prioritise","prioritize","prise","privatise","privatize","privilege","prize","probate","probe","proceed","process","proclaim","procrastinate","procreate","proctor","procure","prod","produce","profane","profess","professionalise","professionalize","proffer","profile","profit","program","programme","progress","prohibit","project","proliferate","prolong","promenade","promise","promote","prompt","promulgate","pronounce","proof","proofread","prop","propagandise","propagandize","propagate","propel","prophesy","propitiate","propose","proposition","propound","proscribe","prosecute","proselytise","proselytize","prospect","prosper","prostitute","prostrate","protect","protest","protrude","prove","provide","provision","provoke","prowl","prune","pry","psych","psychoanalyse","publicise","publicize","publish","pucker","puff","puke","pull","pullulate","pulp","pulsate","pulse","pulverise","pulverize","pummel","pump","pun","punch","punctuate","puncture","punish","punt","pupate","purchase","purge","purify","purl","purloin","purport","purr","purse","pursue","purvey","push","pussyfoot","put","putrefy","putt","putter","puzzle","quack","quadruple","quaff","quail","quake","qualify","quantify","quarantine","quarrel","quarry","quarter","quarterback","quash","quaver","queer","quell","quench","query","quest","question","queue","quibble","quicken","quiet","quieten","quintuple","quip","quirk","quit","quiver","quiz","quote","quoth","rabbit","race","rack","radiate","radicalise","radicalize","radio","raffle","rag","rage","raid","rail","railroad","rain","raise","rake","rally","ram","ramble","ramp","rampage","randomise","randomize","range","rank","rankle","ransack","ransom","rant","rap","rape","rappel","rasp","rasterise","rasterize","rat","ratchet","rate","ratify","ration","rationalise","rationalize","rattle","ravage","rave","ravel","ravish","raze","razz","reach","reacquaint","react","reactivate","read","readdress","readies","readjust","readmit","ready","reaffirm","realign","realise","realize","reallocate","ream","reanimate","reap","reappear","reapply","reappoint","reappraise","rear","rearm","rearrange","reason","reassemble","reassert","reassess","reassign","reassure","reawaken","rebel","reboot","reborn","rebound","rebrand","rebuff","rebuild","rebuke","rebut","recall","recant","recap","recapitulate","recapture","recast","recede","receive","recess","recharge","reciprocate","recite","reckon","reclaim","reclassify","recline","recognise","recognize","recoil","recollect","recommence","recommend","recompense","reconcile","recondition","reconfigure","reconfirm","reconnect","reconnoitre","reconquer","reconsider","reconstitute","reconstruct","reconvene","record","recount","recoup","recover","recreate","recrudesce","recruit","rectify","recuperate","recur","recycle","redact","redden","redecorate","redeem","redefine","redeploy","redesign","redevelop","redial","redirect","rediscover","redistribute","redistrict","redo","redouble","redound","redraft","redraw","redress","reduce","reduplicate","reef","reek","reel","ref","refer","referee","reference","refill","refinance","refine","refit","reflate","reflect","refloat","refocus","reform","reformat","reformulate","refract","refrain","refresh","refrigerate","refuel","refund","refurbish","refuse","refute","regain","regale","regard","regenerate","register","regress","regret","regroup","regularise","regularize","regulate","regurgitate","rehabilitate","rehash","rehear","rehearse","reheat","rehome","rehouse","reign","reignite","reimburse","rein","reincarnate","reinforce","reinstate","reinterpret","reintroduce","reinvent","reinvest","reinvigorate","reissue","reiterate","reject","rejig","rejigger","rejoice","rejoin","rejuvenate","rekindle","relapse","relate","relaunch","relax","relay","release","relegate","relent","relieve","relinquish","relish","relive","reload","relocate","rely","remain","remainder","remake","remand","remap","remark","remarry","remaster","remediate","remedy","remember","remind","reminisce","remit","remix","remodel","remonstrate","remortgage","remould","remount","remove","remunerate","rename","rend","render","rendezvous","renege","renew","renounce","renovate","rent","reoccur","reoffend","reopen","reorder","reorganise","reorganize","reorient","repackage","repair","repatriate","repay","repeal","repeat","repel","repent","rephrase","replace","replay","replenish","replicate","reply","report","repose","repossess","represent","repress","reprieve","reprimand","reprint","reproach","reprocess","reproduce","reprove","repudiate","repulse","repurpose","request","require","requisition","requite","rerun","reschedule","rescind","rescue","research","researches","resect","resell","resemble","resent","reserve","reset","resettle","reshape","reshuffle","reside","resign","resist","resit","resize","reskill","resolve","resonate","resort","resound","resource","respect","respire","respond","respray","rest","restart","restate","restock","restore","restrain","restrict","restring","restructure","result","resume","resupply","resurface","resurrect","resuscitate","retail","retain","retake","retaliate","retard","retch","retell","retest","rethink","retire","retool","retort","retouch","retrace","retract","retrain","retreat","retrench","retrieve","retrofit","retry","return","reunify","reunite","reuse","rev","revalue","revamp","reveal","revel","revenge","reverberate","revere","reverse","revert","review","revile","revise","revisit","revitalise","revitalize","revive","revivify","revoke","revolt","revolutionise","revolutionize","revolve","reward","rewind","rewire","reword","rework","rewrite","rhapsodise","rhapsodize","rhyme","rib","rick","ricochet","rid","riddle","ride","ridge","ridicule","riffle","rifle","rig","right","rightsize","rile","rim","ring","rinse","riot","rip","ripen","riposte","ripple","rise","risk","ritualise","ritualize","rival","rivet","roam","roar","roast","rob","robe","rock","rocket","roger","roll","romance","romanticise","romanticize","romp","roof","room","roost","root","rope","rosin","roster","rot","rotate","rouge","rough","roughen","roughhouse","round","rouse","roust","rout","route","rove","row","rub","rubberneck","rubbish","ruck","rue","ruffle","ruin","ruins","rule","rumble","ruminate","rummage","rumor","rumour","rumple","run","rupture","rush","rust","rustle","sabotage","sack","sacrifice","sadden","saddle","safeguard","sag","sail","salaam","salivate","sally","salt","salute","salvage","salve","sample","sanctify","sanction","sand","sandbag","sandblast","sandpaper","sandwich","sanitise","sanitize","sap","sashay","sass","sate","satiate","satirise","satirize","satisfy","saturate","saunter","savage","save","savor","savour","saw","say","scald","scale","scallop","scalp","scamper","scan","scandalise","scandalize","scapegoat","scar","scare","scarf","scarify","scarper","scatter","scattering","scavenge","scent","schedule","schematise","schematize","scheme","schlep","schlepp","schmooze","school","schtup","schuss","scoff","scold","scoop","scoot","scope","scorch","score","scorn","scotch","scour","scourge","scout","scowl","scrabble","scram","scramble","scrap","scrape","scratch","scrawl","scream","screech","screen","screw","scribble","scrimp","script","scroll","scrounge","scrub","scrummage","scrunch","scruple","scrutinise","scrutinize","scud","scuff","scuffle","scull","sculpt","scupper","scurry","scuttle","scythe","seal","sealift","sear","search","season","seat","secede","seclude","second","secrete","section","secularise","secularize","secure","sedate","seduce","see","seed","seek","seep","seethe","segment","segregate","segue","seize","select","sell","sellotape","semaphore","send","sensationalise","sensationalize","sense","sensitise","sensitize","sentence","sentimentalise","sentimentalize","separate","sequence","sequester","sequestrate","serenade","serialise","serialize","sermonise","sermonize","serve","service","set","settle","sever","sew","sex","sexualise","sexualize","shack","shackle","shade","shadow","shaft","shag","shake","shalt","sham","shamble","shame","shampoo","shanghai","shape","share","sharpen","shatter","shave","shear","sheathe","shed","sheer","shell","shellac","shelter","shelve","shepherd","shield","shift","shimmer","shimmy","shin","shine","shinny","ship","shipwreck","shirk","shit","shiver","shock","shoe","shoehorn","shoo","shoot","shop","shoplift","shore","short","shorten","shortlist","shoulder","shout","shove","shovel","show","showboat","showcase","shower","shred","shriek","shrill","shrink","shrivel","shroom","shroud","shrug","shtup","shuck","shudder","shuffle","shun","shunt","shush","shut","shuttle","shy","sic","sick","sicken","side","sideline","sidestep","sideswipe","sidetrack","sidle","sieve","sift","sigh","sight","sightsee","sign","signal","signify","signpost","silence","silhouette","silt","silver","simmer","simper","simplify","simulate","simulcast","sin","sing","singe","single","sink","sip","siphon","sire","sit","site","situate","size","sizzle","skate","skateboard","skedaddle","sketch","skew","skewer","ski","skid","skim","skimp","skin","skip","skipper","skirmish","skirt","skitter","skive","skivvy","skulk","sky","skyjack","skyrocket","slack","slacken","slag","slake","slam","slander","slant","slap","slash","slate","slather","slaughter","slave","slaver","slay","sledge","sleek","sleep","sleepwalk","sleet","slew","slice","slick","slide","slight","slim","sling","slink","slip","slit","slither","slob","slobber","slog","slop","slope","slosh","slot","slouch","slough","slow","slug","sluice","slum","slumber","slump","slur","slurp","smack","smart","smarten","smash","smear","smell","smelt","smile","smirk","smite","smoke","smooch","smoodge","smooth","smother","smoulder","smudge","smuggle","snack","snaffle","snag","snaggle","snake","snap","snare","snarf","snarl","snatch","sneak","sneer","sneeze","snicker","sniff","sniffle","snigger","snip","snipe","snitch","snivel","snog","snooker","snoop","snooper","snooze","snore","snorkel","snort","snow","snowball","snowplough","snowplow","snub","snuff","snuffle","snuffling","snuggle","soak","soap","soar","sob","sober","socialise","socialize","sock","sod","sodomise","sodomize","soften","soil","sojourn","solace","solder","soldier","sole","solemnise","solemnize","solicit","solidify","soliloquize","solve","somersault","soothe","sorrow","sort","sough","sound","soundproof","soup","sour","source","souse","sow","space","span","spangle","spank","spar","spare","spark","sparkle","spatter","spattering","spawn","spay","speak","spear","spearhead","spec","specialise","specialize","specify","spectacles","spectate","speculate","speed","spell","spellcheck","spend","spew","spice","spiff","spike","spill","spin","spiral","spirit","spit","spite","splash","splatter","splay","splice","splinter","split","splosh","splurge","splutter","spoil","sponge","sponsor","spoof","spook","spool","spoon","sport","sports","spot","spotlight","spout","sprain","sprawl","spray","spread","spreadeagle","spring","springboard","sprinkle","sprint","spritz","sprout","spruce","spur","spurn","spurt","sputter","spy","squabble","squall","squander","square","squash","squat","squawk","squeak","squeal","squeeze","squelch","squint","squirm","squirrel","squirt","squish","stab","stabilise","stabilize","stable","stables","stack","staff","stage","stagger","stagnate","stain","stake","stalk","stall","stammer","stamp","stampede","stanch","stand","standardise","standardize","staple","star","starch","stare","start","startle","starve","stash","state","statement","station","staunch","stave","stay","steady","steal","steam","steamroller","steel","steep","steepen","steer","stem","stencil","step","stereotype","sterilise","sterilize","stew","stick","stickybeak","stiff","stiffen","stifle","stigmatise","stigmatize","still","stimulate","sting","stinger","stink","stint","stipple","stipulate","stir","stitch","stock","stockpile","stoke","stomach","stomp","stone","stonewall","stoop","stop","stopper","store","storm","storyboard","stow","straddle","strafe","straggle","straighten","strain","strand","strangle","strap","stratify","stravage","stravaig","stray","streak","stream","streamline","strengthen","stress","stretch","stretcher","strew","stride","strike","string","strip","strive","stroke","stroll","structure","struggle","strum","strut","stub","stud","study","stuff","stultify","stumble","stump","stun","stunt","stupefy","stutter","style","stymie","sub","subcontract","subdivide","subdue","subedit","subject","subjugate","sublet","sublimate","submerge","submit","subordinate","suborn","subpoena","subscribe","subside","subsidise","subsidize","subsist","substantiate","substitute","subsume","subtend","subtitle","subtract","subvert","succeed","succor","succour","succumb","suck","sucker","suckle","suction","sue","suffer","suffice","suffocate","suffuse","sugar","suggest","suit","sulk","sulks","sully","sum","summarise","summarize","summon","summons","sun","sunbathe","sunder","sunset","sup","superimpose","superintend","superpose","supersede","supersize","supersized","supervene","supervise","supplant","supplement","supply","support","suppose","suppress","suppurate","surcharge","surf","surface","surge","surmise","surmount","surpass","surprise","surrender","surround","survey","survive","suspect","suspend","suspenders","suss","sustain","suture","swab","swaddle","swagger","swallow","swamp","swan","swank","swap","swarm","swat","swath","swathe","sway","swear","sweat","sweep","sweeps","sweeten","swell","swelter","swerve","swig","swill","swim","swindle","swing","swipe","swirl","swish","switch","swivel","swoon","swoop","swoosh","swot","symbolise","symbolize","sympathise","sympathize","symptomize","synchronise","synchronize","syndicate","synthesise","synthesize","syringe","systematise","systematize","tab","table","tabulate","tack","tackle","tag","tail","tailgate","tailor","taint","take","talk","tally","tame","tamp","tamper","tan","tangle","tango","tank","tankful","tantalise","tantalize","tap","tape","taper","tar","target","tarmac","tarnish","tarry","tart","task","taste","tattle","tattoo","taunt","tauten","tax","taxi","taxicab","teach","team","tear","tease","tee","teem","teeter","teethe","telecast","telecommute","teleconference","telegraph","telemeter","teleoperate","telephone","teleport","telescope","televise","telex","tell","telnet","temp","temper","temporise","temporize","tempt","tenant","tend","tender","tenderise","tenderize","tense","tension","tergiversate","term","terminate","terraform","terrify","terrorise","terrorize","test","testify","tether","text","thank","thatch","thaw","theorise","theorize","thicken","thin","think","thirst","thrash","thread","threaten","thresh","thrill","thrive","throb","throbbing","throng","throttle","throw","thrust","thud","thumb","thump","thunder","thwack","thwart","tick","ticket","tickle","tide","tidy","tie","tighten","tile","till","tilt","time","timetable","tinge","tingle","tingling","tinker","tinkle","tinkling","tint","tip","tippex","tipple","tiptoe","tire","titillate","titivate","title","titrate","titter","toady","toast","toboggan","toddle","toe","tog","toggle","toil","toke","tolerate","toll","tone","tongue","tonify","tool","toot","tootle","top","topple","torch","torment","torpedo","torture","toss","tot","total","tote","totter","touch","tough","toughen","tour","tousle","tout","tow","towel","tower","toy","trace","track","trade","traduce","traffic","trail","train","traipse","trammel","tramp","trample","trampoline","tranquilize","tranquillize","transact","transcend","transcribe","transfer","transfigure","transfix","transform","transfuse","transgress","transit","translate","transliterate","transmit","transmogrify","transmute","transpire","transplant","transport","transpose","trap","trash","traumatise","traumatize","travel","traverse","trawl","tread","treasure","treat","treble","trek","tremble","trembling","trepan","trespass","trial","trick","trickle","trifle","trigger","trill","trim","trip","triple","triumph","trivialise","trivialize","troll","tromp","troop","trot","trouble","troubleshoot","trounce","trouser","truant","truck","trudge","trump","trumpet","truncate","trundle","truss","trust","try","tuck","tug","tugboat","tumble","tune","tunnel","turbocharge","turf","turn","tussle","tut","tutor","twang","tweak","tweet","twiddle","twig","twin","twine","twinkle","twirl","twist","twitch","twitter","twittering","type","typecast","typeset","typify","tyrannise","tyrannize","ulcerate","ululate","ump","umpire","unbalance","unban","unbend","unblock","unbuckle","unburden","unbutton","uncoil","uncork","uncouple","uncover","uncurl","undelete","underachieve","underbid","undercharge","undercook","undercut","underestimate","underestimation","underexpose","undergo","underlie","underline","undermine","underpay","underperform","underpin","underplay","underrate","underscore","undersell","undershoot","underspend","understand","understate","understudy","undertake","undervalue","underwrite","undo","undock","undress","undulate","unearth","unfasten","unfold","unfreeze","unfurl","unhand","unhinge","unhitch","unhook","unify","uninstall","unionise","unionize","unite","unlace","unlearn","unleash","unload","unlock","unloose","unloosen","unmask","unnerve","unpack","unpick","unplug","unravel","unroll","unsaddle","unscramble","unscrew","unseat","unsettle","unsubscribe","untangle","untie","unveil","unwind","unwrap","unzip","up","upbraid","upchange","upchuck","update","upend","upgrade","uphold","upholster","uplift","upload","uproot","upsell","upset","upshift","upskill","upstage","urge","urinate","use","usher","usurp","utilise","utilize","utter","vacate","vacation","vaccinate","vacillate","vacuum","valet","validate","value","vamoose","vandalise","vandalize","vanish","vanquish","vaporise","vaporize","varnish","vary","vault","veer","veg","vegetate","veil","vend","veneer","venerate","vent","ventilate","venture","verbalise","verbalize","verge","verify","versify","vest","vet","veto","vex","vibrate","victimise","victimize","vide","video","videotape","vie","view","viewing","vilify","vindicate","violate","visit","visualise","visualize","vitiate","vitrify","vocalize","voice","void","volley","volumise","volumize","volunteer","vomit","vote","vouch","vouchsafe","vow","voyage","vulgarise","vulgarize","wad","waddle","wade","waffle","waft","wag","wage","wager","waggle","wail","wait","waive","wake","wakeboard","waken","walk","wall","wallop","wallow","wallpaper","waltz","wander","wane","wangle","wank","want","warble","ward","warm","warn","warp","warrant","wash","wassail","waste","watch","water","waterproof","waterski","wave","waver","wax","waylay","weaken","wean","weaponise","weaponize","wear","weary","weasel","weather","weatherise","weatherize","weave","wed","wedge","wee","weed","weekend","weep","weigh","weight","weird","welch","welcome","weld","well","welly","welsh","wend","westernise","westernize","wet","whack","wheedle","wheel","wheeze","whelp","whet","whiff","while","whilst","whimper","whine","whinge","whinny","whip","whirl","whirr","whirring","whisk","whisper","whispering","whistle","whiten","whitewash","whittle","whiz","whizz","whoop","whoosh","whup","wick","widen","widow","wield","wig","wiggle","wildcat","will","wilt","wimp","win","wince","winch","wind","winds","windsurf","wine","wing","wink","winkle","winnow","winter","wipe","wire","wiretap","wise","wisecrack","wish","withdraw","wither","withhold","withstand","witness","witter","wobble","wolf","wonder","woo","woof","word","work","worm","worry","worsen","worship","worst","wound","wow","wowee","wrangle","wrap","wreak","wreathe","wreck","wrench","wrest","wrestle","wriggle","wring","wrinkle","writ","write","writhe","wrong","wrought","xerox","yack","yak","yank","yap","yaw","yawn","yearn","yell","yellow","yelp","yield","yodel","yoke","yomp","yowl","yuppify","zap","zero","zigzag","zing","zip","zone","zoom"];var Cd=Object.freeze({adjective:kn,adverb:vn,conjunction:wn,interjection:Sn,noun:_n,preposition:An,verb:En}),xn=Cd;var Td=Object.freeze({title:"English",syntax:cn,time:ln,internet:mn,person:bn,word:xn}),fe=Td;var St=["male","female"],xe=Symbol("randomValue"),sr=Symbol("typesValue"),it=Symbol("localeValue"),Is=class{[sr];[xe];[it];constructor(e={}){this[sr]=new tt(e.seed),this[xe]=new Yt(e.seed),this[it]=e.locale||fe}seed(e){this[xe].seed(e),this[sr].seed(e)}locale(e){this[it]=e||fe}firstName(e){let{person:t}=this[it],i=e&&St.includes(e)?e:this[xe].pickOne(St),r;t&&t.firstName&&t.firstName[i]?r=t.firstName:r=fe.person.firstName;let s=r[i];return this[xe].pickOne(s)}lastName(e){let{person:t}=this[it];if(!e){let a=t&&t.lastName||fe.person.lastName;if(Array.isArray(a.general)&&a.general.length)return this[xe].pickOne(a.general);throw new Error("The locale does not have a general last name pool.")}let i=e&&St.includes(e)?e:this[xe].pickOne(St),r;t&&t.lastName&&t.lastName[i]?r=t.lastName:r=fe.person.lastName;let s=r[i];return this[xe].pickOne(s)}middleName(e){let{person:t}=this[it],i=t&&t.middleName||t&&t.firstName||fe.person.firstName,r=e&&St.includes(e)?e:this[xe].pickOne(St),s=i[r];return this[xe].pickOne(s)}name(e={}){let{firstName:t,lastName:i,gender:r}=e,s=[];return this[sr].boolean({likelihood:10})&&s.push(this.prefix(r)),s.push(t||this.firstName(r)),s.push(i||this.lastName(r)),this[sr].boolean({likelihood:10})&&s.push(this.suffix(r)),s.join(" ")}gender(e){let{person:t}=this[it],i=t&&t.gender||fe.person.gender;return e?this[xe].pickOne(i.binary||fe.person.gender.binary):this[xe].pickOne(i.pool||fe.person.gender.pool)}prefix(e){let{person:t}=this[it],i=t&&t.prefix||fe.person.prefix;if(!e&&Array.isArray(i.general)&&i.general.length)return this[xe].pickOne(i.general);let r=e&&St.includes(e)?e:this[xe].pickOne(St),s=i[r]||fe.person.prefix[r];return this[xe].pickOne(s)}suffix(e){let{person:t}=this[it],i=t&&t.suffix||fe.person.suffix;if(Array.isArray(i.general)&&i.general.length)return this[xe].pickOne(i.general);let r=e&&St.includes(e)?e:this[xe].pickOne(St),s=i[r]||fe.person.suffix[r];return this[xe].pickOne(s)}jobTitle(){let e=this.jobDescriptor(),t=this.jobArea(),i=this.jobType();return`${e} ${t} ${i}`}jobDescriptor(){let{person:e}=this[it],t;return e&&e.title&&e.title.descriptor?t=e.title:t=fe.person.title,this[xe].pickOne(t.descriptor)}jobArea(){let{person:e}=this[it],t;return e&&e.title&&e.title.level?t=e.title:t=fe.person.title,this[xe].pickOne(t.level)}jobType(){let{person:e}=this[it],t;return e&&e.title&&e.title.job?t=e.title:t=fe.person.title,this[xe].pickOne(t.job||[])}};var js=Symbol("randomValue"),rt=Symbol("typesValue"),Rs=Symbol("localeValue"),Cs=class{[rt];[js];[Rs];constructor(e={}){this[rt]=new tt(e.seed),this[js]=new Yt(e.seed),this[Rs]=e.locale||fe}seed(e){this[js].seed(e),this[rt].seed(e)}locale(e){this[Rs]=e||fe}word(e={}){let t={...e};if(typeof t.syllables=="number"&&typeof t.length=="number")throw new RangeError('Cannot specify both "syllables" and "length".');let i="";if(typeof t.length=="number"){do i+=this.syllable();while(i.length<t.length);i=i.substring(0,t.length)}else{let r=t.syllables||this[rt].number({min:1,max:3});for(let s=0;s<r;s++)i+=this.syllable()}return t.capitalize&&(i=this.capitalize(i)),i}capitalize(e){return e.charAt(0).toUpperCase()+e.substr(1)}words(e=3){return new Array(e).fill("").map(()=>this.word()).join(" ")}sentence(e={}){let t={...e},{words:i=this[rt].number({min:12,max:18})}=t,r=new Array(i).fill("").map(()=>this.word()).join(" ");r=this.capitalize(r);let{punctuation:s}=t;return s!==!1&&!/^[.?;!:]$/.test(String(s))&&(s="."),s&&(r+=s),r}sentences(e={}){let t={};typeof e=="number"?t.size=e:t={...e};let{size:i=this[rt].number({min:2,max:6})}=t;return new Array(i).fill("").map(()=>this.sentence()).join(" ")}slug(e){let t=this.words(e);return en(t)}paragraph(e={}){let t={};typeof e=="number"?t.sentences=e:t={...e};let{lineBreak:i,sentences:r=this[rt].number({min:3,max:7})}=t;return new Array(r).fill("").map(()=>this.sentence()).join(i===!0?`\r
33
+ `)}function Qo(n,e){if(typeof n=="number")return n;let t=Number(n);return Number.isNaN(t)?e:t}function ea(n,e){let t=typeof n;if(t==="boolean")return n;if(t==="string"){let i=n.trim();if(i==="true")return!0;if(i==="false")return!1}return e}function xs(n,e){switch(e){case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:return Qo(n,0);case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return ea(n,!1);case d.w3.xmlSchema.string:case d.aml.vocabularies.shapes.password:return n??"";case d.aml.vocabularies.shapes.nil:case d.w3.xmlSchema.nil:return null;default:return n}}function ta(n,e=[]){let t;return Array.isArray(e)&&e.length&&(t=n.find(i=>e.includes(i.id))),t||([t]=n),t}function Os(n,e){let t=[],{properties:i,inherits:r}=n;i.length&&(t=[...i]),Array.isArray(r)&&r.length&&r.forEach(o=>{let a=o;if(a.types.includes(d.aml.vocabularies.shapes.UnionShape)){let p=a,{anyOf:u=[]}=p;a=ta(u,e)}if(!a.types.includes(d.w3.shacl.NodeShape))return;let c=Os(a);c.length&&(t=t.concat(c))});let s=[];return t.forEach(o=>{s.find(l=>l.name===o.name)||s.push(o)}),s}var Xt=class{processNode(e){let{types:t}=e;if(t.includes(d.aml.vocabularies.data.Scalar))return this.processScalarNode(e);if(t.includes(d.aml.vocabularies.data.Array))return this.processArrayNode(e);if(t.includes(d.aml.vocabularies.data.Object))return this.processObjectNode(e)}processScalarNode(e){return xs(e.value,e.dataType)}processArrayNode(e){let t=[];return e.members.forEach(i=>{let r=this.processNode(i);r!==void 0&&t.push(r)}),t}processObjectNode(e){let t={},{properties:i}=e;return Object.keys(i).forEach(r=>{let s=i[r],o=this.processNode(s);if(typeof o<"u"){let a=this.normalizePropertyName(r);t[a]=o}}),t}normalizePropertyName(e){let t=e;try{t=decodeURIComponent(t)}catch{}return t}};var Ye=class extends Xt{generate(e){let t=this.processNode(e);return!t||typeof t=="string"?t:JSON.stringify(t,null,2)}};var qe=class extends Xt{generate(e,t,i={}){let r=this.processNode(e);if(!r)return r;let{indent:s=0}=i,o=new Array(s).fill(" ").join("");return t?Array.isArray(r)?r.map(a=>`${o}<${t}>${Ri(a)}</${t}>`).filter(a=>!!a).join(`
34
+ `):`${Ri({[t]:r})}`:`${Ri(r,s)}`}};var Ge={};za(Ge,{anyShape:()=>Yt,arrayShape:()=>Ed,fileShape:()=>_d,nodeShape:()=>wd,propertyShape:()=>Od,recursiveShape:()=>Pd,scalarShape:()=>Sd,shape:()=>fa,tupleShape:()=>xd,unionShape:()=>Ad,xmlSerializer:()=>on});var sr={};za(sr,{IAmfAPIContractProcessingDataTypes:()=>od,IAmfAnyTypes:()=>la,IAmfApiKeySettingsTypes:()=>Bc,IAmfArrayNodeTypes:()=>ma,IAmfArrayTypes:()=>ra,IAmfAsyncApiTypes:()=>vd,IAmfBaseUnitProcessingDataTypes:()=>kd,IAmfCallbackTypes:()=>Wc,IAmfCreativeWorkTypes:()=>rd,IAmfDataTypeFragmentTypes:()=>md,IAmfDocumentTypes:()=>id,IAmfDomainExtensionTypes:()=>ed,IAmfDomainPropertyTypes:()=>yd,IAmfEncodingTypes:()=>sd,IAmfEndpointType:()=>Cc,IAmfExampleTypes:()=>Pc,IAmfExternalDomainElementTypes:()=>bd,IAmfExternalFragmentTypes:()=>hd,IAmfFileTypes:()=>na,IAmfHttpSettingsTypes:()=>Jc,IAmfIriTemplateMappingTypes:()=>Yc,IAmfLicenseTypes:()=>jc,IAmfMessageTypes:()=>Qc,IAmfModuleTypes:()=>ud,IAmfNilTypes:()=>xc,IAmfNodeTypes:()=>sa,IAmfOAuth1SettingsTypes:()=>qc,IAmfOAuth2FlowTypes:()=>Kc,IAmfOAuth2SettingsTypes:()=>Fc,IAmfObjectNodeTypes:()=>ha,IAmfOpenIdConnectSettingsTypes:()=>Gc,IAmfParameterTypes:()=>$c,IAmfParametrizedResourceTypeTypes:()=>nd,IAmfParametrizedSecuritySchemeTypes:()=>zc,IAmfParametrizedTraitTypes:()=>ld,IAmfPayloadTypes:()=>Lc,IAmfPropertyTypes:()=>oa,IAmfProviderTypes:()=>Rc,IAmfRdfsSeqType:()=>ad,IAmfRecursiveTypes:()=>da,IAmfRequestTypes:()=>Dc,IAmfResourceTypeTypes:()=>cd,IAmfResponseTypes:()=>Mc,IAmfScalarNodeTypes:()=>ua,IAmfScalarTypes:()=>ia,IAmfSchemaTypes:()=>Oc,IAmfScopeTypes:()=>Hc,IAmfSecurityRequirementTypes:()=>Uc,IAmfSecuritySchemeFragmentTypes:()=>gd,IAmfSecuritySchemeTypes:()=>Vc,IAmfServerType:()=>Nc,IAmfSourceMapTypes:()=>td,IAmfSupportedOperationTypes:()=>Tc,IAmfTagTypes:()=>Zc,IAmfTemplatedLinkTypes:()=>Xc,IAmfTraitFragmentTypes:()=>fd,IAmfTraitTypes:()=>dd,IAmfTupleTypes:()=>ca,IAmfUnionTypes:()=>aa,IAmfVariableValueTypes:()=>pd,IAmfWebApiType:()=>Ic,IAmfXmlSerializationTypes:()=>pa});var ia=[d.aml.vocabularies.shapes.ScalarShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],ra=[d.aml.vocabularies.shapes.ArrayShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],sa=[d.w3.shacl.NodeShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],oa=[d.w3.shacl.PropertyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],xc=[d.aml.vocabularies.shapes.NilShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],aa=[d.aml.vocabularies.shapes.UnionShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],na=[d.aml.vocabularies.shapes.FileShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],la=[d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],Oc=[d.aml.vocabularies.shapes.SchemaShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],ca=[d.aml.vocabularies.shapes.TupleShape,d.aml.vocabularies.shapes.ArrayShape,d.aml.vocabularies.shapes.AnyShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],da=[d.aml.vocabularies.shapes.RecursiveShape,d.w3.shacl.Shape,d.aml.vocabularies.shapes.Shape,d.aml.vocabularies.document.DomainElement],pa=[d.aml.vocabularies.shapes.XMLSerializer,d.aml.vocabularies.document.DomainElement],ua=[d.aml.vocabularies.data.Scalar,d.aml.vocabularies.data.Node,d.aml.vocabularies.document.DomainElement],ma=[d.aml.vocabularies.data.Array,d.w3.rdfSyntax.Seq,d.aml.vocabularies.data.Node,d.aml.vocabularies.document.DomainElement],ha=[d.aml.vocabularies.data.Object,d.aml.vocabularies.data.Node,d.aml.vocabularies.document.DomainElement],Pc=[d.aml.vocabularies.apiContract.Example,d.aml.vocabularies.document.DomainElement],Ic=[d.aml.vocabularies.apiContract.WebAPI,d.aml.vocabularies.apiContract.API,d.aml.vocabularies.document.RootDomainElement,d.aml.vocabularies.document.DomainElement],Nc=[d.aml.vocabularies.apiContract.Server,d.aml.vocabularies.document.DomainElement],$c=[d.aml.vocabularies.apiContract.Parameter,d.aml.vocabularies.core.Parameter,d.aml.vocabularies.document.DomainElement],Rc=[d.aml.vocabularies.core.Organization,d.aml.vocabularies.document.DomainElement],jc=[d.aml.vocabularies.core.License,d.aml.vocabularies.document.DomainElement],Cc=[d.aml.vocabularies.apiContract.EndPoint,d.aml.vocabularies.document.DomainElement],Tc=[d.aml.vocabularies.apiContract.Operation,d.aml.vocabularies.core.Operation,d.aml.vocabularies.document.DomainElement],Dc=[d.aml.vocabularies.apiContract.Request,d.aml.vocabularies.core.Request,d.aml.vocabularies.apiContract.Message,d.aml.vocabularies.document.DomainElement],Mc=[d.aml.vocabularies.apiContract.Response,d.aml.vocabularies.core.Response,d.aml.vocabularies.apiContract.Message,d.aml.vocabularies.document.DomainElement],Lc=[d.aml.vocabularies.apiContract.Payload,d.aml.vocabularies.core.Payload,d.aml.vocabularies.document.DomainElement],Uc=[d.aml.vocabularies.security.SecurityRequirement,d.aml.vocabularies.document.DomainElement],zc=[d.aml.vocabularies.security.ParametrizedSecurityScheme,d.aml.vocabularies.document.DomainElement],Vc=[d.aml.vocabularies.security.SecurityScheme,d.aml.vocabularies.document.DomainElement],Fc=[d.aml.vocabularies.security.OAuth2Settings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Kc=[d.aml.vocabularies.security.OAuth2Flow,d.aml.vocabularies.document.DomainElement],qc=[d.aml.vocabularies.security.OAuth1Settings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Jc=[d.aml.vocabularies.security.HttpSettings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Bc=[d.aml.vocabularies.security.ApiKeySettings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Gc=[d.aml.vocabularies.security.OpenIdConnectSettings,d.aml.vocabularies.security.Settings,d.aml.vocabularies.document.DomainElement],Hc=[d.aml.vocabularies.security.Scope,d.aml.vocabularies.document.DomainElement],Wc=[d.aml.vocabularies.apiContract.Callback,d.aml.vocabularies.document.DomainElement],Xc=[d.aml.vocabularies.apiContract.TemplatedLink,d.aml.vocabularies.document.DomainElement],Yc=[d.aml.vocabularies.apiContract.IriTemplateMapping,d.aml.vocabularies.document.DomainElement],Zc=[d.aml.vocabularies.apiContract.Tag,d.aml.vocabularies.document.DomainElement],Qc=[d.aml.vocabularies.apiContract.Message,d.aml.vocabularies.document.DomainElement],ed=[d.aml.vocabularies.apiContract.DomainExtension,d.aml.vocabularies.document.DomainElement],td=[d.aml.vocabularies.docSourceMaps.SourceMap],id=[d.aml.vocabularies.document.Document,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Module,d.aml.vocabularies.document.Unit],rd=[d.aml.vocabularies.core.CreativeWork,d.aml.vocabularies.document.DomainElement],sd=[d.aml.vocabularies.apiContract.Encoding,d.aml.vocabularies.document.DomainElement],od=[d.aml.vocabularies.document.APIContractProcessingData],ad=[d.w3.rdfSchema.Seq],nd=[d.aml.vocabularies.apiContract.ParametrizedResourceType,d.aml.vocabularies.document.ParametrizedDeclaration,d.aml.vocabularies.document.DomainElement],ld=[d.aml.vocabularies.apiContract.ParametrizedTrait,d.aml.vocabularies.document.ParametrizedDeclaration,d.aml.vocabularies.document.DomainElement],cd=[d.aml.vocabularies.apiContract.ResourceType,d.aml.vocabularies.document.AbstractDeclaration,d.aml.vocabularies.document.DomainElement],dd=[d.aml.vocabularies.apiContract.Trait,d.aml.vocabularies.document.AbstractDeclaration,d.aml.vocabularies.document.DomainElement],pd=[d.aml.vocabularies.document.VariableValue,d.aml.vocabularies.document.DomainElement],ud=[d.aml.vocabularies.document.Module,d.aml.vocabularies.document.Unit],md=[d.aml.vocabularies.shapes.DataTypeFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],hd=[d.aml.vocabularies.document.ExternalFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],fd=[d.aml.vocabularies.apiContract.TraitFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],gd=[d.aml.vocabularies.security.SecuritySchemeFragment,d.aml.vocabularies.document.Fragment,d.aml.vocabularies.document.Unit],yd=[d.aml.vocabularies.document.DomainProperty,d.w3.rdfSyntax.Property,d.aml.vocabularies.document.DomainElement],bd=[d.aml.vocabularies.document.ExternalDomainElement,d.aml.vocabularies.document.DomainElement],kd=[d.aml.vocabularies.document.BaseUnitProcessingData],vd=[d.aml.vocabularies.apiContract.AsyncAPI,d.aml.vocabularies.apiContract.API,d.aml.vocabularies.document.RootDomainElement,d.aml.vocabularies.document.DomainElement];function on(n){return{id:`xml-serializer-${n}`,types:pa,customDomainProperties:[]}}function fa(n){return{id:n,types:[],values:[],inherits:[],or:[],and:[],xone:[],customDomainProperties:[]}}function Yt(n){return{...fa(n),types:la,examples:[],xmlSerialization:on(n)}}function wd(n){let e=Yt(n);return e.types=sa,e.id=`node-shape-${n}`,{...e,properties:[],dependencies:[],customShapeProperties:[],customShapePropertyDefinitions:[]}}function Sd(n){let e=Yt(n);return e.id=`scalar-shape-${n}`,e.types=ia,e}function Ad(n){let e=Yt(n);return e.id=`union-shape-${n}`,e.types=aa,{...e,anyOf:[]}}function _d(n){let e=Yt(n);return e.id=`file-shape-${n}`,e.types=na,e}function Ed(n){let e=Yt(n);return e.id=`array-shape-${n}`,e.types=ra,e}function xd(n){let e=Yt(n);return e.id=`tuple-shape-${n}`,e.types=ca,{...e,items:[]}}function Od(n){let e=Yt(n);return e.types=oa,e}function Pd(n,e){return{...fa(n),id:`recursive-${n}`,types:da,fixPoint:e||""}}import{customAlphabet as Id}from"nanoid";var an=Id("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var vt=class n{id=an();types;name;properties;value;dataType;members;customDomainProperties=[];static scalar(e,t){let i=new n("scalar");return i.value=e,i.dataType=t,i}constructor(e){if(typeof e=="string"){if(e==="scalar")this.types=ua;else if(e==="array")this.types=ma;else if(e==="object")this.types=ha;else throw new Error(`Invalid data node init option: ${e}`);return}if(!e)throw new Error("Expected an initialization option.");let t=e,{id:i,types:r,customDomainProperties:s}=t;if(this.id=i,this.types=r,this.customDomainProperties=s,r.includes(d.aml.vocabularies.data.Scalar)){let o=t;this.value=o.value,this.dataType=o.dataType}else if(r.includes(d.aml.vocabularies.data.Object)){let o=t,a={};this.properties=a,Object.keys(o.properties).forEach(l=>{let c=new n(o.properties[l]);a[l]=c})}else if(r.includes(d.aml.vocabularies.data.Array)){let o=t,a=[];this.members=a,Array.isArray(o.members)&&o.members.forEach(l=>{let c=new n(l);a.push(c)})}}toJSON(){let{id:e,customDomainProperties:t,types:i,name:r}=this,s={id:e,types:i,customDomainProperties:t};if(r&&(s.name=r),i.includes(d.aml.vocabularies.data.Scalar)){let o=s;o.dataType=this.dataType,o.value=this.value}else if(i.includes(d.aml.vocabularies.data.Object)){let o=s;o.properties={};let a=this.properties;a&&Object.keys(a).forEach(l=>{o.properties[l]=a[l].toJSON()})}else if(i.includes(d.aml.vocabularies.data.Array)){let o=s;o.members=[],this.members&&this.members.forEach(a=>{o.members.push(a.toJSON())})}return s}addMember(e){if(!this.types.includes(d.aml.vocabularies.data.Array))throw new Error("Not an ArrayNode.");this.members||(this.members=[]),this.members.push(e)}removeMember(e){if(!this.types.includes(d.aml.vocabularies.data.Array))throw new Error("Not an ArrayNode.");if(!this.members)return;let t=this.members.findIndex(i=>i.id===e);t>=0&&this.members.splice(t,1)}addProperty(e,t){if(!this.types.includes(d.aml.vocabularies.data.Object))throw new Error("Not an ObjectNode.");this.properties||(this.properties={}),this.properties[e]=t}removeProperty(e){if(!this.types.includes(d.aml.vocabularies.data.Object))throw new Error("Not an ObjectNode.");this.properties&&delete this.properties[e]}};var Ce=Symbol("nValue"),or=Symbol("mValue"),nn=Symbol("matrixAValue"),Ps=Symbol("upperMaskValue"),Is=Symbol("lowerMaskValue"),se=Symbol("mtValue"),Ze=Symbol("mtiValue"),Ns=Symbol("instancesValue"),Zt=class n{static[Ns]=new Map;[Ce]=624;[or]=397;[nn]=2567483615;[Ps]=2147483648;[Is]=2147483647;[se]=new Array(this[Ce]);[Ze]=this[Ce]+1;constructor(e=n.seedFn()){this.initGenRand(e)}static seedFn(){return Math.floor(Math.random()*10**13)}static fromSeed(e=n.seedFn()){if(this[Ns].has(e))return this[Ns].get(e);let t=new n(e);return this[Ns].set(e,t),t}initGenRand(e){let t=e;for(this[se][0]=t>>>0,this[Ze]=1;this[Ze]<this[Ce];this[Ze]++)t=this[se][this[Ze]-1]^this[se][this[Ze]-1]>>>30,this[se][this[Ze]]=(((t&4294901760)>>>16)*1812433253<<16)+(t&65535)*1812433253+this[Ze],this[se][this[Ze]]>>>=0}initByArray(e,t){let i=1,r=0,s;this.initGenRand(19650218);let o=this[Ce]>t?this[Ce]:t;for(;o;o--)s=this[se][i-1]^this[se][i-1]>>>30,this[se][i]=(this[se][i]^(((s&4294901760)>>>16)*1664525<<16)+(s&65535)*1664525)+e[r]+r,this[se][i]>>>=0,i++,r++,i>=this[Ce]&&(this[se][0]=this[se][this[Ce]-1],i=1),r>=t&&(r=0);for(o=this[Ce]-1;o;o--)s=this[se][i-1]^this[se][i-1]>>>30,this[se][i]=(this[se][i]^(((s&4294901760)>>>16)*1566083941<<16)+(s&65535)*1566083941)-i,this[se][i]>>>=0,i++,i>=this[Ce]&&(this[se][0]=this[se][this[Ce]-1],i=1);this[se][0]=2147483648}int32(){let e,t=[0,this[nn]];if(this[Ze]>=this[Ce]){let i;for(this[Ze]===this[Ce]+1&&this.initGenRand(5489),i=0;i<this[Ce]-this[or];i++)e=this[se][i]&this[Ps]|this[se][i+1]&this[Is],this[se][i]=this[se][i+this[or]]^e>>>1^t[e&1];for(;i<this[Ce]-1;i++)e=this[se][i]&this[Ps]|this[se][i+1]&this[Is],this[se][i]=this[se][i+(this[or]-this[Ce])]^e>>>1^t[e&1];e=this[se][this[Ce]-1]&this[Ps]|this[se][0]&this[Is],this[se][this[Ce]-1]=this[se][this[or]-1]^e>>>1^t[e&1],this[Ze]=0}return e=this[se][this[Ze]++],e^=e>>>11,e^=e<<7&2636928640,e^=e<<15&4022730752,e^=e>>>18,e>>>0}int31(){return this.int32()>>>1}real1(){return this.int32()*(1/4294967295)}random(e=32768,t=0){return Math.floor(this.real2()*(e-t)+t)}real2(){return this.int32()*(1/4294967296)}real3(){return(this.int32()+.5)*(1/4294967296)}res53(){let e=this.int32()>>>5,t=this.int32()>>>6;return(e*67108864+t)*(1/9007199254740992)}};var $s="0123456789",ar="abcdefghijklmnopqrstuvwxyz",Rs=ar.toUpperCase(),ga=`${$s}abcdef`;function ln(n=""){return n.replace(/ /g,"-").replace(/[^一-龠ぁ-ゔァ-ヴー\w.-]+/g,"")}function wt(n,e={}){let t={};typeof e=="number"?t.max=e:typeof e=="object"&&(t={...e}),typeof t.min!="number"&&(t.min=0),typeof t.max!="number"&&(t.max=99999),typeof t.precision!="number"&&(t.precision=1),t.max>0&&(t.max+=t.precision);let i=Math.floor(n.random(t.max/t.precision,t.min/t.precision));return t.precision===1||(i/=1/t.precision),i}function js(n,e={}){let t={};return typeof e=="number"?t.precision=e:typeof e=="object"&&(t={...e}),typeof t.precision!="number"&&(t.precision=.01),wt(n,t)}function cn(n,e=10,t){let i=typeof t=="string"?t:Rs+ar,r={min:0,max:i.length-1};return new Array(e).fill("").map(()=>i[wt(n,r)]).join("")}function dn(n,e={}){let t={...e},i;switch(t.casing){case"lower":i=ar;break;case"upper":i=Rs;break;default:i=ar+Rs}if(!t.pool){t.pool="";let r="!@#$%^&*()[]";t.alpha&&(t.pool+=i),t.numeric&&(t.pool+=$s),t.symbols&&(t.pool+=r),t.pool||(t.pool=`${i}${$s}${r}`)}return t.pool.charAt(wt(n,t.pool.length-1))}function pn(n,e={}){let t={};typeof e=="number"?t.max=e:typeof e=="object"&&(t={...e});let i=864e13;(typeof t.min!="number"||t.min<i*-1)&&(t.min=new Date().setFullYear(1970,1,1)),(typeof t.max!="number"||t.max>i)&&(t.max=new Date().setFullYear(2100,1,1));let r=wt(n,t);return new Date(r)}var ji=Symbol("mtValue"),Qt=class{[ji];constructor(e){this[ji]=Zt.fromSeed(e)}seed(e){this[ji]=Zt.fromSeed(e)}pick(e,t){let i=t;typeof i!="number"?i=wt(this[ji],{min:1,max:e.length}):i>e.length?i=e.length:i<0&&(i=0);let r=[...e],s=r.length,o=s-i,a,l;for(;s-- >o;)l=Math.floor((s+1)*js(this[ji],{min:0,max:.99})),a=r[l],r[l]=r[s],r[s]=a;return r.slice(o)}pickOne(e){let t=wt(this[ji],{max:e.length-1});return e[t]}};var nr=Symbol("randomValue"),St=Symbol("mtValue"),it=class{[St];[nr];constructor(e){this[St]=Zt.fromSeed(e),this[nr]=new Qt(e)}seed(e){this[St]=Zt.fromSeed(e),this[nr].seed(e)}number(e={}){return wt(this[St],e)}float(e={}){return js(this[St],e)}datetime(e={}){return pn(this[St],e)}string(e=10,t){return cn(this[St],e,t)}character(e={}){return dn(this[St],e)}uuid(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{let i=this.number({min:0,max:15});return(t==="x"?i:i&3|8).toString(16)})}hash(e={}){let{length:t=40,casing:i="lower"}=e,r=i==="upper"?ga.toUpperCase():ga;return this.string(t,r)}boolean(e={}){let t={};if(typeof e=="number"?t.likelihood=e:typeof e=="object"&&(t={...e}),typeof t.likelihood>"u"&&(t.likelihood=wt(this[St],{min:0,max:100})),t.likelihood<0||t.likelihood>100)throw new RangeError("Invalid likelihood range. Accepted range is [0, 100].");return this[St].real2()*100<t.likelihood}falsy(e={}){let t=e.pool||[!1,null,0,NaN,""];return this[nr].pickOne(t)}hexaDecimal(e=1){let t=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","A","B","C","D","E","F"];return`0x${this[nr].pick(t,e).join("")}`}};var Nd={names:["January","February","March","April","May","June","July","August","September","October","November","December"],abbr:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]},mn=Nd;var $d={names:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],abbr:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"]},hn=$d;var Rd={month:mn,weekday:hn},fn=Rd;var jd=Object.freeze({consonants:"bcdfghjklmnprstvwz",vowels:"aeiou"}),gn=jd;var Cd={free:["gmail.com","yahoo.com","hotmail.com"],example:["example.org","example.com","example.net"]},yn=Cd;var Td={suffix:["com","biz","info","name","net","org"]},bn=Td;var Dd=["0therplanet_128.jpg","1markiz_128.jpg","2fockus_128.jpg","8d3k_128.jpg","91bilal_128.jpg","9lessons_128.jpg","AM_Kn2_128.jpg","AlbertoCococi_128.jpg","BenouarradeM_128.jpg","BillSKenney_128.jpg","BrianPurkiss_128.jpg","BroumiYoussef_128.jpg","BryanHorsey_128.jpg","Chakintosh_128.jpg","ChrisFarina78_128.jpg","Elt_n_128.jpg","GavicoInd_128.jpg","HenryHoffman_128.jpg","IsaryAmairani_128.jpg","Karimmove_128.jpg","LucasPerdidao_128.jpg","ManikRathee_128.jpg","RussellBishop_128.jpg","S0ufi4n3_128.jpg","SULiik_128.jpg","Shriiiiimp_128.jpg","Silveredge9_128.jpg","Skyhartman_128.jpg","SlaapMe_128.jpg","Stievius_128.jpg","Talbi_ConSept_128.jpg","VMilescu_128.jpg","VinThomas_128.jpg","YoungCutlass_128.jpg","ZacharyZorbas_128.jpg","_dwite__128.jpg","_kkga_128.jpg","_pedropinho_128.jpg","_ragzor_128.jpg","_scottburgess_128.jpg","_shahedk_128.jpg","_victa_128.jpg","_vojto_128.jpg","_williamguerra_128.jpg","_yardenoon_128.jpg","a1chapone_128.jpg","a_brixen_128.jpg","a_harris88_128.jpg","aaronalfred_128.jpg","aaroni_128.jpg","aaronkwhite_128.jpg","abdots_128.jpg","abdulhyeuk_128.jpg","abdullindenis_128.jpg","abelcabans_128.jpg","abotap_128.jpg","abovefunction_128.jpg","adamawesomeface_128.jpg","adammarsbar_128.jpg","adamnac_128.jpg","adamsxu_128.jpg","adellecharles_128.jpg","ademilter_128.jpg","adhamdannaway_128.jpg","adhiardana_128.jpg","adityasutomo_128.jpg","adobi_128.jpg","adrienths_128.jpg","aeon56_128.jpg","afusinatto_128.jpg","agromov_128.jpg","agustincruiz_128.jpg","ah_lice_128.jpg","ahmadajmi_128.jpg","ahmetalpbalkan_128.jpg","ahmetsulek_128.jpg","aiiaiiaii_128.jpg","ainsleywagon_128.jpg","aio____128.jpg","airskylar_128.jpg","aislinnkelly_128.jpg","ajaxy_ru_128.jpg","aka_james_128.jpg","akashsharma39_128.jpg","akmalfikri_128.jpg","akmur_128.jpg","al_li_128.jpg","alagoon_128.jpg","alan_zhang__128.jpg","albertaugustin_128.jpg","alecarpentier_128.jpg","aleclarsoniv_128.jpg","aleinadsays_128.jpg","alek_djuric_128.jpg","aleksitappura_128.jpg","alessandroribe_128.jpg","alevizio_128.jpg","alexandermayes_128.jpg","alexivanichkin_128.jpg","algunsanabria_128.jpg","allagringaus_128.jpg","allfordesign_128.jpg","allthingssmitty_128.jpg","alsobrooks_128.jpg","alterchuca_128.jpg","aluisio_azevedo_128.jpg","alxleroydeval_128.jpg","alxndrustinov_128.jpg","amandabuzard_128.jpg","amanruzaini_128.jpg","amayvs_128.jpg","amywebbb_128.jpg","anaami_128.jpg","anasnakawa_128.jpg","anatolinicolae_128.jpg","andrea211087_128.jpg","andreas_pr_128.jpg","andresdjasso_128.jpg","andresenfredrik_128.jpg","andrewabogado_128.jpg","andrewarrow_128.jpg","andrewcohen_128.jpg","andrewofficer_128.jpg","andyisonline_128.jpg","andysolomon_128.jpg","andytlaw_128.jpg","angelceballos_128.jpg","angelcolberg_128.jpg","angelcreative_128.jpg","anjhero_128.jpg","ankitind_128.jpg","anoff_128.jpg","anthonysukow_128.jpg","antjanus_128.jpg","antongenkin_128.jpg","antonyryndya_128.jpg","antonyzotov_128.jpg","aoimedia_128.jpg","apriendeau_128.jpg","arashmanteghi_128.jpg","areandacom_128.jpg","areus_128.jpg","ariffsetiawan_128.jpg","ariil_128.jpg","arindam__128.jpg","arishi__128.jpg","arkokoley_128.jpg","aroon_sharma_128.jpg","arpitnj_128.jpg","artd_sign_128.jpg","artem_kostenko_128.jpg","arthurholcombe1_128.jpg","artvavs_128.jpg","ashernatali_128.jpg","ashocka18_128.jpg","atanism_128.jpg","atariboy_128.jpg","ateneupopular_128.jpg","attacks_128.jpg","aviddayentonbay_128.jpg","axel_128.jpg","badlittleduck_128.jpg","bagawarman_128.jpg","baires_128.jpg","balakayuriy_128.jpg","balintorosz_128.jpg","baliomega_128.jpg","baluli_128.jpg","bargaorobalo_128.jpg","barputro_128.jpg","bartjo_128.jpg","bartoszdawydzik_128.jpg","bassamology_128.jpg","batsirai_128.jpg","baumann_alex_128.jpg","baumannzone_128.jpg","bboy1895_128.jpg","bcrad_128.jpg","begreative_128.jpg","belyaev_rs_128.jpg","benefritz_128.jpg","benjamin_knight_128.jpg","bennyjien_128.jpg","benoitboucart_128.jpg","bereto_128.jpg","bergmartin_128.jpg","bermonpainter_128.jpg","bertboerland_128.jpg","besbujupi_128.jpg","beshur_128.jpg","betraydan_128.jpg","beweinreich_128.jpg","bfrohs_128.jpg","bighanddesign_128.jpg","bigmancho_128.jpg","billyroshan_128.jpg","bistrianiosip_128.jpg","blakehawksworth_128.jpg","blakesimkins_128.jpg","bluefx__128.jpg","bluesix_128.jpg","bobbytwoshoes_128.jpg","bobwassermann_128.jpg","bolzanmarco_128.jpg","borantula_128.jpg","borges_marcos_128.jpg","bowbrick_128.jpg","boxmodel_128.jpg","bpartridge_128.jpg","bradenhamm_128.jpg","brajeshwar_128.jpg","brandclay_128.jpg","brandonburke_128.jpg","brandonflatsoda_128.jpg","brandonmorreale_128.jpg","brenmurrell_128.jpg","brenton_clarke_128.jpg","bruno_mart_128.jpg","brunodesign1206_128.jpg","bryan_topham_128.jpg","bu7921_128.jpg","bublienko_128.jpg","buddhasource_128.jpg","buleswapnil_128.jpg","bungiwan_128.jpg","buryaknick_128.jpg","buzzusborne_128.jpg","byrnecore_128.jpg","byryan_128.jpg","cadikkara_128.jpg","calebjoyce_128.jpg","calebogden_128.jpg","canapud_128.jpg","carbontwelve_128.jpg","carlfairclough_128.jpg","carlosblanco_eu_128.jpg","carlosgavina_128.jpg","carlosjgsousa_128.jpg","carlosm_128.jpg","carlyson_128.jpg","caseycavanagh_128.jpg","caspergrl_128.jpg","catadeleon_128.jpg","catarino_128.jpg","cboller1_128.jpg","cbracco_128.jpg","ccinojasso1_128.jpg","cdavis565_128.jpg","cdharrison_128.jpg","ceekaytweet_128.jpg","cemshid_128.jpg","cggaurav_128.jpg","chaabane_wail_128.jpg","chacky14_128.jpg","chadami_128.jpg","chadengle_128.jpg","chaensel_128.jpg","chandlervdw_128.jpg","chanpory_128.jpg","charlesrpratt_128.jpg","charliecwaite_128.jpg","charliegann_128.jpg","chatyrko_128.jpg","cherif_b_128.jpg","chris_frees_128.jpg","chris_witko_128.jpg","chrismj83_128.jpg","chrisslowik_128.jpg","chrisstumph_128.jpg","christianoliff_128.jpg","chrisvanderkooi_128.jpg","ciaranr_128.jpg","cicerobr_128.jpg","claudioguglieri_128.jpg","cloudstudio_128.jpg","clubb3rry_128.jpg","cocolero_128.jpg","codepoet_ru_128.jpg","coderdiaz_128.jpg","codysanfilippo_128.jpg","cofla_128.jpg","colgruv_128.jpg","colirpixoil_128.jpg","collegeman_128.jpg","commadelimited_128.jpg","conspirator_128.jpg","constantx_128.jpg","coreyginnivan_128.jpg","coreyhaggard_128.jpg","coreyweb_128.jpg","craigelimeliah_128.jpg","craighenneberry_128.jpg","craigrcoles_128.jpg","creartinc_128.jpg","croakx_128.jpg","curiousoffice_128.jpg","curiousonaut_128.jpg","cybind_128.jpg","cynthiasavard_128.jpg","cyril_gaillard_128.jpg","d00maz_128.jpg","d33pthought_128.jpg","d_kobelyatsky_128.jpg","d_nny_m_cher_128.jpg","dactrtr_128.jpg","dahparra_128.jpg","dallasbpeters_128.jpg","damenleeturks_128.jpg","danillos_128.jpg","daniloc_128.jpg","danmartin70_128.jpg","dannol_128.jpg","danpliego_128.jpg","danro_128.jpg","dansowter_128.jpg","danthms_128.jpg","danvernon_128.jpg","danvierich_128.jpg","darcystonge_128.jpg","darylws_128.jpg","davecraige_128.jpg","davidbaldie_128.jpg","davidcazalis_128.jpg","davidhemphill_128.jpg","davidmerrique_128.jpg","davidsasda_128.jpg","dawidwu_128.jpg","daykiine_128.jpg","dc_user_128.jpg","dcalonaci_128.jpg","ddggccaa_128.jpg","de_ascanio_128.jpg","deeenright_128.jpg","demersdesigns_128.jpg","denisepires_128.jpg","depaulawagner_128.jpg","derekcramer_128.jpg","derekebradley_128.jpg","derienzo777_128.jpg","desastrozo_128.jpg","designervzm_128.jpg","dev_essentials_128.jpg","devankoshal_128.jpg","deviljho__128.jpg","devinhalladay_128.jpg","dgajjar_128.jpg","dgclegg_128.jpg","dhilipsiva_128.jpg","dhoot_amit_128.jpg","dhooyenga_128.jpg","dhrubo_128.jpg","diansigitp_128.jpg","dicesales_128.jpg","diesellaws_128.jpg","digitalmaverick_128.jpg","dimaposnyy_128.jpg","dingyi_128.jpg","divya_128.jpg","dixchen_128.jpg","djsherman_128.jpg","dmackerman_128.jpg","dmitriychuta_128.jpg","dnezkumar_128.jpg","dnirmal_128.jpg","donjain_128.jpg","doooon_128.jpg","doronmalki_128.jpg","dorphern_128.jpg","dotgridline_128.jpg","dparrelli_128.jpg","dpmachado_128.jpg","dreizle_128.jpg","drewbyreese_128.jpg","dshster_128.jpg","dss49_128.jpg","dudestein_128.jpg","duivvv_128.jpg","dutchnadia_128.jpg","dvdwinden_128.jpg","dzantievm_128.jpg","ecommerceil_128.jpg","eddiechen_128.jpg","edgarchris99_128.jpg","edhenderson_128.jpg","edkf_128.jpg","edobene_128.jpg","eduardostuart_128.jpg","ehsandiary_128.jpg","eitarafa_128.jpg","el_fuertisimo_128.jpg","elbuscainfo_128.jpg","elenadissi_128.jpg","elisabethkjaer_128.jpg","elliotlewis_128.jpg","elliotnolten_128.jpg","embrcecreations_128.jpg","emileboudeling_128.jpg","emmandenn_128.jpg","emmeffess_128.jpg","emsgulam_128.jpg","enda_128.jpg","enjoythetau_128.jpg","enricocicconi_128.jpg","envex_128.jpg","ernestsemerda_128.jpg","erwanhesry_128.jpg","estebanuribe_128.jpg","eugeneeweb_128.jpg","evandrix_128.jpg","evanshajed_128.jpg","exentrich_128.jpg","eyronn_128.jpg","fabbianz_128.jpg","fabbrucci_128.jpg","faisalabid_128.jpg","falconerie_128.jpg","falling_soul_128.jpg","falvarad_128.jpg","felipeapiress_128.jpg","felipecsl_128.jpg","ffbel_128.jpg","finchjke_128.jpg","findingjenny_128.jpg","fiterik_128.jpg","fjaguero_128.jpg","flashmurphy_128.jpg","flexrs_128.jpg","foczzi_128.jpg","fotomagin_128.jpg","fran_mchamy_128.jpg","francis_vega_128.jpg","franciscoamk_128.jpg","frankiefreesbie_128.jpg","fronx_128.jpg","funwatercat_128.jpg","g3d_128.jpg","gaborenton_128.jpg","gabrielizalo_128.jpg","gabrielrosser_128.jpg","ganserene_128.jpg","garand_128.jpg","gauchomatt_128.jpg","gauravjassal_128.jpg","gavr1l0_128.jpg","gcmorley_128.jpg","gearpixels_128.jpg","geneseleznev_128.jpg","geobikas_128.jpg","geran7_128.jpg","geshan_128.jpg","giancarlon_128.jpg","gipsy_raf_128.jpg","giuliusa_128.jpg","gizmeedevil1991_128.jpg","gkaam_128.jpg","gmourier_128.jpg","goddardlewis_128.jpg","gofrasdesign_128.jpg","gojeanyn_128.jpg","gonzalorobaina_128.jpg","grahamkennery_128.jpg","greenbes_128.jpg","gregkilian_128.jpg","gregrwilkinson_128.jpg","gregsqueeb_128.jpg","grrr_nl_128.jpg","gseguin_128.jpg","gt_128.jpg","gu5taf_128.jpg","guiiipontes_128.jpg","guillemboti_128.jpg","guischmitt_128.jpg","gusoto_128.jpg","h1brd_128.jpg","hafeeskhan_128.jpg","hai_ninh_nguyen_128.jpg","haligaliharun_128.jpg","hanna_smi_128.jpg","happypeter1983_128.jpg","harry_sistalam_128.jpg","haruintesettden_128.jpg","hasslunsford_128.jpg","haydn_woods_128.jpg","helderleal_128.jpg","hellofeverrrr_128.jpg","her_ruu_128.jpg","herbigt_128.jpg","herkulano_128.jpg","hermanobrother_128.jpg","herrhaase_128.jpg","heycamtaylor_128.jpg","heyimjuani_128.jpg","heykenneth_128.jpg","hfalucas_128.jpg","hgharrygo_128.jpg","hiemil_128.jpg","hjartstrorn_128.jpg","hoangloi_128.jpg","holdenweb_128.jpg","homka_128.jpg","horaciobella_128.jpg","hota_v_128.jpg","hsinyo23_128.jpg","hugocornejo_128.jpg","hugomano_128.jpg","iamgarth_128.jpg","iamglimy_128.jpg","iamjdeleon_128.jpg","iamkarna_128.jpg","iamkeithmason_128.jpg","iamsteffen_128.jpg","id835559_128.jpg","idiot_128.jpg","iduuck_128.jpg","ifarafonow_128.jpg","igorgarybaldi_128.jpg","illyzoren_128.jpg","ilya_pestov_128.jpg","imammuht_128.jpg","imcoding_128.jpg","imomenui_128.jpg","imsoper_128.jpg","increase_128.jpg","incubo82_128.jpg","instalox_128.jpg","ionuss_128.jpg","ipavelek_128.jpg","iqbalperkasa_128.jpg","iqonicd_128.jpg","irae_128.jpg","isaacfifth_128.jpg","isacosta_128.jpg","ismail_biltagi_128.jpg","isnifer_128.jpg","itolmach_128.jpg","itsajimithing_128.jpg","itskawsar_128.jpg","itstotallyamy_128.jpg","ivanfilipovbg_128.jpg","j04ntoh_128.jpg","j2deme_128.jpg","j_drake__128.jpg","jackiesaik_128.jpg","jacksonlatka_128.jpg","jacobbennett_128.jpg","jagan123_128.jpg","jakemoore_128.jpg","jamiebrittain_128.jpg","janpalounek_128.jpg","jarjan_128.jpg","jarsen_128.jpg","jasonmarkjones_128.jpg","javorszky_128.jpg","jay_wilburn_128.jpg","jayphen_128.jpg","jayrobinson_128.jpg","jcubic_128.jpg","jedbridges_128.jpg","jefffis_128.jpg","jeffgolenski_128.jpg","jehnglynn_128.jpg","jennyshen_128.jpg","jennyyo_128.jpg","jeremery_128.jpg","jeremiaha_128.jpg","jeremiespoken_128.jpg","jeremymouton_128.jpg","jeremyshimko_128.jpg","jeremyworboys_128.jpg","jerrybai1907_128.jpg","jervo_128.jpg","jesseddy_128.jpg","jffgrdnr_128.jpg","jghyllebert_128.jpg","jimmuirhead_128.jpg","jitachi_128.jpg","jjshaw14_128.jpg","jjsiii_128.jpg","jlsolerdeltoro_128.jpg","jm_denis_128.jpg","jmfsocial_128.jpg","jmillspaysbills_128.jpg","jnmnrd_128.jpg","joannefournier_128.jpg","joaoedumedeiros_128.jpg","jodytaggart_128.jpg","joe_black_128.jpg","joelcipriano_128.jpg","joelhelin_128.jpg","joemdesign_128.jpg","joetruesdell_128.jpg","joeymurdah_128.jpg","johannesneu_128.jpg","johncafazza_128.jpg","johndezember_128.jpg","johnriordan_128.jpg","johnsmithagency_128.jpg","joki4_128.jpg","jomarmen_128.jpg","jonathansimmons_128.jpg","jonkspr_128.jpg","jonsgotwood_128.jpg","jordyvdboom_128.jpg","joreira_128.jpg","josecarlospsh_128.jpg","josemarques_128.jpg","josep_martins_128.jpg","josevnclch_128.jpg","joshaustin_128.jpg","joshhemsley_128.jpg","joshmedeski_128.jpg","joshuaraichur_128.jpg","joshuasortino_128.jpg","jpenico_128.jpg","jpscribbles_128.jpg","jqiuss_128.jpg","juamperro_128.jpg","juangomezw_128.jpg","juanmamartinez_128.jpg","juaumlol_128.jpg","judzhin_miles_128.jpg","justinrgraham_128.jpg","justinrhee_128.jpg","justinrob_128.jpg","justme_timothyg_128.jpg","jwalter14_128.jpg","jydesign_128.jpg","kaelifa_128.jpg","kalmerrautam_128.jpg","kamal_chaneman_128.jpg","kanickairaj_128.jpg","kapaluccio_128.jpg","karalek_128.jpg","karlkanall_128.jpg","karolkrakowiak__128.jpg","karsh_128.jpg","karthipanraj_128.jpg","kaspernordkvist_128.jpg","katiemdaly_128.jpg","kaysix_dizzy_128.jpg","kazaky999_128.jpg","kennyadr_128.jpg","kerem_128.jpg","kerihenare_128.jpg","keryilmaz_128.jpg","kevinjohndayy_128.jpg","kevinoh_128.jpg","kevka_128.jpg","keyuri85_128.jpg","kianoshp_128.jpg","kijanmaharjan_128.jpg","kikillo_128.jpg","kimcool_128.jpg","kinday_128.jpg","kirangopal_128.jpg","kiwiupover_128.jpg","kkusaa_128.jpg","klefue_128.jpg","klimmka_128.jpg","knilob_128.jpg","kohette_128.jpg","kojourin_128.jpg","kolage_128.jpg","kolmarlopez_128.jpg","kolsvein_128.jpg","konus_128.jpg","koridhandy_128.jpg","kosmar_128.jpg","kostaspt_128.jpg","krasnoukhov_128.jpg","krystalfister_128.jpg","kucingbelang4_128.jpg","kudretkeskin_128.jpg","kuldarkalvik_128.jpg","kumarrajan12123_128.jpg","kurafire_128.jpg","kurtinc_128.jpg","kushsolitary_128.jpg","kvasnic_128.jpg","ky_128.jpg","kylefoundry_128.jpg","kylefrost_128.jpg","laasli_128.jpg","lanceguyatt_128.jpg","langate_128.jpg","larrybolt_128.jpg","larrygerard_128.jpg","laurengray_128.jpg","lawlbwoy_128.jpg","layerssss_128.jpg","leandrovaranda_128.jpg","lebinoclard_128.jpg","lebronjennan_128.jpg","leehambley_128.jpg","leeiio_128.jpg","leemunroe_128.jpg","leonfedotov_128.jpg","lepetitogre_128.jpg","lepinski_128.jpg","levisan_128.jpg","lewisainslie_128.jpg","lhausermann_128.jpg","liminha_128.jpg","lingeswaran_128.jpg","linkibol_128.jpg","linux29_128.jpg","lisovsky_128.jpg","llun_128.jpg","lmjabreu_128.jpg","loganjlambert_128.jpg","logorado_128.jpg","lokesh_coder_128.jpg","lonesomelemon_128.jpg","longlivemyword_128.jpg","looneydoodle_128.jpg","lososina_128.jpg","louis_currie_128.jpg","low_res_128.jpg","lowie_128.jpg","lu4sh1i_128.jpg","ludwiczakpawel_128.jpg","luxe_128.jpg","lvovenok_128.jpg","m4rio_128.jpg","m_kalibry_128.jpg","ma_tiax_128.jpg","mactopus_128.jpg","macxim_128.jpg","madcampos_128.jpg","madebybrenton_128.jpg","madebyvadim_128.jpg","madewulf_128.jpg","madshensel_128.jpg","madysondesigns_128.jpg","magoo04_128.jpg","magugzbrand2d_128.jpg","mahdif_128.jpg","mahmoudmetwally_128.jpg","maikelk_128.jpg","maiklam_128.jpg","malgordon_128.jpg","malykhinv_128.jpg","mandalareopens_128.jpg","manekenthe_128.jpg","mangosango_128.jpg","manigm_128.jpg","marakasina_128.jpg","marciotoledo_128.jpg","marclgonzales_128.jpg","marcobarbosa_128.jpg","marcomano__128.jpg","marcoramires_128.jpg","marcusgorillius_128.jpg","markjenkins_128.jpg","marklamb_128.jpg","markolschesky_128.jpg","markretzloff_128.jpg","markwienands_128.jpg","marlinjayakody_128.jpg","marosholly_128.jpg","marrimo_128.jpg","marshallchen__128.jpg","martinansty_128.jpg","martip07_128.jpg","mashaaaaal_128.jpg","mastermindesign_128.jpg","matbeedotcom_128.jpg","mateaodviteza_128.jpg","matkins_128.jpg","matt3224_128.jpg","mattbilotti_128.jpg","mattdetails_128.jpg","matthewkay__128.jpg","mattlat_128.jpg","mattsapii_128.jpg","mauriolg_128.jpg","maximseshuk_128.jpg","maximsorokin_128.jpg","maxlinderman_128.jpg","maz_128.jpg","mbilalsiddique1_128.jpg","mbilderbach_128.jpg","mcflydesign_128.jpg","mds_128.jpg","mdsisto_128.jpg","meelford_128.jpg","megdraws_128.jpg","mekal_128.jpg","meln1ks_128.jpg","melvindidit_128.jpg","mfacchinello_128.jpg","mgonto_128.jpg","mhaligowski_128.jpg","mhesslow_128.jpg","mhudobivnik_128.jpg","michaelabehsera_128.jpg","michaelbrooksjr_128.jpg","michaelcolenso_128.jpg","michaelcomiskey_128.jpg","michaelkoper_128.jpg","michaelmartinho_128.jpg","michalhron_128.jpg","michigangraham_128.jpg","michzen_128.jpg","mighty55_128.jpg","miguelkooreman_128.jpg","miguelmendes_128.jpg","mikaeljorhult_128.jpg","mikebeecham_128.jpg","mikemai2awesome_128.jpg","millinet_128.jpg","mirfanqureshi_128.jpg","missaaamy_128.jpg","mizhgan_128.jpg","mizko_128.jpg","mkginfo_128.jpg","mocabyte_128.jpg","mohanrohith_128.jpg","moscoz_128.jpg","motionthinks_128.jpg","moynihan_128.jpg","mr_shiznit_128.jpg","mr_subtle_128.jpg","mrebay007_128.jpg","mrjamesnoble_128.jpg","mrmartineau_128.jpg","mrxloka_128.jpg","mslarkina_128.jpg","msveet_128.jpg","mtolokonnikov_128.jpg","mufaddal_mw_128.jpg","mugukamil_128.jpg","muridrahhal_128.jpg","muringa_128.jpg","murrayswift_128.jpg","mutlu82_128.jpg","mutu_krish_128.jpg","mvdheuvel_128.jpg","mwarkentin_128.jpg","myastro_128.jpg","mylesb_128.jpg","mymyboy_128.jpg","n1ght_coder_128.jpg","n3dmax_128.jpg","n_tassone_128.jpg","nacho_128.jpg","naitanamoreno_128.jpg","namankreative_128.jpg","nandini_m_128.jpg","nasirwd_128.jpg","nastya_mane_128.jpg","nateschulte_128.jpg","nathalie_fs_128.jpg","naupintos_128.jpg","nbirckel_128.jpg","nckjrvs_128.jpg","necodymiconer_128.jpg","nehfy_128.jpg","nellleo_128.jpg","nelshd_128.jpg","nelsonjoyce_128.jpg","nemanjaivanovic_128.jpg","nepdud_128.jpg","nerdgr8_128.jpg","nerrsoft_128.jpg","nessoila_128.jpg","netonet_il_128.jpg","newbrushes_128.jpg","nfedoroff_128.jpg","nickfratter_128.jpg","nicklacke_128.jpg","nicolai_larsen_128.jpg","nicolasfolliot_128.jpg","nicoleglynn_128.jpg","nicollerich_128.jpg","nilshelmersson_128.jpg","nilshoenson_128.jpg","ninjad3m0_128.jpg","nitinhayaran_128.jpg","nomidesigns_128.jpg","normanbox_128.jpg","notbadart_128.jpg","noufalibrahim_128.jpg","noxdzine_128.jpg","nsamoylov_128.jpg","ntfblog_128.jpg","nutzumi_128.jpg","nvkznemo_128.jpg","nwdsha_128.jpg","nyancecom_128.jpg","oaktreemedia_128.jpg","okandungel_128.jpg","okansurreel_128.jpg","okcoker_128.jpg","oksanafrewer_128.jpg","okseanjay_128.jpg","oktayelipek_128.jpg","olaolusoga_128.jpg","olgary_128.jpg","omnizya_128.jpg","ooomz_128.jpg","operatino_128.jpg","opnsrce_128.jpg","orkuncaylar_128.jpg","oscarowusu_128.jpg","oskamaya_128.jpg","oskarlevinson_128.jpg","osmanince_128.jpg","osmond_128.jpg","ostirbu_128.jpg","osvaldas_128.jpg","otozk_128.jpg","ovall_128.jpg","overcloacked_128.jpg","overra_128.jpg","panchajanyag_128.jpg","panghal0_128.jpg","patrickcoombe_128.jpg","paulfarino_128.jpg","pcridesagain_128.jpg","peachananr_128.jpg","pechkinator_128.jpg","peejfancher_128.jpg","pehamondello_128.jpg","perfectflow_128.jpg","perretmagali_128.jpg","petar_prog_128.jpg","petebernardo_128.jpg","peter576_128.jpg","peterlandt_128.jpg","petrangr_128.jpg","phillapier_128.jpg","picard102_128.jpg","pierre_nel_128.jpg","pierrestoffe_128.jpg","pifagor_128.jpg","pixage_128.jpg","plasticine_128.jpg","plbabin_128.jpg","pmeissner_128.jpg","polarity_128.jpg","ponchomendivil_128.jpg","poormini_128.jpg","popey_128.jpg","posterjob_128.jpg","praveen_vijaya_128.jpg","prheemo_128.jpg","primozcigler_128.jpg","prinzadi_128.jpg","privetwagner_128.jpg","prrstn_128.jpg","psaikali_128.jpg","psdesignuk_128.jpg","puzik_128.jpg","pyronite_128.jpg","quailandquasar_128.jpg","r_garcia_128.jpg","r_oy_128.jpg","rachelreveley_128.jpg","rahmeen_128.jpg","ralph_lam_128.jpg","ramanathan_pdy_128.jpg","randomlies_128.jpg","rangafangs_128.jpg","raphaelnikson_128.jpg","raquelwilson_128.jpg","ratbus_128.jpg","rawdiggie_128.jpg","rdbannon_128.jpg","rdsaunders_128.jpg","reabo101_128.jpg","reetajayendra_128.jpg","rehatkathuria_128.jpg","reideiredale_128.jpg","renbyrd_128.jpg","rez___a_128.jpg","ricburton_128.jpg","richardgarretts_128.jpg","richwild_128.jpg","rickdt_128.jpg","rickyyean_128.jpg","rikas_128.jpg","ripplemdk_128.jpg","rmlewisuk_128.jpg","rob_thomas10_128.jpg","robbschiller_128.jpg","robergd_128.jpg","robinclediere_128.jpg","robinlayfield_128.jpg","robturlinckx_128.jpg","rodnylobos_128.jpg","rohixx_128.jpg","romanbulah_128.jpg","roxanejammet_128.jpg","roybarberuk_128.jpg","rpatey_128.jpg","rpeezy_128.jpg","rtgibbons_128.jpg","rtyukmaev_128.jpg","rude_128.jpg","ruehldesign_128.jpg","runningskull_128.jpg","russell_baylis_128.jpg","russoedu_128.jpg","ruzinav_128.jpg","rweve_128.jpg","ryandownie_128.jpg","ryanjohnson_me_128.jpg","ryankirkman_128.jpg","ryanmclaughlin_128.jpg","ryhanhassan_128.jpg","ryuchi311_128.jpg","s4f1_128.jpg","saarabpreet_128.jpg","sachacorazzi_128.jpg","sachingawas_128.jpg","safrankov_128.jpg","sainraja_128.jpg","salimianoff_128.jpg","salleedesign_128.jpg","salvafc_128.jpg","samgrover_128.jpg","samihah_128.jpg","samscouto_128.jpg","samuelkraft_128.jpg","sandywoodruff_128.jpg","sangdth_128.jpg","santi_urso_128.jpg","saschadroste_128.jpg","saschamt_128.jpg","sasha_shestakov_128.jpg","saulihirvi_128.jpg","sawalazar_128.jpg","sawrb_128.jpg","sbtransparent_128.jpg","scips_128.jpg","scott_riley_128.jpg","scottfeltham_128.jpg","scottgallant_128.jpg","scottiedude_128.jpg","scottkclark_128.jpg","scrapdnb_128.jpg","sdidonato_128.jpg","sebashton_128.jpg","sementiy_128.jpg","serefka_128.jpg","sergeyalmone_128.jpg","sergeysafonov_128.jpg","sethlouey_128.jpg","seyedhossein1_128.jpg","sgaurav_baghel_128.jpg","shadeed9_128.jpg","shalt0ni_128.jpg","shaneIxD_128.jpg","shanehudson_128.jpg","sharvin_128.jpg","shesgared_128.jpg","shinze_128.jpg","shoaib253_128.jpg","shojberg_128.jpg","shvelo96_128.jpg","silv3rgvn_128.jpg","silvanmuhlemann_128.jpg","simobenso_128.jpg","sindresorhus_128.jpg","sircalebgrove_128.jpg","skkirilov_128.jpg","slowspock_128.jpg","smaczny_128.jpg","smalonso_128.jpg","smenov_128.jpg","snowshade_128.jpg","snowwrite_128.jpg","sokaniwaal_128.jpg","solid_color_128.jpg","souperphly_128.jpg","souuf_128.jpg","sovesove_128.jpg","soyjavi_128.jpg","spacewood__128.jpg","spbroma_128.jpg","spedwig_128.jpg","sprayaga_128.jpg","sreejithexp_128.jpg","ssbb_me_128.jpg","ssiskind_128.jpg","sta1ex_128.jpg","stalewine_128.jpg","stan_128.jpg","stayuber_128.jpg","stefanotirloni_128.jpg","stefanozoffoli_128.jpg","stefooo_128.jpg","stefvdham_128.jpg","stephcoue_128.jpg","sterlingrules_128.jpg","stevedesigner_128.jpg","steynviljoen_128.jpg","strikewan_128.jpg","stushona_128.jpg","sulaqo_128.jpg","sunlandictwin_128.jpg","sunshinedgirl_128.jpg","superoutman_128.jpg","supervova_128.jpg","supjoey_128.jpg","suprb_128.jpg","sur4dye_128.jpg","surgeonist_128.jpg","suribbles_128.jpg","svenlen_128.jpg","swaplord_128.jpg","sweetdelisa_128.jpg","switmer777_128.jpg","swooshycueb_128.jpg","sydlawrence_128.jpg","syropian_128.jpg","tanveerrao_128.jpg","taybenlor_128.jpg","taylorling_128.jpg","tbakdesigns_128.jpg","teddyzetterlund_128.jpg","teeragit_128.jpg","tereshenkov_128.jpg","terpimost_128.jpg","terrorpixel_128.jpg","terryxlife_128.jpg","teylorfeliz_128.jpg","tgerken_128.jpg","tgormtx_128.jpg","thaisselenator__128.jpg","thaodang17_128.jpg","thatonetommy_128.jpg","the_purplebunny_128.jpg","the_winslet_128.jpg","thedamianhdez_128.jpg","thedjpetersen_128.jpg","thehacker_128.jpg","thekevinjones_128.jpg","themadray_128.jpg","themikenagle_128.jpg","themrdave_128.jpg","theonlyzeke_128.jpg","therealmarvin_128.jpg","thewillbeard_128.jpg","thiagovernetti_128.jpg","thibaut_re_128.jpg","thierrykoblentz_128.jpg","thierrymeier__128.jpg","thimo_cz_128.jpg","thinkleft_128.jpg","thomasgeisen_128.jpg","thomasschrijer_128.jpg","timgthomas_128.jpg","timmillwood_128.jpg","timothycd_128.jpg","timpetricola_128.jpg","tjrus_128.jpg","to_soham_128.jpg","tobysaxon_128.jpg","toddrew_128.jpg","tom_even_128.jpg","tomas_janousek_128.jpg","tonymillion_128.jpg","traneblow_128.jpg","travis_arnold_128.jpg","travishines_128.jpg","tristanlegros_128.jpg","trubeatto_128.jpg","trueblood_33_128.jpg","tumski_128.jpg","tur8le_128.jpg","turkutuuli_128.jpg","tweetubhai_128.jpg","twittypork_128.jpg","txcx_128.jpg","uberschizo_128.jpg","ultragex_128.jpg","umurgdk_128.jpg","unterdreht_128.jpg","urrutimeoli_128.jpg","uxalex_128.jpg","uxpiper_128.jpg","uxward_128.jpg","vanchesz_128.jpg","vaughanmoffitt_128.jpg","vc27_128.jpg","vicivadeline_128.jpg","victorDubugras_128.jpg","victor_haydin_128.jpg","victordeanda_128.jpg","victorerixon_128.jpg","victorquinn_128.jpg","victorstuber_128.jpg","vigobronx_128.jpg","vijaykarthik_128.jpg","vikashpathak18_128.jpg","vikasvinfotech_128.jpg","vimarethomas_128.jpg","vinciarts_128.jpg","vitor376_128.jpg","vitorleal_128.jpg","vivekprvr_128.jpg","vj_demien_128.jpg","vladarbatov_128.jpg","vladimirdevic_128.jpg","vladyn_128.jpg","vlajki_128.jpg","vm_f_128.jpg","vocino_128.jpg","vonachoo_128.jpg","vovkasolovev_128.jpg","vytautas_a_128.jpg","waghner_128.jpg","wake_gs_128.jpg","we_social_128.jpg","wearesavas_128.jpg","weavermedia_128.jpg","webtanya_128.jpg","weglov_128.jpg","wegotvices_128.jpg","wesleytrankin_128.jpg","wikiziner_128.jpg","wiljanslofstra_128.jpg","wim1k_128.jpg","wintopia_128.jpg","woodsman001_128.jpg","woodydotmx_128.jpg","wtrsld_128.jpg","xadhix_128.jpg","xalionmalik_128.jpg","xamorep_128.jpg","xiel_128.jpg","xilantra_128.jpg","xravil_128.jpg","xripunov_128.jpg","xtopherpaul_128.jpg","y2graphic_128.jpg","yalozhkin_128.jpg","yassiryahya_128.jpg","yayteejay_128.jpg","yecidsm_128.jpg","yehudab_128.jpg","yesmeck_128.jpg","yigitpinarbasi_128.jpg","zackeeler_128.jpg","zaki3d_128.jpg","zauerkraut_128.jpg","zforrester_128.jpg","zvchkelly_128.jpg"],kn=Dd;var Md={email:yn,domain:bn,avatar:kn},vn=Md;var Ld={female:["Mary","Patricia","Linda","Barbara","Elizabeth","Jennifer","Maria","Susan","Margaret","Dorothy","Lisa","Nancy","Karen","Betty","Helen","Sandra","Donna","Carol","Ruth","Sharon","Michelle","Laura","Sarah","Kimberly","Deborah","Jessica","Shirley","Cynthia","Angela","Melissa","Brenda","Amy","Anna","Rebecca","Virginia","Kathleen","Pamela","Martha","Debra","Amanda","Stephanie","Carolyn","Christine","Marie","Janet","Catherine","Frances","Ann","Joyce","Diane","Alice","Julie","Heather","Teresa","Doris","Gloria","Evelyn","Jean","Cheryl","Mildred","Katherine","Joan","Ashley","Judith","Rose","Janice","Kelly","Nicole","Judy","Christina","Kathy","Theresa","Beverly","Denise","Tammy","Irene","Jane","Lori","Rachel","Marilyn","Andrea","Kathryn","Louise","Sara","Anne","Jacqueline","Wanda","Bonnie","Julia","Ruby","Lois","Tina","Phyllis","Norma","Paula","Diana","Annie","Lillian","Emily","Robin","Peggy","Crystal","Gladys","Rita","Dawn","Connie","Florence","Tracy","Edna","Tiffany","Carmen","Rosa","Cindy","Grace","Wendy","Victoria","Edith","Kim","Sherry","Sylvia","Josephine","Thelma","Shannon","Sheila","Ethel","Ellen","Elaine","Marjorie","Carrie","Charlotte","Monica","Esther","Pauline","Emma","Juanita","Anita","Rhonda","Hazel","Amber","Eva","Debbie","April","Leslie","Clara","Lucille","Jamie","Joanne","Eleanor","Valerie","Danielle","Megan","Alicia","Suzanne","Michele","Gail","Bertha","Darlene","Veronica","Jill","Erin","Geraldine","Lauren","Cathy","Joann","Lorraine","Lynn","Sally","Regina","Erica","Beatrice","Dolores","Bernice","Audrey","Yvonne","Annette","June","Samantha","Marion","Dana","Stacy","Ana","Renee","Ida","Vivian","Roberta","Holly","Brittany","Melanie","Loretta","Yolanda","Jeanette","Laurie","Katie","Kristen","Vanessa","Alma","Sue","Elsie","Beth","Jeanne","Vicki","Carla","Tara","Rosemary","Eileen","Terri","Gertrude","Lucy","Tonya","Ella","Stacey","Wilma","Gina","Kristin","Jessie","Natalie","Agnes","Vera","Willie","Charlene","Bessie","Delores","Melinda","Pearl","Arlene","Maureen","Colleen","Allison","Tamara","Joy","Georgia","Constance","Lillie","Claudia","Jackie","Marcia","Tanya","Nellie","Minnie","Marlene","Heidi","Glenda","Lydia","Viola","Courtney","Marian","Stella","Caroline","Dora","Jo","Vickie","Mattie","Terry","Maxine","Irma","Mabel","Marsha","Myrtle","Lena","Christy","Deanna","Patsy","Hilda","Gwendolyn","Jennie","Nora","Margie","Nina","Cassandra","Leah","Penny","Kay","Priscilla","Naomi","Carole","Brandy","Olga","Billie","Dianne","Tracey","Leona","Jenny","Felicia","Sonia","Miriam","Velma","Becky","Bobbie","Violet","Kristina","Toni","Misty","Mae","Shelly","Daisy","Ramona","Sherri","Erika","Katrina","Claire","Lindsey","Lindsay","Geneva","Guadalupe","Belinda","Margarita","Sheryl","Cora","Faye","Ada","Natasha","Sabrina","Isabel","Marguerite","Hattie","Harriet","Molly","Cecilia","Kristi","Brandi","Blanche","Sandy","Rosie","Joanna","Iris","Eunice","Angie","Inez","Lynda","Madeline","Amelia","Alberta","Genevieve","Monique","Jodi","Janie","Maggie","Kayla","Sonya","Jan","Lee","Kristine","Candace","Fannie","Maryann","Opal","Alison","Yvette","Melody","Luz","Susie","Olivia","Flora","Shelley","Kristy","Mamie","Lula","Lola","Verna","Beulah","Antoinette","Candice","Juana","Jeannette","Pam","Kelli","Hannah","Whitney","Bridget","Karla","Celia","Latoya","Patty","Shelia","Gayle","Della","Vicky","Lynne","Sheri","Marianne","Kara","Jacquelyn","Erma","Blanca","Myra","Leticia","Pat","Krista","Roxanne","Angelica","Johnnie","Robyn","Francis","Adrienne","Rosalie","Alexandra","Brooke","Bethany","Sadie","Bernadette","Traci","Jody","Kendra","Jasmine","Nichole","Rachael","Chelsea","Mable","Ernestine","Muriel","Marcella","Elena","Krystal","Angelina","Nadine","Kari","Estelle","Dianna","Paulette","Lora","Mona","Doreen","Rosemarie","Angel","Desiree","Antonia","Hope","Ginger","Janis","Betsy","Christie","Freda","Mercedes","Meredith","Lynette","Teri","Cristina","Eula","Leigh","Meghan","Sophia","Eloise","Rochelle","Gretchen","Cecelia","Raquel","Henrietta","Alyssa","Jana","Kelley","Gwen","Kerry","Jenna","Tricia","Laverne","Olive","Alexis","Tasha","Silvia","Elvira","Casey","Delia","Sophie","Kate","Patti","Lorena","Kellie","Sonja","Lila","Lana","Darla","May","Mindy","Essie","Mandy","Lorene","Elsa","Josefina","Jeannie","Miranda","Dixie","Lucia","Marta","Faith","Lela","Johanna","Shari","Camille","Tami","Shawna","Elisa","Ebony","Melba","Ora","Nettie","Tabitha","Ollie","Jaime","Winifred","Kristie"],male:["James","John","Robert","Michael","William","David","Richard","Charles","Joseph","Thomas","Christopher","Daniel","Paul","Mark","Donald","George","Kenneth","Steven","Edward","Brian","Ronald","Anthony","Kevin","Jason","Matthew","Gary","Timothy","Jose","Larry","Jeffrey","Frank","Scott","Eric","Stephen","Andrew","Raymond","Gregory","Joshua","Jerry","Dennis","Walter","Patrick","Peter","Harold","Douglas","Henry","Carl","Arthur","Ryan","Roger","Joe","Juan","Jack","Albert","Jonathan","Justin","Terry","Gerald","Keith","Samuel","Willie","Ralph","Lawrence","Nicholas","Roy","Benjamin","Bruce","Brandon","Adam","Harry","Fred","Wayne","Billy","Steve","Louis","Jeremy","Aaron","Randy","Howard","Eugene","Carlos","Russell","Bobby","Victor","Martin","Ernest","Phillip","Todd","Jesse","Craig","Alan","Shawn","Clarence","Sean","Philip","Chris","Johnny","Earl","Jimmy","Antonio","Danny","Bryan","Tony","Luis","Mike","Stanley","Leonard","Nathan","Dale","Manuel","Rodney","Curtis","Norman","Allen","Marvin","Vincent","Glenn","Jeffery","Travis","Jeff","Chad","Jacob","Lee","Melvin","Alfred","Kyle","Francis","Bradley","Jesus","Herbert","Frederick","Ray","Joel","Edwin","Don","Eddie","Ricky","Troy","Randall","Barry","Alexander","Bernard","Mario","Leroy","Francisco","Marcus","Micheal","Theodore","Clifford","Miguel","Oscar","Jay","Jim","Tom","Calvin","Alex","Jon","Ronnie","Bill","Lloyd","Tommy","Leon","Derek","Warren","Darrell","Jerome","Floyd","Leo","Alvin","Tim","Wesley","Gordon","Dean","Greg","Jorge","Dustin","Pedro","Derrick","Dan","Lewis","Zachary","Corey","Herman","Maurice","Vernon","Roberto","Clyde","Glen","Hector","Shane","Ricardo","Sam","Rick","Lester","Brent","Ramon","Charlie","Tyler","Gilbert","Gene","Marc","Reginald","Ruben","Brett","Angel","Nathaniel","Rafael","Leslie","Edgar","Milton","Raul","Ben","Chester","Cecil","Duane","Franklin","Andre","Elmer","Brad","Gabriel","Ron","Mitchell","Roland","Arnold","Harvey","Jared","Adrian","Karl","Cory","Claude","Erik","Darryl","Jamie","Neil","Jessie","Christian","Javier","Fernando","Clinton","Ted","Mathew","Tyrone","Darren","Lonnie","Lance","Cody","Julio","Kelly","Kurt","Allan","Nelson","Guy","Clayton","Hugh","Max","Dwayne","Dwight","Armando","Felix","Jimmie","Everett","Jordan","Ian","Wallace","Ken","Bob","Jaime","Casey","Alfredo","Alberto","Dave","Ivan","Johnnie","Sidney","Byron","Julian","Isaac","Morris","Clifton","Willard","Daryl","Ross","Virgil","Andy","Marshall","Salvador","Perry","Kirk","Sergio","Marion","Tracy","Seth","Kent","Terrance","Rene","Eduardo","Terrence","Enrique","Freddie","Wade","Austin","Stuart","Fredrick","Arturo","Alejandro","Jackie","Joey","Nick","Luther","Wendell","Jeremiah","Evan","Julius","Dana","Donnie","Otis","Shannon","Trevor","Oliver","Luke","Homer","Gerard","Doug","Kenny","Hubert","Angelo","Shaun","Lyle","Matt","Lynn","Alfonso","Orlando","Rex","Carlton","Ernesto","Cameron","Neal","Pablo","Lorenzo","Omar","Wilbur","Blake","Grant","Horace","Roderick","Kerry","Abraham","Willis","Rickey","Jean","Ira","Andres","Cesar","Johnathan","Malcolm","Rudolph","Damon","Kelvin","Rudy","Preston","Alton","Archie","Marco","Wm","Pete","Randolph","Garry","Geoffrey","Jonathon","Felipe","Bennie","Gerardo","Ed","Dominic","Robin","Loren","Delbert","Colin","Guillermo","Earnest","Lucas","Benny","Noel","Spencer","Rodolfo","Myron","Edmund","Garrett","Salvatore","Cedric","Lowell","Gregg","Sherman","Wilson","Devin","Sylvester","Kim","Roosevelt","Israel","Jermaine","Forrest","Wilbert","Leland","Simon","Guadalupe","Clark","Irving","Carroll","Bryant","Owen","Rufus","Woodrow","Sammy","Kristopher","Mack","Levi","Marcos","Gustavo","Jake","Lionel","Marty","Taylor","Ellis","Dallas","Gilberto","Clint","Nicolas","Laurence","Ismael","Orville","Drew","Jody","Ervin","Dewey","Al","Wilfred","Josh","Hugo","Ignacio","Caleb","Tomas","Sheldon","Erick","Frankie","Stewart","Doyle","Darrel","Rogelio","Terence","Santiago","Alonzo","Elias","Bert","Elbert","Ramiro","Conrad","Pat","Noah","Grady","Phil","Cornelius","Lamar","Rolando","Clay","Percy","Dexter","Bradford","Merle","Darin","Amos","Terrell","Moses","Irvin","Saul","Roman","Darnell","Randal","Tommie","Timmy","Darrin","Winston","Brendan","Toby","Van","Abel","Dominick","Boyd","Courtney","Jan","Emilio","Elijah","Cary","Domingo","Santos","Aubrey","Emmett","Marlon","Emanuel","Jerald","Edmond"]},wn=Ld;var ya=["Abbott","Abernathy","Abshire","Adams","Altenwerth","Anderson","Ankunding","Armstrong","Auer","Aufderhar","Bahringer","Bailey","Balistreri","Barrows","Bartell","Bartoletti","Barton","Bashirian","Batz","Bauch","Baumbach","Bayer","Beahan","Beatty","Bechtelar","Becker","Bednar","Beer","Beier","Berge","Bergnaum","Bergstrom","Bernhard","Bernier","Bins","Blanda","Blick","Block","Bode","Boehm","Bogan","Bogisich","Borer","Bosco","Botsford","Boyer","Boyle","Bradtke","Brakus","Braun","Breitenberg","Brekke","Brown","Bruen","Buckridge","Carroll","Carter","Cartwright","Casper","Cassin","Champlin","Christiansen","Cole","Collier","Collins","Conn","Connelly","Conroy","Considine","Corkery","Cormier","Corwin","Cremin","Crist","Crona","Cronin","Crooks","Cruickshank","Cummerata","Cummings","Dach","D'Amore","Daniel","Dare","Daugherty","Davis","Deckow","Denesik","Dibbert","Dickens","Dicki","Dickinson","Dietrich","Donnelly","Dooley","Douglas","Doyle","DuBuque","Durgan","Ebert","Effertz","Emard","Emmerich","Erdman","Ernser","Fadel","Fahey","Farrell","Fay","Feeney","Feest","Feil","Ferry","Fisher","Flatley","Frami","Franecki","Friesen","Fritsch","Funk","Gaylord","Gerhold","Gerlach","Gibson","Gislason","Gleason","Gleichner","Glover","Goldner","Goodwin","Gorczany","Gottlieb","Goyette","Grady","Graham","Grant","Green","Greenfelder","Greenholt","Grimes","Gulgowski","Gusikowski","Gutkowski","Gutmann","Haag","Hackett","Hagenes","Hahn","Haley","Halvorson","Hamill","Hammes","Hand","Hane","Hansen","Harber","Harris","Hartmann","Harvey","Hauck","Hayes","Heaney","Heathcote","Hegmann","Heidenreich","Heller","Herman","Hermann","Hermiston","Herzog","Hessel","Hettinger","Hickle","Hilll","Hills","Hilpert","Hintz","Hirthe","Hodkiewicz","Hoeger","Homenick","Hoppe","Howe","Howell","Hudson","Huel","Huels","Hyatt","Jacobi","Jacobs","Jacobson","Jakubowski","Jaskolski","Jast","Jenkins","Jerde","Johns","Johnson","Johnston","Jones","Kassulke","Kautzer","Keebler","Keeling","Kemmer","Kerluke","Kertzmann","Kessler","Kiehn","Kihn","Kilback","King","Kirlin","Klein","Kling","Klocko","Koch","Koelpin","Koepp","Kohler","Konopelski","Koss","Kovacek","Kozey","Krajcik","Kreiger","Kris","Kshlerin","Kub","Kuhic","Kuhlman","Kuhn","Kulas","Kunde","Kunze","Kuphal","Kutch","Kuvalis","Labadie","Lakin","Lang","Langosh","Langworth","Larkin","Larson","Leannon","Lebsack","Ledner","Leffler","Legros","Lehner","Lemke","Lesch","Leuschke","Lind","Lindgren","Littel","Little","Lockman","Lowe","Lubowitz","Lueilwitz","Luettgen","Lynch","Macejkovic","MacGyver","Maggio","Mann","Mante","Marks","Marquardt","Marvin","Mayer","Mayert","McClure","McCullough","McDermott","McGlynn","McKenzie","McLaughlin","Medhurst","Mertz","Metz","Miller","Mills","Mitchell","Moen","Mohr","Monahan","Moore","Morar","Morissette","Mosciski","Mraz","Mueller","Muller","Murazik","Murphy","Murray","Nader","Nicolas","Nienow","Nikolaus","Nitzsche","Nolan","Oberbrunner","O'Connell","O'Conner","O'Hara","O'Keefe","O'Kon","Okuneva","Olson","Ondricka","O'Reilly","Orn","Ortiz","Osinski","Pacocha","Padberg","Pagac","Parisian","Parker","Paucek","Pfannerstill","Pfeffer","Pollich","Pouros","Powlowski","Predovic","Price","Prohaska","Prosacco","Purdy","Quigley","Quitzon","Rath","Ratke","Rau","Raynor","Reichel","Reichert","Reilly","Reinger","Rempel","Renner","Reynolds","Rice","Rippin","Ritchie","Robel","Roberts","Rodriguez","Rogahn","Rohan","Rolfson","Romaguera","Roob","Rosenbaum","Rowe","Ruecker","Runolfsdottir","Runolfsson","Runte","Russel","Rutherford","Ryan","Sanford","Satterfield","Sauer","Sawayn","Schaden","Schaefer","Schamberger","Schiller","Schimmel","Schinner","Schmeler","Schmidt","Schmitt","Schneider","Schoen","Schowalter","Schroeder","Schulist","Schultz","Schumm","Schuppe","Schuster","Senger","Shanahan","Shields","Simonis","Sipes","Skiles","Smith","Smitham","Spencer","Spinka","Sporer","Stamm","Stanton","Stark","Stehr","Steuber","Stiedemann","Stokes","Stoltenberg","Stracke","Streich","Stroman","Strosin","Swaniawski","Swift","Terry","Thiel","Thompson","Tillman","Torp","Torphy","Towne","Toy","Trantow","Tremblay","Treutel","Tromp","Turcotte","Turner","Ullrich","Upton","Vandervort","Veum","Volkman","Von","VonRueden","Waelchi","Walker","Walsh","Walter","Ward","Waters","Watsica","Weber","Wehner","Weimann","Weissnat","Welch","West","White","Wiegand","Wilderman","Wilkinson","Will","Williamson","Willms","Windler","Wintheiser","Wisoky","Wisozk","Witting","Wiza","Wolf","Wolff","Wuckert","Wunsch","Wyman","Yost","Yundt","Zboncak","Zemlak","Ziemann","Zieme","Zulauf"],Ud={general:ya,female:ya,male:ya},Sn=Ud;var zd={binary:["Female","Male"],pool:["Asexual","Female to male trans man","Female to male transgender man","Female to male transsexual man","F2M","Gender neutral","Hermaphrodite","Intersex man","Intersex person","Intersex woman","Male to female trans woman","Male to female transgender woman","Male to female transsexual woman","Man","M2F","Polygender","T* man","T* woman","Two* person","Two-spirit person","Woman","Agender","Androgyne","Androgynes","Androgynous","Bigender","Cis","Cis Female","Cis Male","Cis Man","Cis Woman","Cisgender","Cisgender Female","Cisgender Male","Cisgender Man","Cisgender Woman","Female to Male","FTM","Gender Fluid","Gender Nonconforming","Gender Questioning","Gender Variant","Genderqueer","Intersex","Male to Female","MTF","Neither","Neutrois","Non-binary","Other","Pangender","Trans","Trans Female","Trans Male","Trans Man","Trans Person","Trans*Female","Trans*Male","Trans*Man","Trans*Person","Trans*Woman","Transexual","Transexual Female","Transexual Male","Transexual Man","Transexual Person","Transexual Woman","Transgender Female","Transgender Person","Transmasculine","Two-spirit"]},An=zd;var Vd={descriptor:["Lead","Senior","Direct","Corporate","Dynamic","Future","Product","National","Regional","District","Central","Global","Customer","Investor","Dynamic","International","Legacy","Forward","Internal","Human","Chief","Principal"],level:["Solutions","Program","Brand","Security","Research","Marketing","Directives","Implementation","Integration","Functionality","Response","Paradigm","Tactics","Identity","Markets","Group","Division","Applications","Optimization","Operations","Infrastructure","Intranet","Communications","Web","Branding","Quality","Assurance","Mobility","Accounts","Data","Creative","Configuration","Accountability","Interactions","Factors","Usability","Metrics"],job:["Supervisor","Associate","Executive","Liaison","Officer","Manager","Engineer","Specialist","Director","Coordinator","Administrator","Architect","Analyst","Designer","Planner","Orchestrator","Technician","Developer","Producer","Consultant","Assistant","Facilitator","Agent","Representative","Strategist"]},_n=Vd;var ba=["Jr.","Sr.","I","II","III","IV","V","MD","DDS","PhD","DVM"],Fd={gender:An,firstName:wn,lastName:Sn,title:_n,suffix:{general:ba,female:ba,male:ba},prefix:{general:["Mr.","Mrs.","Ms.","Miss","Dr."],female:["Mrs.","Ms.","Miss"],male:["Mr.","Dr."]},templates:["#{prefix} #{first_name} #{last_name}","#{first_name} #{last_name} #{suffix}","#{first_name} #{last_name}","#{first_name} #{last_name}","#{male_first_name} #{last_name}","#{female_first_name} #{last_name}"]},En=Fd;var xn=["abandoned","able","absolute","adorable","adventurous","academic","acceptable","acclaimed","accomplished","accurate","aching","acidic","acrobatic","active","actual","adept","admirable","admired","adolescent","adorable","adored","advanced","afraid","affectionate","aged","aggravating","aggressive","agile","agitated","agonizing","agreeable","ajar","alarmed","alarming","alert","alienated","alive","all","altruistic","amazing","ambitious","ample","amused","amusing","anchored","ancient","angelic","angry","anguished","animated","annual","another","antique","anxious","any","apprehensive","appropriate","apt","arctic","arid","aromatic","artistic","ashamed","assured","astonishing","athletic","attached","attentive","attractive","austere","authentic","authorized","automatic","avaricious","average","aware","awesome","awful","awkward","babyish","bad","back","baggy","bare","barren","basic","beautiful","belated","beloved","beneficial","better","best","bewitched","big","big-hearted","biodegradable","bite-sized","bitter","black","black-and-white","bland","blank","blaring","bleak","blind","blissful","blond","blue","blushing","bogus","boiling","bold","bony","boring","bossy","both","bouncy","bountiful","bowed","brave","breakable","brief","bright","brilliant","brisk","broken","bronze","brown","bruised","bubbly","bulky","bumpy","buoyant","burdensome","burly","bustling","busy","buttery","buzzing","calculating","calm","candid","canine","capital","carefree","careful","careless","caring","cautious","cavernous","celebrated","charming","cheap","cheerful","cheery","chief","chilly","chubby","circular","classic","clean","clear","clear-cut","clever","close","closed","cloudy","clueless","clumsy","cluttered","coarse","cold","colorful","colorless","colossal","comfortable","common","compassionate","competent","complete","complex","complicated","composed","concerned","concrete","confused","conscious","considerate","constant","content","conventional","cooked","cool","cooperative","coordinated","corny","corrupt","costly","courageous","courteous","crafty","crazy","creamy","creative","creepy","criminal","crisp","critical","crooked","crowded","cruel","crushing","cuddly","cultivated","cultured","cumbersome","curly","curvy","cute","cylindrical","damaged","damp","dangerous","dapper","daring","darling","dark","dazzling","dead","deadly","deafening","dear","dearest","decent","decimal","decisive","deep","defenseless","defensive","defiant","deficient","definite","definitive","delayed","delectable","delicious","delightful","delirious","demanding","dense","dental","dependable","dependent","descriptive","deserted","detailed","determined","devoted","different","difficult","digital","diligent","dim","dimpled","dimwitted","direct","disastrous","discrete","disfigured","disgusting","disloyal","dismal","distant","downright","dreary","dirty","disguised","dishonest","dismal","distant","distinct","distorted","dizzy","dopey","doting","double","downright","drab","drafty","dramatic","dreary","droopy","dry","dual","dull","dutiful","each","eager","earnest","early","easy","easy-going","ecstatic","edible","educated","elaborate","elastic","elated","elderly","electric","elegant","elementary","elliptical","embarrassed","embellished","eminent","emotional","empty","enchanted","enchanting","energetic","enlightened","enormous","enraged","entire","envious","equal","equatorial","essential","esteemed","ethical","euphoric","even","evergreen","everlasting","every","evil","exalted","excellent","exemplary","exhausted","excitable","excited","exciting","exotic","expensive","experienced","expert","extraneous","extroverted","extra-large","extra-small","fabulous","failing","faint","fair","faithful","fake","false","familiar","famous","fancy","fantastic","far","faraway","far-flung","far-off","fast","fat","fatal","fatherly","favorable","favorite","fearful","fearless","feisty","feline","female","feminine","few","fickle","filthy","fine","finished","firm","first","firsthand","fitting","fixed","flaky","flamboyant","flashy","flat","flawed","flawless","flickering","flimsy","flippant","flowery","fluffy","fluid","flustered","focused","fond","foolhardy","foolish","forceful","forked","formal","forsaken","forthright","fortunate","fragrant","frail","frank","frayed","free","french","fresh","frequent","friendly","frightened","frightening","frigid","frilly","frizzy","frivolous","front","frosty","frozen","frugal","fruitful","full","fumbling","functional","funny","fussy","fuzzy","gargantuan","gaseous","general","generous","gentle","genuine","giant","giddy","gigantic","gifted","giving","glamorous","glaring","glass","gleaming","gleeful","glistening","glittering","gloomy","glorious","glossy","glum","golden","good","good-natured","gorgeous","graceful","gracious","grand","grandiose","granular","grateful","grave","gray","great","greedy","green","gregarious","grim","grimy","gripping","grizzled","gross","grotesque","grouchy","grounded","growing","growling","grown","grubby","gruesome","grumpy","guilty","gullible","gummy","hairy","half","handmade","handsome","handy","happy","happy-go-lucky","hard","hard-to-find","harmful","harmless","harmonious","harsh","hasty","hateful","haunting","healthy","heartfelt","hearty","heavenly","heavy","hefty","helpful","helpless","hidden","hideous","high","high-level","hilarious","hoarse","hollow","homely","honest","honorable","honored","hopeful","horrible","hospitable","hot","huge","humble","humiliating","humming","humongous","hungry","hurtful","husky","icky","icy","ideal","idealistic","identical","idle","idiotic","idolized","ignorant","ill","illegal","ill-fated","ill-informed","illiterate","illustrious","imaginary","imaginative","immaculate","immaterial","immediate","immense","impassioned","impeccable","impartial","imperfect","imperturbable","impish","impolite","important","impossible","impractical","impressionable","impressive","improbable","impure","inborn","incomparable","incompatible","incomplete","inconsequential","incredible","indelible","inexperienced","indolent","infamous","infantile","infatuated","inferior","infinite","informal","innocent","insecure","insidious","insignificant","insistent","instructive","insubstantial","intelligent","intent","intentional","interesting","internal","international","intrepid","ironclad","irresponsible","irritating","itchy","jaded","jagged","jam-packed","jaunty","jealous","jittery","joint","jolly","jovial","joyful","joyous","jubilant","judicious","juicy","jumbo","junior","jumpy","juvenile","kaleidoscopic","keen","key","kind","kindhearted","kindly","klutzy","knobby","knotty","knowledgeable","knowing","known","kooky","kosher","lame","lanky","large","last","lasting","late","lavish","lawful","lazy","leading","lean","leafy","left","legal","legitimate","light","lighthearted","likable","likely","limited","limp","limping","linear","lined","liquid","little","live","lively","livid","loathsome","lone","lonely","long","long-term","loose","lopsided","lost","loud","lovable","lovely","loving","low","loyal","lucky","lumbering","luminous","lumpy","lustrous","luxurious","mad","made-up","magnificent","majestic","major","male","mammoth","married","marvelous","masculine","massive","mature","meager","mealy","mean","measly","meaty","medical","mediocre","medium","meek","mellow","melodic","memorable","menacing","merry","messy","metallic","mild","milky","mindless","miniature","minor","minty","miserable","miserly","misguided","misty","mixed","modern","modest","moist","monstrous","monthly","monumental","moral","mortified","motherly","motionless","mountainous","muddy","muffled","multicolored","mundane","murky","mushy","musty","muted","mysterious","naive","narrow","nasty","natural","naughty","nautical","near","neat","necessary","needy","negative","neglected","negligible","neighboring","nervous","new","next","nice","nifty","nimble","nippy","nocturnal","noisy","nonstop","normal","notable","noted","noteworthy","novel","noxious","numb","nutritious","nutty","obedient","obese","oblong","oily","oblong","obvious","occasional","odd","oddball","offbeat","offensive","official","old","old-fashioned","only","open","optimal","optimistic","opulent","orange","orderly","organic","ornate","ornery","ordinary","original","other","our","outlying","outgoing","outlandish","outrageous","outstanding","oval","overcooked","overdue","overjoyed","overlooked","palatable","pale","paltry","parallel","parched","partial","passionate","past","pastel","peaceful","peppery","perfect","perfumed","periodic","perky","personal","pertinent","pesky","pessimistic","petty","phony","physical","piercing","pink","pitiful","plain","plaintive","plastic","playful","pleasant","pleased","pleasing","plump","plush","polished","polite","political","pointed","pointless","poised","poor","popular","portly","posh","positive","possible","potable","powerful","powerless","practical","precious","present","prestigious","pretty","precious","previous","pricey","prickly","primary","prime","pristine","private","prize","probable","productive","profitable","profuse","proper","proud","prudent","punctual","pungent","puny","pure","purple","pushy","putrid","puzzled","puzzling","quaint","qualified","quarrelsome","quarterly","queasy","querulous","questionable","quick","quick-witted","quiet","quintessential","quirky","quixotic","quizzical","radiant","ragged","rapid","rare","rash","raw","recent","reckless","rectangular","ready","real","realistic","reasonable","red","reflecting","regal","regular","reliable","relieved","remarkable","remorseful","remote","repentant","required","respectful","responsible","repulsive","revolving","rewarding","rich","rigid","right","ringed","ripe","roasted","robust","rosy","rotating","rotten","rough","round","rowdy","royal","rubbery","rundown","ruddy","rude","runny","rural","rusty","sad","safe","salty","same","sandy","sane","sarcastic","sardonic","satisfied","scaly","scarce","scared","scary","scented","scholarly","scientific","scornful","scratchy","scrawny","second","secondary","second-hand","secret","self-assured","self-reliant","selfish","sentimental","separate","serene","serious","serpentine","several","severe","shabby","shadowy","shady","shallow","shameful","shameless","sharp","shimmering","shiny","shocked","shocking","shoddy","short","short-term","showy","shrill","shy","sick","silent","silky","silly","silver","similar","simple","simplistic","sinful","single","sizzling","skeletal","skinny","sleepy","slight","slim","slimy","slippery","slow","slushy","small","smart","smoggy","smooth","smug","snappy","snarling","sneaky","sniveling","snoopy","sociable","soft","soggy","solid","somber","some","spherical","sophisticated","sore","sorrowful","soulful","soupy","sour","spanish","sparkling","sparse","specific","spectacular","speedy","spicy","spiffy","spirited","spiteful","splendid","spotless","spotted","spry","square","squeaky","squiggly","stable","staid","stained","stale","standard","starchy","stark","starry","steep","sticky","stiff","stimulating","stingy","stormy","straight","strange","steel","strict","strident","striking","striped","strong","studious","stunning","stupendous","stupid","sturdy","stylish","subdued","submissive","substantial","subtle","suburban","sudden","sugary","sunny","super","superb","superficial","superior","supportive","sure-footed","surprised","suspicious","svelte","sweaty","sweet","sweltering","swift","sympathetic","tall","talkative","tame","tan","tangible","tart","tasty","tattered","taut","tedious","teeming","tempting","tender","tense","tepid","terrible","terrific","testy","thankful","that","these","thick","thin","third","thirsty","this","thorough","thorny","those","thoughtful","threadbare","thrifty","thunderous","tidy","tight","timely","tinted","tiny","tired","torn","total","tough","traumatic","treasured","tremendous","tragic","trained","tremendous","triangular","tricky","trifling","trim","trivial","troubled","true","trusting","trustworthy","trusty","truthful","tubby","turbulent","twin","ugly","ultimate","unacceptable","unaware","uncomfortable","uncommon","unconscious","understated","unequaled","uneven","unfinished","unfit","unfolded","unfortunate","unhappy","unhealthy","uniform","unimportant","unique","united","unkempt","unknown","unlawful","unlined","unlucky","unnatural","unpleasant","unrealistic","unripe","unruly","unselfish","unsightly","unsteady","unsung","untidy","untimely","untried","untrue","unused","unusual","unwelcome","unwieldy","unwilling","unwitting","unwritten","upbeat","upright","upset","urban","usable","used","useful","useless","utilized","utter","vacant","vague","vain","valid","valuable","vapid","variable","vast","velvety","venerated","vengeful","verifiable","vibrant","vicious","victorious","vigilant","vigorous","villainous","violet","violent","virtual","virtuous","visible","vital","vivacious","vivid","voluminous","wan","warlike","warm","warmhearted","warped","wary","wasteful","watchful","waterlogged","watery","wavy","wealthy","weak","weary","webbed","wee","weekly","weepy","weighty","weird","welcome","well-documented","well-groomed","well-informed","well-lit","well-made","well-off","well-to-do","well-worn","wet","which","whimsical","whirlwind","whispered","white","whole","whopping","wicked","wide","wide-eyed","wiggly","wild","willing","wilted","winding","windy","winged","wiry","wise","witty","wobbly","woeful","wonderful","wooden","woozy","wordy","worldly","worn","worried","worrisome","worse","worst","worthless","worthwhile","worthy","wrathful","wretched","writhing","wrong","wry","yawning","yearly","yellow","yellowish","young","youthful","yummy","zany","zealous","zesty","zigzag"];var On=["abnormally","absentmindedly","accidentally","acidly","actually","adventurously","afterwards","almost","always","angrily","annually","anxiously","arrogantly","awkwardly","badly","bashfully","beautifully","bitterly","bleakly","blindly","blissfully","boastfully","boldly","bravely","briefly","brightly","briskly","broadly","busily","calmly","carefully","carelessly","cautiously","certainly","cheerfully","clearly","cleverly","closely","coaxingly","colorfully","commonly","continually","coolly","correctly","courageously","crossly","cruelly","curiously","daily","daintily","dearly","deceivingly","deeply","defiantly","deliberately","delightfully","diligently","dimly","doubtfully","dreamily","easily","elegantly","energetically","enormously","enthusiastically","equally","especially","even","evenly","eventually","exactly","excitedly","extremely","fairly","faithfully","famously","far","fast","fatally","ferociously","fervently","fiercely","fondly","foolishly","fortunately","frankly","frantically","freely","frenetically","frightfully","fully","furiously","generally","generously","gently","gladly","gleefully","gracefully","gratefully","greatly","greedily","happily","hastily","healthily","heavily","helpfully","helplessly","highly","honestly","hopelessly","hourly","hungrily","immediately","innocently","inquisitively","instantly","intensely","intently","interestingly","inwardly","irritably","jaggedly","jealously","joshingly","jovially","joyfully","joyously","jubilantly","judgementally","justly","keenly","kiddingly","kindheartedly","kindly","kissingly","knavishly","knottily","knowingly","knowledgeably","kookily","lazily","less","lightly","likely","limply","lively","loftily","longingly","loosely","loudly","lovingly","loyally","madly","majestically","meaningfully","mechanically","merrily","miserably","mockingly","monthly","more","mortally","mostly","mysteriously","naturally","nearly","neatly","needily","nervously","never","nicely","noisily","not","obediently","obnoxiously","oddly","offensively","officially","often","only","openly","optimistically","overconfidently","owlishly","painfully","partially","patiently","perfectly","physically","playfully","politely","poorly","positively","potentially","powerfully","promptly","properly","punctually","quaintly","quarrelsomely","queasily","queerly","questionably","questioningly","quicker","quickly","quietly","quirkily","quizzically","rapidly","rarely","readily","really","reassuringly","recklessly","regularly","reluctantly","repeatedly","reproachfully","restfully","righteously","rightfully","rigidly","roughly","rudely","sadly","safely","scarcely","scarily","searchingly","sedately","seemingly","seldom","selfishly","separately","seriously","shakily","sharply","sheepishly","shrilly","shyly","silently","sleepily","slowly","smoothly","softly","solemnly","solidly","sometimes","soon","speedily","stealthily","sternly","strictly","successfully","suddenly","surprisingly","suspiciously","sweetly","swiftly","sympathetically","tenderly","tensely","terribly","thankfully","thoroughly","thoughtfully","tightly","tomorrow","too","tremendously","triumphantly","truly","truthfully","ultimately","unabashedly","unaccountably","unbearably","unethically","unexpectedly","unfortunately","unimpressively","unnaturally","unnecessarily","upbeat","upliftingly","upright","upside-down","upward","upwardly","urgently","usefully","uselessly","usually","utterly","vacantly","vaguely","vainly","valiantly","vastly","verbally","very","viciously","victoriously","violently","vivaciously","voluntarily","warmly","weakly","wearily","well","wetly","wholly","wildly","willfully","wisely","woefully","wonderfully","worriedly","wrongly","yawningly","yearly","yearningly","yesterday","yieldingly","youthfully"];var Pn=["after","after all","although","and","as","as a result","as if","as long as","as much as","as soon as","as though","because","before","but","consequently","even","even if","even though","finally","for","for example","furthermore","hence","however","if","if only","if then","if when","in addition","in fact","in order that","inasmuch","incidentally","indeed","instead","just as","lest","likewise","meanwhile","nor","now","now since","now that","now when","once","or","provided","provided that","rather than","since","so","so that","supposing","that","though","until","whenever","whereas","wherever","which","who","yet"];var In=["yuck","oh","phooey","blah","boo","whoa","yowza","huzzah","boo hoo","fooey","geez","pfft","ew","ah","yum","brr","hm","yahoo","aha","woot","drat","gah","meh","psst","aw","ugh","yippee","eek","gee","bah","gadzooks","duh","ha","mmm","tsk tsk","ouch","phew","ack","uh-huh","gosh","hmph","pish","zowie","er","ick","oof","um"];var Nn=["ATM","CD","SUV","TV","aardvark","abacus","abbey","abbreviation","abdomen","ability","abnormality","abolishment","abortion","abrogation","absence","abundance","abuse","academics","academy","accelerant","accelerator","accent","acceptance","access","accessory","accident","accommodation","accompanist","accomplishment","accord","accordance","accordion","account","accountability","accountant","accounting","accuracy","accusation","acetate","achievement","achiever","acid","acknowledgment","acorn","acoustics","acquaintance","acquisition","acre","acrylic","act","action","activation","activist","activity","actor","actress","acupuncture","ad","adaptation","adapter","addiction","addition","address","adjective","adjustment","admin","administration","administrator","admire","admission","adobe","adoption","adrenalin","adrenaline","adult","adulthood","advance","advancement","advantage","advent","adverb","advertisement","advertising","advice","adviser","advocacy","advocate","affair","affect","affidavit","affiliate","affinity","afoul","afterlife","aftermath","afternoon","aftershave","aftershock","afterthought","age","agency","agenda","agent","aggradation","aggression","aglet","agony","agreement","agriculture","aid","aide","aim","air","airbag","airbus","aircraft","airfare","airfield","airforce","airline","airmail","airman","airplane","airport","airship","airspace","alarm","alb","albatross","album","alcohol","alcove","alder","ale","alert","alfalfa","algebra","algorithm","alias","alibi","alien","allegation","allergist","alley","alliance","alligator","allocation","allowance","alloy","alluvium","almanac","almighty","almond","alpaca","alpenglow","alpenhorn","alpha","alphabet","altar","alteration","alternative","altitude","alto","aluminium","aluminum","amazement","amazon","ambassador","amber","ambience","ambiguity","ambition","ambulance","amendment","amenity","ammunition","amnesty","amount","amusement","anagram","analgesia","analog","analogue","analogy","analysis","analyst","analytics","anarchist","anarchy","anatomy","ancestor","anchovy","android","anesthesiologist","anesthesiology","angel","anger","angina","angiosperm","angle","angora","angstrom","anguish","animal","anime","anise","ankle","anklet","anniversary","announcement","annual","anorak","answer","ant","anteater","antecedent","antechamber","antelope","antennae","anterior","anthropology","antibody","anticipation","anticodon","antigen","antique","antiquity","antler","antling","anxiety","anybody","anyone","anything","anywhere","apartment","ape","aperitif","apology","app","apparatus","apparel","appeal","appearance","appellation","appendix","appetiser","appetite","appetizer","applause","apple","applewood","appliance","application","appointment","appreciation","apprehension","approach","appropriation","approval","apricot","apron","apse","aquarium","aquifer","arcade","arch","arch-rival","archaeologist","archaeology","archeology","archer","architect","architecture","archives","area","arena","argument","arithmetic","ark","arm","arm-rest","armadillo","armament","armchair","armoire","armor","armour","armpit","armrest","army","arrangement","array","arrest","arrival","arrogance","arrow","art","artery","arthur","artichoke","article","artifact","artificer","artist","ascend","ascent","ascot","ash","ashram","ashtray","aside","asparagus","aspect","asphalt","aspic","ass","assassination","assault","assembly","assertion","assessment","asset","assignment","assist","assistance","assistant","associate","association","assumption","assurance","asterisk","astrakhan","astrolabe","astrologer","astrology","astronomy","asymmetry","atelier","atheist","athlete","athletics","atmosphere","atom","atrium","attachment","attack","attacker","attainment","attempt","attendance","attendant","attention","attenuation","attic","attitude","attorney","attraction","attribute","auction","audience","audit","auditorium","aunt","authentication","authenticity","author","authorisation","authority","authorization","auto","autoimmunity","automation","automaton","autumn","availability","avalanche","avenue","average","avocado","award","awareness","awe","axis","azimuth","babe","baboon","babushka","baby","bachelor","back","back-up","backbone","backburn","backdrop","background","backpack","backup","backyard","bacon","bacterium","badge","badger","bafflement","bag","bagel","baggage","baggie","baggy","bagpipe","bail","bait","bake","baker","bakery","bakeware","balaclava","balalaika","balance","balcony","ball","ballet","balloon","balloonist","ballot","ballpark","bamboo","ban","banana","band","bandana","bandanna","bandolier","bandwidth","bangle","banjo","bank","bankbook","banker","banking","bankruptcy","banner","banquette","banyan","baobab","bar","barbecue","barbeque","barber","barbiturate","bargain","barge","baritone","barium","bark","barley","barn","barometer","barracks","barrage","barrel","barrier","barstool","bartender","base","baseball","baseboard","baseline","basement","basics","basil","basin","basis","basket","basketball","bass","bassinet","bassoon","bat","bath","bather","bathhouse","bathrobe","bathroom","bathtub","battalion","batter","battery","batting","battle","battleship","bay","bayou","beach","bead","beak","beam","bean","beancurd","beanie","beanstalk","bear","beard","beast","beastie","beat","beating","beauty","beaver","beck","bed","bedrock","bedroom","bee","beech","beef","beer","beet","beetle","beggar","beginner","beginning","begonia","behalf","behavior","behaviour","beheading","behest","behold","being","belfry","belief","believer","bell","belligerency","bellows","belly","belt","bench","bend","beneficiary","benefit","beret","berry","best-seller","bestseller","bet","beverage","beyond","bias","bibliography","bicycle","bid","bidder","bidding","bidet","bifocals","bijou","bike","bikini","bill","billboard","billing","billion","bin","binoculars","biology","biopsy","biosphere","biplane","birch","bird","bird-watcher","birdbath","birdcage","birdhouse","birth","birthday","biscuit","bit","bite","bitten","bitter","black","blackberry","blackbird","blackboard","blackfish","blackness","bladder","blade","blame","blank","blanket","blast","blazer","blend","blessing","blight","blind","blinker","blister","blizzard","block","blocker","blog","blogger","blood","bloodflow","bloom","bloomer","blossom","blouse","blow","blowgun","blowhole","blue","blueberry","blush","boar","board","boat","boatload","boatyard","bob","bobcat","body","bog","bolero","bolt","bomb","bomber","bombing","bond","bonding","bondsman","bone","bonfire","bongo","bonnet","bonsai","bonus","boogeyman","book","bookcase","bookend","booking","booklet","bookmark","boolean","boom","boon","boost","booster","boot","bootee","bootie","booty","border","bore","borrower","borrowing","bosom","boss","botany","bother","bottle","bottling","bottom","bottom-line","boudoir","bough","boulder","boulevard","boundary","bouquet","bourgeoisie","bout","boutique","bow","bower","bowl","bowler","bowling","bowtie","box","boxer","boxspring","boy","boycott","boyfriend","boyhood","boysenberry","bra","brace","bracelet","bracket","brain","brake","bran","branch","brand","brandy","brass","brassiere","bratwurst","bread","breadcrumb","breadfruit","break","breakdown","breakfast","breakpoint","breakthrough","breast","breastplate","breath","breeze","brewer","bribery","brick","bricklaying","bride","bridge","brief","briefing","briefly","briefs","brilliant","brink","brisket","broad","broadcast","broccoli","brochure","brocolli","broiler","broker","bronchitis","bronco","bronze","brooch","brood","brook","broom","brother","brother-in-law","brow","brown","brownie","browser","browsing","brunch","brush","brushfire","brushing","bubble","buck","bucket","buckle","buckwheat","bud","buddy","budget","buffalo","buffer","buffet","bug","buggy","bugle","builder","building","bulb","bulk","bull","bull-fighter","bulldozer","bullet","bump","bumper","bun","bunch","bungalow","bunghole","bunkhouse","burden","bureau","burglar","burial","burlesque","burn","burn-out","burning","burrito","burro","burrow","burst","bus","bush","business","businessman","bust","bustle","butane","butcher","butler","butter","butterfly","button","buy","buyer","buying","buzz","buzzard","c-clamp","cabana","cabbage","cabin","cabinet","cable","caboose","cacao","cactus","caddy","cadet","cafe","caffeine","caftan","cage","cake","calcification","calculation","calculator","calculus","calendar","calf","caliber","calibre","calico","call","calm","calorie","camel","cameo","camera","camp","campaign","campaigning","campanile","camper","campus","can","canal","cancer","candelabra","candidacy","candidate","candle","candy","cane","cannibal","cannon","canoe","canon","canopy","cantaloupe","canteen","canvas","cap","capability","capacity","cape","caper","capital","capitalism","capitulation","capon","cappelletti","cappuccino","captain","caption","captor","car","carabao","caramel","caravan","carbohydrate","carbon","carboxyl","card","cardboard","cardigan","care","career","cargo","caribou","carload","carnation","carnival","carol","carotene","carp","carpenter","carpet","carpeting","carport","carriage","carrier","carrot","carry","cart","cartel","carter","cartilage","cartload","cartoon","cartridge","carving","cascade","case","casement","cash","cashew","cashier","casino","casket","cassava","casserole","cassock","cast","castanet","castle","casualty","cat","catacomb","catalogue","catalysis","catalyst","catamaran","catastrophe","catch","catcher","category","caterpillar","cathedral","cation","catsup","cattle","cauliflower","causal","cause","causeway","caution","cave","caviar","cayenne","ceiling","celebration","celebrity","celeriac","celery","cell","cellar","cello","celsius","cement","cemetery","cenotaph","census","cent","center","centimeter","centre","centurion","century","cephalopod","ceramic","ceramics","cereal","ceremony","certainty","certificate","certification","cesspool","chafe","chain","chainstay","chair","chairlift","chairman","chairperson","chaise","chalet","chalice","chalk","challenge","chamber","champagne","champion","championship","chance","chandelier","change","channel","chaos","chap","chapel","chaplain","chapter","character","characteristic","characterization","chard","charge","charger","charity","charlatan","charm","charset","chart","charter","chasm","chassis","chastity","chasuble","chateau","chatter","chauffeur","chauvinist","check","checkbook","checking","checkout","checkroom","cheddar","cheek","cheer","cheese","cheesecake","cheetah","chef","chem","chemical","chemistry","chemotaxis","cheque","cherry","chess","chest","chestnut","chick","chicken","chicory","chief","chiffonier","child","childbirth","childhood","chili","chill","chime","chimpanzee","chin","chinchilla","chino","chip","chipmunk","chit-chat","chivalry","chive","chives","chocolate","choice","choir","choker","cholesterol","choosing","chop","chops","chopstick","chopsticks","chord","chorus","chow","chowder","chrome","chromolithograph","chronicle","chronograph","chronometer","chrysalis","chub","chuck","chug","church","churn","chutney","cicada","cigarette","cilantro","cinder","cinema","cinnamon","circadian","circle","circuit","circulation","circumference","circumstance","cirrhosis","cirrus","citizen","citizenship","citron","citrus","city","civilian","civilisation","civilization","claim","clam","clamp","clan","clank","clapboard","clarification","clarinet","clarity","clasp","class","classic","classification","classmate","classroom","clause","clave","clavicle","clavier","claw","clay","cleaner","clearance","clearing","cleat","cleavage","clef","cleft","clergyman","cleric","clerk","click","client","cliff","climate","climb","clinic","clip","clipboard","clipper","cloak","cloakroom","clock","clockwork","clogs","cloister","clone","close","closet","closing","closure","cloth","clothes","clothing","cloud","cloudburst","clove","clover","cloves","club","clue","cluster","clutch","co-producer","coach","coal","coalition","coast","coaster","coat","cob","cobbler","cobweb","cock","cockpit","cockroach","cocktail","cocoa","coconut","cod","code","codepage","codling","codon","codpiece","coevolution","cofactor","coffee","coffin","cohesion","cohort","coil","coin","coincidence","coinsurance","coke","cold","coleslaw","coliseum","collaboration","collagen","collapse","collar","collard","collateral","colleague","collection","collectivisation","collectivization","collector","college","collision","colloquy","colon","colonial","colonialism","colonisation","colonization","colony","color","colorlessness","colt","column","columnist","comb","combat","combination","combine","comeback","comedy","comestible","comfort","comfortable","comic","comics","comma","command","commander","commandment","comment","commerce","commercial","commission","commitment","committee","commodity","common","commonsense","commotion","communicant","communication","communion","communist","community","commuter","company","comparison","compass","compassion","compassionate","compensation","competence","competition","competitor","complaint","complement","completion","complex","complexity","compliance","complication","complicity","compliment","component","comportment","composer","composite","composition","compost","comprehension","compress","compromise","comptroller","compulsion","computer","comradeship","con","concentrate","concentration","concept","conception","concern","concert","conclusion","concrete","condition","conditioner","condominium","condor","conduct","conductor","cone","confectionery","conference","confidence","confidentiality","configuration","confirmation","conflict","conformation","confusion","conga","congo","congregation","congress","congressman","congressperson","conifer","connection","connotation","conscience","consciousness","consensus","consent","consequence","conservation","conservative","consideration","consignment","consist","consistency","console","consonant","conspiracy","conspirator","constant","constellation","constitution","constraint","construction","consul","consulate","consulting","consumer","consumption","contact","contact lens","contagion","container","content","contention","contest","context","continent","contingency","continuity","contour","contract","contractor","contrail","contrary","contrast","contribution","contributor","control","controller","controversy","convection","convenience","convention","conversation","conversion","convert","convertible","conviction","cook","cookbook","cookie","cooking","coonskin","cooperation","coordination","coordinator","cop","cop-out","cope","copper","copy","copying","copyright","copywriter","coral","cord","corduroy","core","cork","cormorant","corn","corner","cornerstone","cornet","cornflakes","cornmeal","corporal","corporation","corporatism","corps","corral","correspondence","correspondent","corridor","corruption","corsage","cosset","cost","costume","cot","cottage","cotton","couch","cougar","cough","council","councilman","councilor","councilperson","counsel","counseling","counselling","counsellor","counselor","count","counter","counter-force","counterpart","counterterrorism","countess","country","countryside","county","couple","coupon","courage","course","court","courthouse","courtroom","cousin","covariate","cover","coverage","coverall","cow","cowbell","cowboy","coyote","crab","crack","cracker","crackers","cradle","craft","craftsman","cranberry","crane","cranky","crap","crash","crate","cravat","craw","crawdad","crayfish","crayon","crazy","cream","creation","creationism","creationist","creative","creativity","creator","creature","creche","credential","credenza","credibility","credit","creditor","creek","creme brulee","crepe","crest","crew","crewman","crewmate","crewmember","crewmen","cria","crib","cribbage","cricket","cricketer","crime","criminal","crinoline","crisis","crisp","criteria","criterion","critic","criticism","crocodile","crocus","croissant","crook","crop","cross","cross-contamination","cross-stitch","crotch","croup","crow","crowd","crown","crucifixion","crude","cruelty","cruise","crumb","crunch","crusader","crush","crust","cry","crystal","crystallography","cub","cube","cuckoo","cucumber","cue","cuff-link","cuisine","cultivar","cultivator","culture","culvert","cummerbund","cup","cupboard","cupcake","cupola","curd","cure","curio","curiosity","curl","curler","currant","currency","current","curriculum","curry","curse","cursor","curtailment","curtain","curve","cushion","custard","custody","custom","customer","cut","cuticle","cutlet","cutover","cutting","cyclamen","cycle","cyclone","cyclooxygenase","cygnet","cylinder","cymbal","cynic","cyst","cytokine","cytoplasm","dad","daddy","daffodil","dagger","dahlia","daikon","daily","dairy","daisy","dam","damage","dame","damn","dance","dancer","dancing","dandelion","danger","dare","dark","darkness","darn","dart","dash","dashboard","data","database","date","daughter","dawn","day","daybed","daylight","dead","deadline","deal","dealer","dealing","dearest","death","deathwatch","debate","debris","debt","debtor","decade","decadence","decency","decimal","decision","decision-making","deck","declaration","declination","decline","decoder","decongestant","decoration","decrease","decryption","dedication","deduce","deduction","deed","deep","deer","default","defeat","defendant","defender","defense","deficit","definition","deformation","degradation","degree","delay","deliberation","delight","delivery","demand","democracy","democrat","demon","demur","den","denim","denominator","density","dentist","deodorant","department","departure","dependency","dependent","deployment","deposit","deposition","depot","depression","depressive","depth","deputy","derby","derivation","derivative","derrick","descendant","descent","description","desert","design","designation","designer","desire","desk","desktop","dessert","destination","destiny","destroyer","destruction","detail","detainee","detainment","detection","detective","detector","detention","determination","detour","devastation","developer","developing","development","developmental","deviance","deviation","device","devil","dew","dhow","diabetes","diadem","diagnosis","diagram","dial","dialect","dialogue","diam","diamond","diaper","diaphragm","diarist","diary","dibble","dick","dickey","dictaphone","dictator","diction","dictionary","die","diesel","diet","difference","differential","difficulty","diffuse","dig","digestion","digestive","digger","digging","digit","dignity","dilapidation","dill","dilution","dime","dimension","dimple","diner","dinghy","dining","dinner","dinosaur","dioxide","dip","diploma","diplomacy","dipstick","direction","directive","director","directory","dirndl","dirt","disability","disadvantage","disagreement","disappointment","disarmament","disaster","discharge","discipline","disclaimer","disclosure","disco","disconnection","discount","discourse","discovery","discrepancy","discretion","discrimination","discussion","disdain","disease","disembodiment","disengagement","disguise","disgust","dish","dishwasher","disk","disparity","dispatch","displacement","display","disposal","disposer","disposition","dispute","disregard","disruption","dissemination","dissonance","distance","distinction","distortion","distribution","distributor","district","divalent","divan","diver","diversity","divide","dividend","divider","divine","diving","division","divorce","doc","dock","doctor","doctorate","doctrine","document","documentary","documentation","doe","dog","doggie","dogsled","dogwood","doing","doll","dollar","dollop","dolman","dolor","dolphin","domain","dome","domination","donation","donkey","donor","donut","door","doorbell","doorknob","doorpost","doorway","dory","dose","dot","double","doubling","doubt","doubter","dough","doughnut","down","downfall","downforce","downgrade","download","downstairs","downtown","downturn","dozen","draft","drag","dragon","dragonfly","dragonfruit","dragster","drain","drainage","drake","drama","dramaturge","drapes","draw","drawbridge","drawer","drawing","dream","dreamer","dredger","dress","dresser","dressing","drill","drink","drinking","drive","driver","driveway","driving","drizzle","dromedary","drop","drudgery","drug","drum","drummer","drunk","dryer","duck","duckling","dud","dude","due","duel","dueling","duffel","dugout","dulcimer","dumbwaiter","dump","dump truck","dune","dune buggy","dungarees","dungeon","duplexer","duration","durian","dusk","dust","dust storm","duster","duty","dwarf","dwell","dwelling","dynamics","dynamite","dynamo","dynasty","dysfunction","e-book","e-mail","e-reader","eagle","eaglet","ear","eardrum","earmuffs","earnings","earplug","earring","earrings","earth","earthquake","earthworm","ease","easel","east","eating","eaves","eavesdropper","ecclesia","echidna","eclipse","ecliptic","ecology","economics","economy","ecosystem","ectoderm","ectodermal","ecumenist","eddy","edge","edger","edible","editing","edition","editor","editorial","education","eel","effacement","effect","effective","effectiveness","effector","efficacy","efficiency","effort","egg","egghead","eggnog","eggplant","ego","eicosanoid","ejector","elbow","elderberry","election","electricity","electrocardiogram","electronics","element","elephant","elevation","elevator","eleventh","elf","elicit","eligibility","elimination","elite","elixir","elk","ellipse","elm","elongation","elver","email","emanate","embarrassment","embassy","embellishment","embossing","embryo","emerald","emergence","emergency","emergent","emery","emission","emitter","emotion","emphasis","empire","employ","employee","employer","employment","empowerment","emu","enactment","encirclement","enclave","enclosure","encounter","encouragement","encyclopedia","end","endive","endoderm","endorsement","endothelium","endpoint","enemy","energy","enforcement","engagement","engine","engineer","engineering","enigma","enjoyment","enquiry","enrollment","enterprise","entertainment","enthusiasm","entirety","entity","entrance","entree","entrepreneur","entry","envelope","environment","envy","enzyme","epauliere","epee","ephemera","ephemeris","ephyra","epic","episode","epithelium","epoch","eponym","epoxy","equal","equality","equation","equinox","equipment","equity","equivalent","era","eraser","erection","erosion","error","escalator","escape","escort","espadrille","espalier","essay","essence","essential","establishment","estate","estimate","estrogen","estuary","eternity","ethernet","ethics","ethnicity","ethyl","euphonium","eurocentrism","evaluation","evaluator","evaporation","eve","evening","evening-wear","event","everybody","everyone","everything","eviction","evidence","evil","evocation","evolution","ex-husband","ex-wife","exaggeration","exam","examination","examiner","example","exasperation","excellence","exception","excerpt","excess","exchange","excitement","exclamation","excursion","excuse","execution","executive","executor","exercise","exhaust","exhaustion","exhibit","exhibition","exile","existence","exit","exocrine","expansion","expansionism","expectancy","expectation","expedition","expense","experience","experiment","experimentation","expert","expertise","explanation","exploration","explorer","explosion","export","expose","exposition","exposure","expression","extension","extent","exterior","external","extinction","extreme","extremist","eye","eyeball","eyebrow","eyebrows","eyeglasses","eyelash","eyelashes","eyelid","eyelids","eyeliner","eyestrain","eyrie","fabric","face","facelift","facet","facility","facsimile","fact","factor","factory","faculty","fahrenheit","fail","failure","fairness","fairy","faith","faithful","fall","fallacy","falling-out","fame","familiar","familiarity","family","fan","fang","fanlight","fanny","fanny-pack","fantasy","farm","farmer","farming","farmland","farrow","fascia","fashion","fat","fate","father","father-in-law","fatigue","fatigues","faucet","fault","fav","fava","favor","favorite","fawn","fax","fear","feast","feather","feature","fedelini","federation","fedora","fee","feed","feedback","feeding","feel","feeling","fellow","felony","female","fen","fence","fencing","fender","feng","fennel","ferret","ferry","ferryboat","fertilizer","festival","fetus","few","fiber","fiberglass","fibre","fibroblast","fibrosis","ficlet","fiction","fiddle","field","fiery","fiesta","fifth","fig","fight","fighter","figure","figurine","file","filing","fill","fillet","filly","film","filter","filth","final","finance","financing","finding","fine","finer","finger","fingerling","fingernail","finish","finisher","fir","fire","fireman","fireplace","firewall","firm","first","fish","fishbone","fisherman","fishery","fishing","fishmonger","fishnet","fisting","fit","fitness","fix","fixture","flag","flair","flame","flan","flanker","flare","flash","flat","flatboat","flavor","flax","fleck","fledgling","fleece","flesh","flexibility","flick","flicker","flight","flint","flintlock","flip-flops","flock","flood","floodplain","floor","floozie","flour","flow","flower","flu","flugelhorn","fluke","flume","flung","flute","fly","flytrap","foal","foam","fob","focus","fog","fold","folder","folk","folklore","follower","following","fondue","font","food","foodstuffs","fool","foot","footage","football","footnote","footprint","footrest","footstep","footstool","footwear","forage","forager","foray","force","ford","forearm","forebear","forecast","forehead","foreigner","forelimb","forest","forestry","forever","forgery","fork","form","formal","formamide","format","formation","former","formicarium","formula","fort","forte","fortnight","fortress","fortune","forum","foundation","founder","founding","fountain","fourths","fowl","fox","foxglove","fraction","fragrance","frame","framework","fratricide","fraud","fraudster","freak","freckle","freedom","freelance","freezer","freezing","freight","freighter","frenzy","freon","frequency","fresco","friction","fridge","friend","friendship","fries","frigate","fright","fringe","fritter","frock","frog","front","frontier","frost","frosting","frown","fruit","frustration","fry","fuck","fuel","fugato","fulfillment","full","fun","function","functionality","fund","funding","fundraising","funeral","fur","furnace","furniture","furry","fusarium","futon","future","gadget","gaffe","gaffer","gain","gaiters","gale","gall-bladder","gallery","galley","gallon","galoshes","gambling","game","gamebird","gaming","gamma-ray","gander","gang","gap","garage","garb","garbage","garden","garlic","garment","garter","gas","gasket","gasoline","gasp","gastronomy","gastropod","gate","gateway","gather","gathering","gator","gauge","gauntlet","gavel","gazebo","gazelle","gear","gearshift","geek","gel","gelatin","gelding","gem","gemsbok","gender","gene","general","generation","generator","generosity","genetics","genie","genius","genocide","genre","gentleman","geography","geology","geometry","geranium","gerbil","gesture","geyser","gherkin","ghost","giant","gift","gig","gigantism","giggle","ginger","gingerbread","ginseng","giraffe","girdle","girl","girlfriend","git","glacier","gladiolus","glance","gland","glass","glasses","glee","glen","glider","gliding","glimpse","globe","glockenspiel","gloom","glory","glove","glow","glucose","glue","glut","glutamate","gnat","gnu","go-kart","goal","goat","gobbler","god","goddess","godfather","godmother","godparent","goggles","going","gold","goldfish","golf","gondola","gong","good","good-bye","goodbye","goodie","goodness","goodnight","goodwill","goose","gopher","gorilla","gosling","gossip","governance","government","governor","gown","grab-bag","grace","grade","gradient","graduate","graduation","graffiti","graft","grain","gram","grammar","gran","grand","grandchild","granddaughter","grandfather","grandma","grandmom","grandmother","grandpa","grandparent","grandson","granny","granola","grant","grape","grapefruit","graph","graphic","grasp","grass","grasshopper","grassland","gratitude","gravel","gravitas","gravity","gravy","gray","grease","great-grandfather","great-grandmother","greatness","greed","green","greenhouse","greens","grenade","grey","grid","grief","grill","grin","grip","gripper","grit","grocery","ground","group","grouper","grouse","grove","growth","grub","guacamole","guarantee","guard","guava","guerrilla","guess","guest","guestbook","guidance","guide","guideline","guilder","guilt","guilty","guinea","guitar","guitarist","gum","gumshoe","gun","gunpowder","gutter","guy","gym","gymnast","gymnastics","gynaecology","gyro","habit","habitat","hacienda","hacksaw","hackwork","hail","hair","haircut","hake","half","half-brother","half-sister","halibut","hall","halloween","hallway","halt","ham","hamburger","hammer","hammock","hamster","hand","hand-holding","handball","handful","handgun","handicap","handle","handlebar","handmaiden","handover","handrail","handsaw","hanger","happening","happiness","harald","harbor","harbour","hard-hat","hardboard","hardcover","hardening","hardhat","hardship","hardware","hare","harm","harmonica","harmonise","harmonize","harmony","harp","harpooner","harpsichord","harvest","harvester","hash","hashtag","hassock","haste","hat","hatbox","hatchet","hatchling","hate","hatred","haunt","haven","haversack","havoc","hawk","hay","haze","hazel","hazelnut","head","headache","headlight","headline","headphones","headquarters","headrest","health","health-care","hearing","hearsay","heart","heart-throb","heartache","heartbeat","hearth","hearthside","heartwood","heat","heater","heating","heaven","heavy","hectare","hedge","hedgehog","heel","heifer","height","heir","heirloom","helicopter","helium","hell","hellcat","hello","helmet","helo","help","hemisphere","hemp","hen","hepatitis","herb","herbs","heritage","hermit","hero","heroine","heron","herring","hesitation","heterosexual","hexagon","heyday","hiccups","hide","hierarchy","high","high-rise","highland","highlight","highway","hike","hiking","hill","hint","hip","hippodrome","hippopotamus","hire","hiring","historian","history","hit","hive","hobbit","hobby","hockey","hoe","hog","hold","holder","hole","holiday","home","homeland","homeownership","hometown","homework","homicide","homogenate","homonym","homosexual","homosexuality","honesty","honey","honeybee","honeydew","honor","honoree","hood","hoof","hook","hop","hope","hops","horde","horizon","hormone","horn","hornet","horror","horse","horseradish","horst","hose","hosiery","hospice","hospital","hospitalisation","hospitality","hospitalization","host","hostel","hostess","hotdog","hotel","hound","hour","hourglass","house","houseboat","household","housewife","housework","housing","hovel","hovercraft","howard","howitzer","hub","hubcap","hubris","hug","hugger","hull","human","humanity","humidity","hummus","humor","humour","hunchback","hundred","hunger","hunt","hunter","hunting","hurdle","hurdler","hurricane","hurry","hurt","husband","hut","hutch","hyacinth","hybridisation","hybridization","hydrant","hydraulics","hydrocarb","hydrocarbon","hydrofoil","hydrogen","hydrolyse","hydrolysis","hydrolyze","hydroxyl","hyena","hygienic","hype","hyphenation","hypochondria","hypothermia","hypothesis","ice","ice-cream","iceberg","icebreaker","icecream","icicle","icing","icon","icy","id","idea","ideal","identification","identity","ideology","idiom","idiot","igloo","ignorance","ignorant","ikebana","illegal","illiteracy","illness","illusion","illustration","image","imagination","imbalance","imitation","immigrant","immigration","immortal","impact","impairment","impala","impediment","implement","implementation","implication","import","importance","impostor","impress","impression","imprisonment","impropriety","improvement","impudence","impulse","in-joke","in-laws","inability","inauguration","inbox","incandescence","incarnation","incense","incentive","inch","incidence","incident","incision","inclusion","income","incompetence","inconvenience","increase","incubation","independence","independent","index","indication","indicator","indigence","individual","industrialisation","industrialization","industry","inequality","inevitable","infancy","infant","infarction","infection","infiltration","infinite","infix","inflammation","inflation","influence","influx","info","information","infrastructure","infusion","inglenook","ingrate","ingredient","inhabitant","inheritance","inhibition","inhibitor","initial","initialise","initialize","initiative","injunction","injury","injustice","ink","inlay","inn","innervation","innocence","innocent","innovation","input","inquiry","inscription","insect","insectarium","insert","inside","insight","insolence","insomnia","inspection","inspector","inspiration","installation","instance","instant","instinct","institute","institution","instruction","instructor","instrument","instrumentalist","instrumentation","insulation","insurance","insurgence","insurrection","integer","integral","integration","integrity","intellect","intelligence","intensity","intent","intention","intentionality","interaction","interchange","interconnection","intercourse","interest","interface","interferometer","interior","interject","interloper","internet","interpretation","interpreter","interval","intervenor","intervention","interview","interviewer","intestine","introduction","intuition","invader","invasion","invention","inventor","inventory","inverse","inversion","investigation","investigator","investment","investor","invitation","invite","invoice","involvement","iridescence","iris","iron","ironclad","irony","irrigation","ischemia","island","isogloss","isolation","issue","item","itinerary","ivory","jack","jackal","jacket","jackfruit","jade","jaguar","jail","jailhouse","jalape\xC3\xB1o","jam","jar","jasmine","jaw","jazz","jealousy","jeans","jeep","jelly","jellybeans","jellyfish","jerk","jet","jewel","jeweller","jewellery","jewelry","jicama","jiffy","job","jockey","jodhpurs","joey","jogging","joint","joke","jot","journal","journalism","journalist","journey","joy","judge","judgment","judo","jug","juggernaut","juice","julienne","jumbo","jump","jumper","jumpsuit","jungle","junior","junk","junker","junket","jury","justice","justification","jute","kale","kamikaze","kangaroo","karate","kayak","kazoo","kebab","keep","keeper","kendo","kennel","ketch","ketchup","kettle","kettledrum","key","keyboard","keyboarding","keystone","kick","kick-off","kid","kidney","kielbasa","kill","killer","killing","kilogram","kilometer","kilt","kimono","kinase","kind","kindness","king","kingdom","kingfish","kiosk","kiss","kit","kitchen","kite","kitsch","kitten","kitty","kiwi","knee","kneejerk","knickers","knife","knife-edge","knight","knitting","knock","knot","know-how","knowledge","knuckle","koala","kohlrabi","kumquat","lab","label","labor","laboratory","laborer","labour","labourer","lace","lack","lacquerware","lad","ladder","ladle","lady","ladybug","lag","lake","lamb","lambkin","lament","lamp","lanai","land","landform","landing","landmine","landscape","lane","language","lantern","lap","laparoscope","lapdog","laptop","larch","lard","larder","lark","larva","laryngitis","lasagna","lashes","last","latency","latex","lathe","latitude","latte","latter","laugh","laughter","laundry","lava","law","lawmaker","lawn","lawsuit","lawyer","lay","layer","layout","lead","leader","leadership","leading","leaf","league","leaker","leap","learning","leash","leather","leave","leaver","lecture","leek","leeway","left","leg","legacy","legal","legend","legging","legislation","legislator","legislature","legitimacy","legume","leisure","lemon","lemonade","lemur","lender","lending","length","lens","lentil","leopard","leprosy","leptocephalus","lesbian","lesson","letter","lettuce","level","lever","leverage","leveret","liability","liar","liberty","libido","library","licence","license","licensing","licorice","lid","lie","lieu","lieutenant","life","lifestyle","lifetime","lift","ligand","light","lighting","lightning","lightscreen","ligula","likelihood","likeness","lilac","lily","limb","lime","limestone","limit","limitation","limo","line","linen","liner","linguist","linguistics","lining","link","linkage","linseed","lion","lip","lipid","lipoprotein","lipstick","liquid","liquidity","liquor","list","listening","listing","literate","literature","litigation","litmus","litter","littleneck","liver","livestock","living","lizard","llama","load","loading","loaf","loafer","loan","lobby","lobotomy","lobster","local","locality","location","lock","locker","locket","locomotive","locust","lode","loft","log","loggia","logic","login","logistics","logo","loincloth","lollipop","loneliness","longboat","longitude","look","lookout","loop","loophole","loquat","lord","loss","lot","lotion","lottery","lounge","louse","lout","love","lover","lox","loyalty","luck","luggage","lumber","lumberman","lunch","luncheonette","lunchmeat","lunchroom","lung","lunge","lust","lute","luxury","lychee","lycra","lye","lymphocyte","lynx","lyocell","lyre","lyrics","lysine","mRNA","macadamia","macaroni","macaroon","macaw","machine","machinery","macrame","macro","macrofauna","madam","maelstrom","maestro","magazine","maggot","magic","magnet","magnitude","maid","maiden","mail","mailbox","mailer","mailing","mailman","main","mainland","mainstream","maintainer","maintenance","maize","major","major-league","majority","makeover","maker","makeup","making","male","malice","mall","mallard","mallet","malnutrition","mama","mambo","mammoth","man","manacle","management","manager","manatee","mandarin","mandate","mandolin","mangle","mango","mangrove","manhunt","maniac","manicure","manifestation","manipulation","mankind","manner","manor","mansard","manservant","mansion","mantel","mantle","mantua","manufacturer","manufacturing","many","map","maple","mapping","maracas","marathon","marble","march","mare","margarine","margin","mariachi","marimba","marines","marionberry","mark","marker","market","marketer","marketing","marketplace","marksman","markup","marmalade","marriage","marsh","marshland","marshmallow","marten","marxism","mascara","mask","masonry","mass","massage","mast","master","masterpiece","mastication","mastoid","mat","match","matchmaker","mate","material","maternity","math","mathematics","matrix","matter","mattock","mattress","max","maximum","maybe","mayonnaise","mayor","meadow","meal","mean","meander","meaning","means","meantime","measles","measure","measurement","meat","meatball","meatloaf","mecca","mechanic","mechanism","med","medal","media","median","medication","medicine","medium","meet","meeting","melatonin","melody","melon","member","membership","membrane","meme","memo","memorial","memory","men","menopause","menorah","mention","mentor","menu","merchandise","merchant","mercury","meridian","meringue","merit","mesenchyme","mess","message","messenger","messy","metabolite","metal","metallurgist","metaphor","meteor","meteorology","meter","methane","method","methodology","metric","metro","metronome","mezzanine","microlending","micronutrient","microphone","microwave","mid-course","midden","middle","middleman","midline","midnight","midwife","might","migrant","migration","mile","mileage","milepost","milestone","military","milk","milkshake","mill","millennium","millet","millimeter","million","millisecond","millstone","mime","mimosa","min","mincemeat","mind","mine","mineral","mineshaft","mini","mini-skirt","minibus","minimalism","minimum","mining","minion","minister","mink","minnow","minor","minor-league","minority","mint","minute","miracle","mirror","miscarriage","miscommunication","misfit","misnomer","misogyny","misplacement","misreading","misrepresentation","miss","missile","mission","missionary","mist","mistake","mister","misunderstand","miter","mitten","mix","mixer","mixture","moai","moat","mob","mobile","mobility","mobster","moccasins","mocha","mochi","mode","model","modeling","modem","modernist","modernity","modification","molar","molasses","molding","mole","molecule","mom","moment","monastery","monasticism","money","monger","monitor","monitoring","monk","monkey","monocle","monopoly","monotheism","monsoon","monster","month","monument","mood","moody","moon","moonlight","moonscape","moonshine","moose","mop","morale","morbid","morbidity","morning","moron","morphology","morsel","mortal","mortality","mortgage","mortise","mosque","mosquito","most","motel","moth","mother","mother-in-law","motion","motivation","motive","motor","motorboat","motorcar","motorcycle","mound","mountain","mouse","mouser","mousse","moustache","mouth","mouton","movement","mover","movie","mower","mozzarella","mud","muffin","mug","mukluk","mule","multimedia","murder","muscat","muscatel","muscle","musculature","museum","mushroom","music","music-box","music-making","musician","muskrat","mussel","mustache","mustard","mutation","mutt","mutton","mycoplasma","mystery","myth","mythology","nail","name","naming","nanoparticle","napkin","narrative","nasal","nation","nationality","native","naturalisation","nature","navigation","necessity","neck","necklace","necktie","nectar","nectarine","need","needle","neglect","negligee","negotiation","neighbor","neighborhood","neighbour","neighbourhood","neologism","neon","neonate","nephew","nerve","nest","nestling","nestmate","net","netball","netbook","netsuke","network","networking","neurobiologist","neuron","neuropathologist","neuropsychiatry","news","newsletter","newspaper","newsprint","newsstand","nexus","nibble","nicety","niche","nick","nickel","nickname","niece","night","nightclub","nightgown","nightingale","nightlife","nightlight","nightmare","ninja","nit","nitrogen","nobody","nod","node","noir","noise","nonbeliever","nonconformist","nondisclosure","nonsense","noodle","noodles","noon","norm","normal","normalisation","normalization","north","nose","notation","note","notebook","notepad","nothing","notice","notion","notoriety","nougat","noun","nourishment","novel","nucleotidase","nucleotide","nudge","nuke","number","numeracy","numeric","numismatist","nun","nurse","nursery","nursing","nurture","nut","nutmeg","nutrient","nutrition","nylon","nymph","oak","oar","oasis","oat","oatmeal","oats","obedience","obesity","obi","object","objection","objective","obligation","oboe","observation","observatory","obsession","obsidian","obstacle","occasion","occupation","occurrence","ocean","ocelot","octagon","octave","octavo","octet","octopus","odometer","odyssey","oeuvre","off-ramp","offence","offense","offer","offering","office","officer","official","offset","oil","okra","oldie","oleo","olive","omega","omelet","omission","omnivore","oncology","onion","online","onset","opening","opera","operating","operation","operator","ophthalmologist","opinion","opium","opossum","opponent","opportunist","opportunity","opposite","opposition","optimal","optimisation","optimist","optimization","option","orange","orangutan","orator","orchard","orchestra","orchid","order","ordinary","ordination","ore","oregano","organ","organisation","organising","organization","organizing","orient","orientation","origin","original","originality","ornament","osmosis","osprey","ostrich","other","otter","ottoman","ounce","outback","outcome","outfielder","outfit","outhouse","outlaw","outlay","outlet","outline","outlook","output","outrage","outrigger","outrun","outset","outside","oval","ovary","oven","overcharge","overclocking","overcoat","overexertion","overflight","overhead","overheard","overload","overnighter","overshoot","oversight","overview","overweight","owl","owner","ownership","ox","oxford","oxygen","oyster","ozone","pace","pacemaker","pack","package","packaging","packet","pad","paddle","paddock","pagan","page","pagoda","pail","pain","paint","painter","painting","paintwork","pair","pajamas","palace","palate","palm","pamphlet","pan","pancake","pancreas","panda","panel","panic","pannier","panpipe","pansy","panther","panties","pantologist","pantology","pantry","pants","pantsuit","panty","pantyhose","papa","papaya","paper","paperback","paperwork","parable","parachute","parade","paradise","paragraph","parallelogram","paramecium","paramedic","parameter","paranoia","parcel","parchment","pard","pardon","parent","parenthesis","parenting","park","parka","parking","parliament","parole","parrot","parser","parsley","parsnip","part","participant","participation","particle","particular","partner","partnership","partridge","party","pass","passage","passbook","passenger","passing","passion","passive","passport","password","past","pasta","paste","pastor","pastoralist","pastry","pasture","pat","patch","pate","patent","patentee","path","pathogenesis","pathology","pathway","patience","patient","patina","patio","patriarch","patrimony","patriot","patrol","patroller","patrolling","patron","pattern","patty","pattypan","pause","pavement","pavilion","paw","pawnshop","pay","payee","payment","payoff","pea","peace","peach","peacoat","peacock","peak","peanut","pear","pearl","peasant","pecan","pecker","pedal","peek","peen","peer","peer-to-peer","pegboard","pelican","pelt","pen","penalty","pence","pencil","pendant","pendulum","penguin","penicillin","peninsula","penis","pennant","penny","pension","pentagon","peony","people","pepper","pepperoni","percent","percentage","perception","perch","perennial","perfection","performance","perfume","period","periodical","peripheral","permafrost","permission","permit","perp","perpendicular","persimmon","person","personal","personality","personnel","perspective","pest","pet","petal","petition","petitioner","petticoat","pew","pharmacist","pharmacopoeia","phase","pheasant","phenomenon","phenotype","pheromone","philanthropy","philosopher","philosophy","phone","phosphate","photo","photodiode","photograph","photographer","photography","photoreceptor","phrase","phrasing","physical","physics","physiology","pianist","piano","piccolo","pick","pickax","pickaxe","picket","pickle","pickup","picnic","picture","picturesque","pie","piece","pier","piety","pig","pigeon","piglet","pigpen","pigsty","pike","pilaf","pile","pilgrim","pilgrimage","pill","pillar","pillbox","pillow","pilot","pimp","pimple","pin","pinafore","pince-nez","pine","pineapple","pinecone","ping","pink","pinkie","pinot","pinstripe","pint","pinto","pinworm","pioneer","pipe","pipeline","piracy","pirate","piss","pistol","pit","pita","pitch","pitcher","pitching","pith","pizza","place","placebo","placement","placode","plagiarism","plain","plaintiff","plan","plane","planet","planning","plant","plantation","planter","planula","plaster","plasterboard","plastic","plate","platelet","platform","platinum","platter","platypus","play","player","playground","playroom","playwright","plea","pleasure","pleat","pledge","plenty","plier","pliers","plight","plot","plough","plover","plow","plowman","plug","plugin","plum","plumber","plume","plunger","plywood","pneumonia","pocket","pocket-watch","pocketbook","pod","podcast","poem","poet","poetry","poignance","point","poison","poisoning","poker","polarisation","polarization","pole","polenta","police","policeman","policy","polish","politician","politics","poll","polliwog","pollutant","pollution","polo","polyester","polyp","pomegranate","pomelo","pompom","poncho","pond","pony","pool","poor","pop","popcorn","poppy","popsicle","popularity","population","populist","porcelain","porch","porcupine","pork","porpoise","port","porter","portfolio","porthole","portion","portrait","position","possession","possibility","possible","post","postage","postbox","poster","posterior","postfix","pot","potato","potential","pottery","potty","pouch","poultry","pound","pounding","poverty","powder","power","practice","practitioner","prairie","praise","pray","prayer","precedence","precedent","precipitation","precision","predecessor","preface","preference","prefix","pregnancy","prejudice","prelude","premeditation","premier","premise","premium","preoccupation","preparation","prescription","presence","present","presentation","preservation","preserves","presidency","president","press","pressroom","pressure","pressurisation","pressurization","prestige","presume","pretzel","prevalence","prevention","prey","price","pricing","pride","priest","priesthood","primary","primate","prince","princess","principal","principle","print","printer","printing","prior","priority","prison","prisoner","privacy","private","privilege","prize","prizefight","probability","probation","probe","problem","procedure","proceedings","process","processing","processor","proctor","procurement","produce","producer","product","production","productivity","profession","professional","professor","profile","profit","progenitor","program","programme","programming","progress","progression","prohibition","project","proliferation","promenade","promise","promotion","prompt","pronoun","pronunciation","proof","proof-reader","propaganda","propane","property","prophet","proponent","proportion","proposal","proposition","proprietor","prose","prosecution","prosecutor","prospect","prosperity","prostacyclin","prostanoid","prostrate","protection","protein","protest","protocol","providence","provider","province","provision","prow","proximal","proximity","prune","pruner","pseudocode","pseudoscience","psychiatrist","psychoanalyst","psychologist","psychology","ptarmigan","pub","public","publication","publicity","publisher","publishing","pudding","puddle","puffin","pug","puggle","pulley","pulse","puma","pump","pumpernickel","pumpkin","pumpkinseed","pun","punch","punctuation","punishment","pup","pupa","pupil","puppet","puppy","purchase","puritan","purity","purple","purpose","purr","purse","pursuit","push","pusher","put","puzzle","pyramid","pyridine","quadrant","quail","qualification","quality","quantity","quart","quarter","quartet","quartz","queen","query","quest","question","questioner","questionnaire","quiche","quicksand","quiet","quill","quilt","quince","quinoa","quit","quiver","quota","quotation","quote","rabbi","rabbit","raccoon","race","racer","racing","racism","racist","rack","radar","radiator","radio","radiosonde","radish","raffle","raft","rag","rage","raid","rail","railing","railroad","railway","raiment","rain","rainbow","raincoat","rainmaker","rainstorm","rainy","raise","raisin","rake","rally","ram","rambler","ramen","ramie","ranch","rancher","randomisation","randomization","range","ranger","rank","rap","rape","raspberry","rat","rate","ratepayer","rating","ratio","rationale","rations","raven","ravioli","rawhide","ray","rayon","razor","reach","reactant","reaction","read","reader","readiness","reading","real","reality","realization","realm","reamer","rear","reason","reasoning","rebel","rebellion","reboot","recall","recapitulation","receipt","receiver","reception","receptor","recess","recession","recipe","recipient","reciprocity","reclamation","recliner","recognition","recollection","recommendation","reconsideration","record","recorder","recording","recovery","recreation","recruit","rectangle","red","redesign","redhead","redirect","rediscovery","reduction","reef","refectory","reference","referendum","reflection","reform","refreshments","refrigerator","refuge","refund","refusal","refuse","regard","regime","region","regionalism","register","registration","registry","regret","regulation","regulator","rehospitalisation","rehospitalization","reindeer","reinscription","reject","relation","relationship","relative","relaxation","relay","release","reliability","relief","religion","relish","reluctance","remains","remark","reminder","remnant","remote","removal","renaissance","rent","reorganisation","reorganization","repair","reparation","repayment","repeat","replacement","replica","replication","reply","report","reporter","reporting","repository","representation","representative","reprocessing","republic","republican","reputation","request","requirement","resale","rescue","research","researcher","resemblance","reservation","reserve","reservoir","reset","residence","resident","residue","resist","resistance","resolution","resolve","resort","resource","respect","respite","response","responsibility","rest","restaurant","restoration","restriction","restroom","restructuring","result","resume","retailer","retention","rethinking","retina","retirement","retouching","retreat","retrospect","retrospective","retrospectivity","return","reunion","revascularisation","revascularization","reveal","revelation","revenant","revenge","revenue","reversal","reverse","review","revitalisation","revitalization","revival","revolution","revolver","reward","rhetoric","rheumatism","rhinoceros","rhubarb","rhyme","rhythm","rib","ribbon","rice","riddle","ride","rider","ridge","riding","rifle","right","rim","ring","ringworm","riot","rip","ripple","rise","riser","risk","rite","ritual","river","riverbed","rivulet","road","roadway","roar","roast","robe","robin","robot","robotics","rock","rocker","rocket","rocket-ship","rod","role","roll","roller","romaine","romance","roof","room","roommate","rooster","root","rope","rose","rosemary","roster","rostrum","rotation","round","roundabout","route","router","routine","row","rowboat","rowing","rubber","rubbish","rubric","ruby","ruckus","rudiment","ruffle","rug","rugby","ruin","rule","ruler","ruling","rum","rumor","run","runaway","runner","running","runway","rush","rust","rutabaga","rye","sabre","sac","sack","saddle","sadness","safari","safe","safeguard","safety","saffron","sage","sail","sailboat","sailing","sailor","saint","sake","salad","salami","salary","sale","salesman","salmon","salon","saloon","salsa","salt","salute","samovar","sampan","sample","samurai","sanction","sanctity","sanctuary","sand","sandal","sandbar","sandpaper","sandwich","sanity","sardine","sari","sarong","sash","satellite","satin","satire","satisfaction","sauce","saucer","sauerkraut","sausage","savage","savannah","saving","savings","savior","saviour","savory","saw","saxophone","scaffold","scale","scallion","scallops","scalp","scam","scanner","scarecrow","scarf","scarification","scenario","scene","scenery","scent","schedule","scheduling","schema","scheme","schizophrenic","schnitzel","scholar","scholarship","school","schoolhouse","schooner","science","scientist","scimitar","scissors","scooter","scope","score","scorn","scorpion","scotch","scout","scow","scrambled","scrap","scraper","scratch","screamer","screen","screening","screenwriting","screw","screw-up","screwdriver","scrim","scrip","script","scripture","scrutiny","sculpting","sculptural","sculpture","sea","seabass","seafood","seagull","seal","seaplane","search","seashore","seaside","season","seat","seaweed","second","secrecy","secret","secretariat","secretary","secretion","section","sectional","sector","security","sediment","seed","seeder","seeker","seep","segment","seizure","selection","self","self-confidence","self-control","self-esteem","seller","selling","semantics","semester","semicircle","semicolon","semiconductor","seminar","senate","senator","sender","senior","sense","sensibility","sensitive","sensitivity","sensor","sentence","sentencing","sentiment","sepal","separation","septicaemia","sequel","sequence","serial","series","sermon","serum","serval","servant","server","service","servitude","sesame","session","set","setback","setting","settlement","settler","severity","sewer","sex","sexuality","shack","shackle","shade","shadow","shadowbox","shakedown","shaker","shallot","shallows","shame","shampoo","shanty","shape","share","shareholder","shark","shaw","shawl","shear","shearling","sheath","shed","sheep","sheet","shelf","shell","shelter","sherbet","sherry","shield","shift","shin","shine","shingle","ship","shipper","shipping","shipyard","shirt","shirtdress","shit","shoat","shock","shoe","shoe-horn","shoehorn","shoelace","shoemaker","shoes","shoestring","shofar","shoot","shootdown","shop","shopper","shopping","shore","shoreline","short","shortage","shorts","shortwave","shot","shoulder","shout","shovel","show","show-stopper","shower","shred","shrimp","shrine","shutdown","sibling","sick","sickness","side","sideboard","sideburns","sidecar","sidestream","sidewalk","siding","siege","sigh","sight","sightseeing","sign","signal","signature","signet","significance","signify","signup","silence","silica","silicon","silk","silkworm","sill","silly","silo","silver","similarity","simple","simplicity","simplification","simvastatin","sin","singer","singing","singular","sink","sinuosity","sip","sir","sister","sister-in-law","sitar","site","situation","size","skate","skating","skean","skeleton","ski","skiing","skill","skin","skirt","skull","skullcap","skullduggery","skunk","sky","skylight","skyline","skyscraper","skywalk","slang","slapstick","slash","slate","slave","slavery","slaw","sled","sledge","sleep","sleepiness","sleeping","sleet","sleuth","slice","slide","slider","slime","slip","slipper","slippers","slope","slot","sloth","slump","smell","smelting","smile","smith","smock","smog","smoke","smoking","smolt","smuggling","snack","snail","snake","snakebite","snap","snarl","sneaker","sneakers","sneeze","sniffle","snob","snorer","snow","snowboarding","snowflake","snowman","snowmobiling","snowplow","snowstorm","snowsuit","snuck","snug","snuggle","soap","soccer","socialism","socialist","society","sociology","sock","socks","soda","sofa","softball","softdrink","softening","software","soil","soldier","sole","solicitation","solicitor","solidarity","solidity","soliloquy","solitaire","solution","solvency","sombrero","somebody","someone","someplace","somersault","something","somewhere","son","sonar","sonata","song","songbird","sonnet","soot","sophomore","soprano","sorbet","sorghum","sorrel","sorrow","sort","soul","soulmate","sound","soundness","soup","source","sourwood","sousaphone","south","southeast","souvenir","sovereignty","sow","soy","soybean","space","spacing","spade","spaghetti","span","spandex","spank","sparerib","spark","sparrow","spasm","spat","spatula","spawn","speaker","speakerphone","speaking","spear","spec","special","specialist","specialty","species","specification","spectacle","spectacles","spectrograph","spectrum","speculation","speech","speed","speedboat","spell","spelling","spelt","spending","sphere","sphynx","spice","spider","spiderling","spike","spill","spinach","spine","spiral","spirit","spiritual","spirituality","spit","spite","spleen","splendor","split","spokesman","spokeswoman","sponge","sponsor","sponsorship","spool","spoon","spork","sport","sportsman","spot","spotlight","spouse","sprag","sprat","spray","spread","spreadsheet","spree","spring","sprinkles","sprinter","sprout","spruce","spud","spume","spur","spy","spyglass","square","squash","squatter","squeegee","squid","squirrel","stab","stability","stable","stack","stacking","stadium","staff","stag","stage","stain","stair","staircase","stake","stalk","stall","stallion","stamen","stamina","stamp","stance","stand","standard","standardisation","standardization","standing","standoff","standpoint","star","starboard","start","starter","state","statement","statin","station","station-wagon","statistic","statistics","statue","status","statute","stay","steak","stealth","steam","steamroller","steel","steeple","stem","stench","stencil","step","step-aunt","step-brother","step-daughter","step-father","step-grandfather","step-grandmother","step-mother","step-sister","step-son","step-uncle","stepdaughter","stepmother","stepping-stone","stepson","stereo","stew","steward","stick","sticker","stiletto","still","stimulation","stimulus","sting","stinger","stir-fry","stitch","stitcher","stock","stock-in-trade","stockings","stole","stomach","stone","stonework","stool","stop","stopsign","stopwatch","storage","store","storey","storm","story","story-telling","storyboard","stot","stove","strait","strand","stranger","strap","strategy","straw","strawberry","strawman","stream","street","streetcar","strength","stress","stretch","strife","strike","string","strip","stripe","strobe","stroke","structure","strudel","struggle","stucco","stud","student","studio","study","stuff","stumbling","stump","stupidity","sturgeon","sty","style","styling","stylus","sub","subcomponent","subconscious","subcontractor","subexpression","subgroup","subject","submarine","submitter","subprime","subroutine","subscription","subsection","subset","subsidence","subsidiary","subsidy","substance","substitution","subtitle","suburb","subway","success","succotash","suck","sucker","suede","suet","suffocation","sugar","suggestion","suicide","suit","suitcase","suite","sulfur","sultan","sum","summary","summer","summit","sun","sunbeam","sunbonnet","sundae","sunday","sundial","sunflower","sunglasses","sunlamp","sunlight","sunrise","sunroom","sunset","sunshine","superiority","supermarket","supernatural","supervision","supervisor","supper","supplement","supplier","supply","support","supporter","suppression","supreme","surface","surfboard","surge","surgeon","surgery","surname","surplus","surprise","surround","surroundings","surrounds","survey","survival","survivor","sushi","suspect","suspenders","suspension","sustainment","sustenance","swallow","swamp","swan","swanling","swath","sweat","sweater","sweatshirt","sweatshop","sweatsuit","sweets","swell","swim","swimming","swimsuit","swine","swing","switch","switchboard","switching","swivel","sword","swordfight","swordfish","sycamore","symbol","symmetry","sympathy","symptom","syndicate","syndrome","synergy","synod","synonym","synthesis","syrup","system","t-shirt","tab","tabby","tabernacle","table","tablecloth","tablet","tabletop","tachometer","tackle","taco","tactics","tactile","tadpole","tag","tail","tailbud","tailor","tailspin","take-out","takeover","tale","talent","talk","talking","tam-o'-shanter","tamale","tambour","tambourine","tan","tandem","tangerine","tank","tank-top","tanker","tankful","tap","tape","tapioca","target","taro","tarragon","tart","task","tassel","taste","tatami","tattler","tattoo","tavern","tax","taxi","taxicab","taxpayer","tea","teacher","teaching","team","teammate","teapot","tear","tech","technician","technique","technologist","technology","tectonics","teen","teenager","teepee","telephone","telescreen","teletype","television","tell","teller","temp","temper","temperature","temple","tempo","temporariness","temporary","temptation","temptress","tenant","tendency","tender","tenement","tenet","tennis","tenor","tension","tensor","tent","tentacle","tenth","tepee","teriyaki","term","terminal","termination","terminology","termite","terrace","terracotta","terrapin","terrarium","territory","terror","terrorism","terrorist","test","testament","testimonial","testimony","testing","text","textbook","textual","texture","thanks","thaw","theater","theft","theism","theme","theology","theory","therapist","therapy","thermals","thermometer","thermostat","thesis","thickness","thief","thigh","thing","thinking","thirst","thistle","thong","thongs","thorn","thought","thousand","thread","threat","threshold","thrift","thrill","throat","throne","thrush","thrust","thug","thumb","thump","thunder","thunderbolt","thunderhead","thunderstorm","thyme","tiara","tic","tick","ticket","tide","tie","tiger","tights","tile","till","tilt","timbale","timber","time","timeline","timeout","timer","timetable","timing","timpani","tin","tinderbox","tinkle","tintype","tip","tire","tissue","titanium","title","toad","toast","toaster","tobacco","today","toe","toenail","toffee","tofu","tog","toga","toilet","tolerance","tolerant","toll","tom-tom","tomatillo","tomato","tomb","tomography","tomorrow","ton","tonality","tone","tongue","tonic","tonight","tool","toot","tooth","toothbrush","toothpaste","toothpick","top","top-hat","topic","topsail","toque","toreador","tornado","torso","torte","tortellini","tortilla","tortoise","tosser","total","tote","touch","tough-guy","tour","tourism","tourist","tournament","tow-truck","towel","tower","town","townhouse","township","toy","trace","trachoma","track","tracking","tracksuit","tract","tractor","trade","trader","trading","tradition","traditionalism","traffic","trafficker","tragedy","trail","trailer","trailpatrol","train","trainer","training","trait","tram","tramp","trance","transaction","transcript","transfer","transformation","transit","transition","translation","transmission","transom","transparency","transplantation","transport","transportation","trap","trapdoor","trapezium","trapezoid","trash","travel","traveler","tray","treasure","treasury","treat","treatment","treaty","tree","trek","trellis","tremor","trench","trend","triad","trial","triangle","tribe","tributary","trick","trigger","trigonometry","trillion","trim","trinket","trip","tripod","tritone","triumph","trolley","trombone","troop","trooper","trophy","trouble","trousers","trout","trove","trowel","truck","trumpet","trunk","trust","trustee","truth","try","tsunami","tub","tuba","tube","tuber","tug","tugboat","tuition","tulip","tumbler","tummy","tuna","tune","tune-up","tunic","tunnel","turban","turf","turkey","turmeric","turn","turning","turnip","turnover","turnstile","turret","turtle","tusk","tussle","tutu","tuxedo","tweet","tweezers","twig","twilight","twine","twins","twist","twister","twitter","type","typeface","typewriter","typhoon","ukulele","ultimatum","umbrella","unblinking","uncertainty","uncle","underclothes","underestimate","underground","underneath","underpants","underpass","undershirt","understanding","understatement","undertaker","underwear","underweight","underwire","underwriting","unemployment","unibody","uniform","uniformity","union","unique","unit","unity","universe","university","update","upgrade","uplift","upper","upstairs","upward","urge","urgency","urn","usage","use","user","usher","usual","utensil","utilisation","utility","utilization","vacation","vaccine","vacuum","vagrant","valance","valentine","validate","validity","valley","valuable","value","vampire","van","vanadyl","vane","vanilla","vanity","variability","variable","variant","variation","variety","vascular","vase","vault","vaulting","veal","vector","vegetable","vegetarian","vegetarianism","vegetation","vehicle","veil","vein","veldt","vellum","velocity","velodrome","velvet","vendor","veneer","vengeance","venison","venom","venti","venture","venue","veranda","verb","verdict","verification","vermicelli","vernacular","verse","version","vertigo","verve","vessel","vest","vestment","vet","veteran","veterinarian","veto","viability","vibe","vibraphone","vibration","vibrissae","vice","vicinity","victim","victory","video","view","viewer","vignette","villa","village","vine","vinegar","vineyard","vintage","vintner","vinyl","viola","violation","violence","violet","violin","virginal","virtue","virus","visa","viscose","vise","vision","visit","visitor","visor","vista","visual","vitality","vitamin","vitro","vivo","vixen","vodka","vogue","voice","void","vol","volatility","volcano","volleyball","volume","volunteer","volunteering","vomit","vote","voter","voting","voyage","vulture","wad","wafer","waffle","wage","wagon","waist","waistband","wait","waiter","waiting","waitress","waiver","wake","walk","walker","walking","walkway","wall","wallaby","wallet","walnut","walrus","wampum","wannabe","want","war","warden","wardrobe","warfare","warlock","warlord","warm-up","warming","warmth","warning","warrant","warren","warrior","wasabi","wash","washbasin","washcloth","washer","washtub","wasp","waste","wastebasket","wasting","watch","watcher","watchmaker","water","waterbed","watercress","waterfall","waterfront","watermelon","waterskiing","waterspout","waterwheel","wave","waveform","wax","way","weakness","wealth","weapon","wear","weasel","weather","web","webinar","webmail","webpage","website","wedding","wedge","weed","weeder","weedkiller","week","weekend","weekender","weight","weird","welcome","welfare","well","well-being","west","western","wet-bar","wetland","wetsuit","whack","whale","wharf","wheat","wheel","whelp","whey","whip","whirlpool","whirlwind","whisker","whiskey","whisper","whistle","white","whole","wholesale","wholesaler","whorl","wick","widget","widow","width","wife","wifi","wild","wildebeest","wilderness","wildlife","will","willingness","willow","win","wind","wind-chime","windage","window","windscreen","windshield","wine","winery","wing","wingman","wingtip","wink","winner","winter","wire","wiretap","wiring","wisdom","wiseguy","wish","wisteria","wit","witch","witch-hunt","withdrawal","witness","wok","wolf","woman","wombat","wonder","wont","wood","woodchuck","woodland","woodshed","woodwind","wool","woolens","word","wording","work","workbench","worker","workforce","workhorse","working","workout","workplace","workshop","world","worm","worry","worship","worshiper","worth","wound","wrap","wraparound","wrapper","wrapping","wreck","wrecker","wren","wrench","wrestler","wriggler","wrinkle","wrist","writer","writing","wrong","xylophone","yacht","yahoo","yak","yam","yang","yard","yarmulke","yarn","yawl","year","yeast","yellow","yellowjacket","yesterday","yew","yin","yoga","yogurt","yoke","yolk","young","youngster","yourself","youth","yoyo","yurt","zampone","zebra","zebrafish","zen","zephyr","zero","ziggurat","zinc","zipper","zither","zombie","zone","zoo","zoologist","zoology","zoot-suit","zucchini"];var $n=["a","abaft","aboard","about","above","absent","across","afore","after","against","along","alongside","amid","amidst","among","amongst","an","anenst","anti","apropos","apud","around","as","aside","astride","at","athwart","atop","barring","before","behind","below","beneath","beside","besides","between","beyond","but","by","circa","concerning","considering","despite","down","during","except","excepting","excluding","failing","following","for","forenenst","from","given","in","including","inside","into","lest","like","mid","midst","minus","modulo","near","next","notwithstanding","of","off","on","onto","opposite","out","outside","over","pace","past","per","plus","pro","qua","regarding","round","sans","save","since","than","the","through","throughout","till","times","to","toward","towards","under","underneath","unlike","until","unto","up","upon","versus","via","vice","with","within","without","worth"];var Rn=["abandon","abase","abate","abbreviate","abdicate","abduct","abet","abhor","abide","abjure","abnegate","abolish","abominate","abort","abound","abrade","abridge","abrogate","abscond","abseil","absent","absolve","absorb","abstain","abstract","abuse","abut","accede","accelerate","accent","accentuate","accept","access","accessorise","accessorize","acclaim","acclimate","acclimatise","acclimatize","accommodate","accompany","accomplish","accord","accost","account","accouter","accoutre","accredit","accrue","acculturate","accumulate","accuse","accustom","ace","ache","achieve","acidify","acknowledge","acquaint","acquiesce","acquire","acquit","act","action","activate","actualise","actualize","actuate","adapt","add","addle","address","adduce","adhere","adjoin","adjourn","adjudge","adjudicate","adjure","adjust","administer","admire","admit","admonish","adopt","adore","adorn","adsorb","adulterate","adumbrate","advance","advantage","advertise","advise","advocate","aerate","affect","affiliate","affirm","affix","afflict","afford","afforest","affront","age","agglomerate","aggravate","aggregate","agitate","agonise","agonize","agree","aid","ail","aim","air","airbrush","airdrop","airfreight","airlift","alarm","alert","alienate","alight","align","allay","allege","alleviate","allocate","allot","allow","alloy","allude","ally","alphabetise","alphabetize","alter","alternate","amalgamate","amass","amaze","amble","ambush","ameliorate","amend","amortise","amortize","amount","amplify","amputate","amuse","anaesthetise","anaesthetize","analyse","anchor","anesthetize","anger","angle","anglicise","anglicize","animate","anneal","annex","annihilate","annotate","announce","annoy","annul","anodise","anodize","anoint","anonymise","anonymize","answer","antagonise","antagonize","antedate","anthologise","anthologize","anticipate","ape","apologise","apologize","apostrophise","apostrophize","appal","appall","appeal","appear","appease","append","appertain","applaud","apply","appoint","apportion","appraise","appreciate","apprehend","apprentice","apprise","approach","appropriate","approve","approximate","aquaplane","arbitrate","arc","arch","archive","argue","arise","arm","arouse","arraign","arrange","array","arrest","arrive","arrogate","arse","art","articulate","ascend","ascertain","ascribe","ask","asphyxiate","aspirate","aspire","assail","assassinate","assault","assay","assemble","assent","assert","assess","assign","assimilate","assist","associate","assuage","assume","assure","asterisk","astonish","astound","atomise","atomize","atone","atrophy","attach","attack","attain","attempt","attend","attenuate","attest","attract","attribute","auction","audit","audition","augment","augur","authenticate","author","authorise","authorize","autograph","automate","autosave","autowind","avail","avenge","aver","average","avert","avoid","avow","await","awake","awaken","award","awe","ax","axe","baa","babble","baby","babysit","back","backcomb","backdate","backfill","backfire","backlight","backpack","backspace","backtrack","badger","baffle","bag","bail","bait","bake","balance","bale","ball","balloon","ballot","balls","bamboozle","ban","band","bandage","bandy","bang","bangs","banish","bank","bankroll","bankrupt","banter","baptise","baptize","bar","barbecue","bare","barf","bargain","barge","bark","barnstorm","barrack","barrel","barricade","barter","base","bash","bask","bastardise","bastardize","baste","bat","batch","bath","bathe","batten","batter","battle","baulk","bawl","bay","bayonet","be","beach","beam","bean","bear","beard","beat","beatbox","beatboxer","beatify","beautify","beaver","beckon","become","bed","bedazzle","bedeck","bedevil","beef","beep","beetle","befall","befit","befog","befriend","beg","beget","beggar","begin","begrudge","beguile","behave","behead","behold","behoove","behove","belabor","belabour","belay","belch","belie","believe","belittle","bellow","belly","bellyache","belong","belt","bemoan","bemuse","benchmark","bend","benefit","bequeath","berate","bereave","berth","beseech","beset","besiege","besmirch","bespatter","bespeak","best","bestir","bestow","bestride","bet","betake","betide","betoken","betray","better","bewail","beware","bewilder","bewitch","bias","bicker","bicycle","bid","bide","biff","bifurcate","big","bike","bilk","bill","billet","billow","bin","bind","binge","biodegrade","bird","bisect","bitch","bite","bitmap","bivouac","bivvy","blab","blabber","black","blackball","blacken","blacklist","blackmail","blag","blame","blanch","blank","blanket","blare","blaspheme","blast","blather","blaze","blazon","bleach","bleat","bleed","bleep","blemish","blench","blend","bless","blight","blind","blindfold","blindfolded","blindside","blink","bliss","blister","blitz","bloat","block","blockade","blog","blood","bloom","bloop","blossom","blot","blow","blub","blubber","bludge","bludgeon","bluff","blunder","blunt","blur","blurt","blush","bluster","board","boast","bob","bobble","bode","bodge","bog","boggle","boil","bolster","bolt","bomb","bombard","bond","bone","bonk","boo","boob","boogie","book","bookmark","boom","boomerang","boost","boot","bootleg","booze","bop","border","bore","born","borrow","boss","botch","bother","bottle","bottleful","bottom","bounce","bound","bow","bowdlerise","bowdlerize","bowl","bowlful","box","boycott","braai","brace","braces","bracket","brag","braid","brain","brainstorm","brainwash","braise","brake","branch","brand","brandish","brave","brawl","bray","brazen","breach","break","breakfast","breast","breastfeed","breathalyse","breathalyze","breathe","breed","breeze","brew","bribe","brick","bridge","bridle","brief","brighten","brim","bring","bristle","broach","broadcast","broaden","broadside","broil","broker","brood","brook","browbeat","brown","browse","bruise","bruit","brush","brutalise","brutalize","bubble","buck","bucket","bucketful","buckle","bud","buddy","budge","budget","buff","buffer","buffet","bug","bugger","build","bulge","bulk","bulldoze","bullshit","bully","bum","bumble","bump","bunch","bundle","bung","bungle","bunk","bunker","bunt","buoy","burble","burden","burgeon","burglarize","burgle","burn","burnish","burp","burrow","burst","bury","bus","bushwhack","busk","bust","bustle","busy","butcher","butt","butter","button","buttonhole","buttress","buy","buzz","buzzing","bypass","cable","cache","cackle","caddie","cadge","cage","cajole","cake","calcify","calculate","calibrate","call","calm","calve","camouflage","camp","campaign","can","canalise","canalize","cancel","cane","cannibalise","cannibalize","cannon","cannulate","canoe","canonise","canonize","canoodle","canst","cant","canter","canvass","cap","caper","capitalise","capitalize","capitulate","capsize","captain","caption","captivate","capture","caramelise","caramelize","carbonise","carbonize","carburise","carburize","card","care","careen","career","caress","caricature","carjack","carol","carom","carouse","carp","carpet","carpool","carry","cart","cartwheel","carve","cascade","case","cash","cashier","casserole","cast","castigate","castrate","catalog","catalogue","catalyse","catalyze","catapult","catch","categorise","categorize","cater","caterwaul","catnap","caucus","caulk","cause","cauterise","cauterize","caution","cave","cavil","cavort","caw","cc","cease","cede","celebrate","cement","censor","censure","centralise","centralize","centre","certificate","certify","chafe","chaff","chain","chair","chalk","challenge","champ","champion","chance","change","channel","chant","chaperon","chaperone","char","characterise","characterize","charbroil","charge","chargesheet","chargrill","charm","chart","charter","chase","chasten","chastise","chat","chatter","chauffeur","cheapen","cheat","cheater","check","checkmate","cheek","cheep","cheer","cherish","chew","chicken","chide","chill","chillax","chime","chink","chip","chirp","chisel","chivvy","chlorinate","choke","chomp","choose","chop","choreograph","chortle","chorus","christen","chromakey","chronicle","chuck","chuckle","chug","chunder","chunter","churn","cinch","circle","circulate","circumcise","circumnavigate","circumscribe","circumvent","cite","civilise","civilize","clack","claim","clam","clamber","clamor","clamour","clamp","clang","clank","clap","clarify","clash","clasp","class","classify","clatter","claw","clean","cleanse","clear","cleave","clench","clerk","click","climax","climb","clinch","cling","clink","clinking","clip","cloak","clobber","clock","clog","clone","clonk","close","closet","clot","clothe","cloud","clout","clown","club","cluck","clue","clump","clunk","cluster","clutch","clutter","coach","coagulate","coalesce","coarsen","coast","coat","coax","cobble","cock","cocoon","coddle","code","codify","coerce","coexist","cogitate","cohabit","cohere","coil","coin","coincide","collaborate","collapse","collar","collate","collect","collectivise","collectivize","collide","colligate","collocate","collude","colonise","colonize","colorize","colour","comb","combat","combine","combust","come","comfort","command","commandeer","commemorate","commence","commend","comment","commentate","commercialise","commercialize","commingle","commiserate","commission","commit","commune","communicate","commute","compact","compare","compartmentalise","compartmentalize","compel","compensate","compete","compile","complain","complement","complete","complicate","compliment","comply","comport","compose","compost","compound","comprehend","compress","comprise","compromise","compute","computerise","computerize","con","conceal","concede","conceive","concentrate","conceptualise","conceptualize","concern","concertina","conciliate","conclude","concoct","concrete","concur","concuss","condemn","condense","condescend","condition","condone","conduct","cone","confer","confess","confide","configure","confine","confirm","confiscate","conflate","conflict","conform","confound","confront","confuse","confute","congeal","congratulate","congregate","conjecture","conjoin","conjugate","conjure","conk","connect","connive","connote","conquer","conscientise","conscientize","conscript","consecrate","consent","conserve","consider","consign","consist","console","consolidate","consort","conspire","constitute","constrain","constrict","construct","construe","consult","consume","consummate","contact","contain","contaminate","contemplate","contend","content","contest","contextualise","contextualize","continue","contort","contract","contradict","contraindicate","contrast","contravene","contribute","contrive","control","controvert","convalesce","convene","converge","converse","convert","convey","convict","convince","convoke","convulse","coo","cook","cool","coop","cooperate","coordinate","cop","cope","coppice","copulate","copy","copyright","cordon","core","cork","corkscrew","corner","corral","correct","correlate","correspond","corrode","corrupt","coruscate","cosh","cosset","cost","cosy","cotton","couch","cough","counsel","count","countenance","counter","counteract","counterbalance","counterfeit","countermand","counterpoint","countersign","couple","courier","course","court","covenant","cover","covet","cow","cower","cox","cozy","crack","crackle","cradle","craft","cram","cramp","crane","crank","crap","crash","crate","crave","crawl","crayon","creak","creaking","cream","crease","create","credential","credit","creep","cremate","creolise","creolize","creosote","crest","crew","crib","crick","criminalise","criminalize","crimp","cringe","crinkle","cripple","crisp","criticise","criticize","critique","croak","crochet","crook","croon","crop","cross","crouch","crow","crowd","crown","crucify","cruise","crumble","crumple","crunch","crusade","crush","cry","crystallise","crystallize","cube","cuckold","cuddle","cudgel","cue","cuff","cull","culminate","cultivate","culture","cup","curate","curb","curdle","cure","curl","curry","curse","curtail","curtain","curtsy","curve","cushion","cuss","customise","customize","cut","cwtch","cycle","dab","dabble","dally","dam","damage","dammit","damn","damp","dampen","dance","dandle","dangle","dare","darken","darn","dart","dash","date","daub","daunt","dawdle","dawn","daydream","dazzle","deactivate","deaden","deadhead","deafen","deal","debar","debase","debate","debilitate","debit","debrief","debug","debunk","debut","decamp","decant","decapitate","decay","deceive","decelerate","decentralise","decentralize","decide","decimalise","decimalize","decimate","decipher","deck","declaim","declare","declassify","decline","declutter","decode","decommission","decompose","decompress","deconsecrate","deconstruct","decontaminate","decontrol","decorate","decouple","decoy","decrease","decree","decriminalise","decriminalize","decry","decrypt","dedicate","deduce","deduct","deejay","deem","deepen","deface","defame","default","defeat","defecate","defect","defend","defer","defile","define","deflate","deflect","deflower","defog","defoliate","deforest","deform","defrag","defragment","defraud","defray","defrock","defrost","defuse","defy","degenerate","deglaze","degrade","degrease","dehumanise","dehumanize","dehydrate","deify","deign","delay","delegate","delete","deliberate","delight","delimit","delineate","deliquesce","deliver","delouse","delude","deluge","delve","demand","demarcate","demean","demerge","demilitarise","demilitarize","demineralise","demineralize","demist","demo","demob","demobilise","demobilize","democratise","democratize","demolish","demonise","demonize","demonstrate","demoralise","demoralize","demote","demotivate","demur","demystify","denationalise","denationalize","denigrate","denitrify","denominate","denote","denounce","dent","denude","deny","depart","depend","depersonalise","depersonalize","depict","deplane","deplete","deplore","deploy","depopulate","deport","depose","deposit","deprave","deprecate","depreciate","depress","depressurise","depressurize","deprive","depute","deputise","deputize","deracinate","derail","dereference","deregulate","deride","derive","derogate","descale","descend","describe","descry","desecrate","desegregate","deselect","desensitise","desensitize","desert","deserve","design","designate","desire","desist","deskill","desolate","despair","despise","despoil","destabilise","destabilize","destock","destroy","detach","detail","detain","detect","deter","deteriorate","determine","detest","dethrone","detonate","detour","detoxify","detract","detrain","devalue","devastate","develop","deviate","devise","devoice","devolve","devote","devour","diagnose","dial","dice","dicker","dictate","diddle","die","diet","differ","differentiate","diffract","diffuse","dig","digest","digitalise","digitalize","digitise","digitize","dignify","digress","dilate","dilute","diluted","dim","diminish","dimple","dine","ding","dink","dip","diphthongise","diphthongize","direct","dirty","dis","disable","disabuse","disadvantage","disaffiliate","disafforest","disagree","disallow","disambiguate","disappear","disappoint","disapprove","disarm","disarrange","disassemble","disassociate","disavow","disband","disbar","disbelieve","disburse","discard","discern","discharge","discipline","disclaim","disclose","discolor","discolour","discomfit","discomfort","discompose","disconcert","disconnect","discontinue","discount","discourage","discourse","discover","discredit","discriminate","discuss","disdain","disembark","disembowel","disenfranchise","disengage","disentangle","disestablish","disfigure","disgorge","disgrace","disguise","disgust","dish","dishearten","dishonor","dishonour","disillusion","disincentivise","disincentivize","disinfect","disinherit","disinhibit","disintegrate","disinter","disinvest","dislike","dislocate","dislodge","dismantle","dismay","dismember","dismiss","dismount","disobey","disorient","disorientate","disown","disparage","dispatch","dispel","dispense","disperse","displace","display","displease","disport","dispose","dispossess","disprove","dispute","disqualify","disregard","disrespect","disrobe","disrupt","dissect","dissemble","disseminate","dissent","dissimulate","dissipate","dissociate","dissolve","dissuade","distance","distend","distil","distill","distinguish","distort","distract","distress","distribute","distrust","disturb","disunite","ditch","dither","dive","diverge","diversify","divert","divest","divide","divine","divorce","divulge","divvy","do","dob","dock","doctor","document","dodge","doff","dog","dole","doll","dollarise","dollarize","domesticate","dominate","don","donate","doodle","doom","doorstep","dop","dope","dose","doss","dot","dote","double","doubt","douche","douse","dovetail","down","downchange","downgrade","downlink","download","downplay","downshift","downsize","dowse","doze","draft","drag","dragoon","drain","dramatise","dramatize","drape","draught","draw","drawl","dread","dream","dredge","drench","dress","dribble","drift","drill","drink","drip","drive","drivel","drizzle","drone","drool","droop","drop","drown","drowse","drug","drum","dry","dub","duck","duckie","ducks","duel","duff","dull","dumb","dumbfound","dummy","dump","dunk","dunt","dupe","duplicate","dust","dwarf","dwell","dwindle","dye","dynamite","earmark","earn","earth","ease","eat","eavesdrop","ebb","echo","eclipse","economise","economize","eddy","edge","edify","edit","editorialise","editorialize","educate","eff","efface","effect","effectuate","egg","ejaculate","eject","eke","elaborate","elapse","elbow","elect","electrify","electrocute","electroplate","elevate","elicit","elide","eliminate","elongate","elope","elucidate","elude","email","emanate","emancipate","emasculate","embalm","embargo","embark","embarrass","embed","embellish","embezzle","embitter","emblazon","embody","embolden","emboss","embrace","embroider","embroil","emcee","emend","emerge","emigrate","emit","emote","empathise","empathize","emphasise","emphasize","employ","empower","empty","emulate","emulsify","enable","enact","encamp","encapsulate","encase","encash","enchant","encircle","enclose","encode","encompass","encounter","encourage","encroach","encrypt","encumber","end","endanger","endear","endeavor","endeavour","endorse","endow","endure","energise","energize","enervate","enfeeble","enfold","enforce","enfranchise","engage","engender","engineer","engorge","engrave","engross","engulf","enhance","enjoin","enjoy","enlarge","enlighten","enlist","enliven","enmesh","ennoble","enquire","enrage","enrapture","enrich","enrol","enroll","ensconce","enshrine","enshroud","enslave","ensnare","ensue","ensure","entail","entangle","enter","entertain","enthral","enthrall","enthrone","enthuse","entice","entitle","entomb","entrance","entrap","entreat","entrench","entrust","entwine","enumerate","enunciate","envelop","envisage","envision","envy","epitomise","epitomize","equal","equalise","equalize","equate","equip","equivocate","eradicate","erase","erect","erode","err","erupt","escalate","escape","eschew","escort","espouse","espy","essay","establish","esteem","estimate","etch","eulogise","eulogize","euthanise","euthanize","evacuate","evade","evaluate","evangelise","evangelize","evaporate","even","eventuate","evict","evidence","evince","eviscerate","evoke","evolve","exacerbate","exact","exaggerate","exalt","examine","exasperate","excavate","exceed","excel","except","excerpt","exchange","excise","excite","exclaim","exclude","excommunicate","excoriate","excrete","exculpate","excuse","execute","exemplify","exempt","exercise","exert","exeunt","exfoliate","exhale","exhaust","exhibit","exhilarate","exhort","exhume","exile","exist","exit","exonerate","exorcise","exorcize","expand","expatiate","expect","expectorate","expedite","expel","expend","experience","experiment","expiate","expire","explain","explicate","explode","exploit","explore","export","expose","expostulate","expound","express","expropriate","expunge","expurgate","extemporise","extemporize","extend","exterminate","externalise","externalize","extinguish","extirpate","extol","extort","extract","extradite","extrapolate","extricate","extrude","exude","exult","eye","eyeball","eyeglasses","fabricate","face","facilitate","factor","factorise","factorize","fade","faff","fail","faint","fake","fall","falsify","falter","familiarise","familiarize","fan","fancy","fantasise","fantasize","fare","farewell","farm","farrow","fart","fascinate","fashion","fast","fasten","father","fathom","fatten","fault","favor","favour","fawn","fax","faze","fear","feast","feather","feature","federate","feed","feel","feign","feint","fell","fellate","feminise","feminize","fence","fend","ferment","ferret","ferry","fertilise","fertilize","fess","fester","festoon","fetch","fete","fetishise","fetishize","fetter","feud","fib","fictionalise","fictionalize","fiddle","fidget","field","fight","figure","filch","file","filibuster","fill","fillet","film","filter","finagle","finalise","finalize","finance","find","fine","finesse","finger","fingerprint","finish","fire","firebomb","firm","fish","fishtail","fit","fix","fizz","fizzle","flag","flagellate","flail","flake","flame","flank","flap","flare","flash","flat","flatline","flatten","flatter","flaunt","flavour","flay","fleck","flee","fleece","flesh","flex","flick","flicker","flight","flinch","fling","flip","flirt","flit","float","flock","flog","flood","floodlight","floor","flop","floss","flounce","flounder","flour","flourish","flout","flow","flower","flub","fluctuate","fluff","flummox","flunk","flush","fluster","flutter","fly","foal","foam","fob","focalise","focalize","focus","fog","foil","foist","fold","follow","foment","fondle","fool","foot","forage","forbear","forbid","force","ford","forearm","forecast","foreclose","foregather","foreground","foresee","foreshadow","foreshorten","forestall","foretell","forewarn","forfeit","forfend","forgather","forge","forget","forgive","forgo","fork","form","formalise","formalize","format","formulate","fornicate","forsake","forswear","fortify","forward","forwards","fossick","fossilise","fossilize","foster","foul","found","founder","fox","fracture","fragment","frame","franchise","frank","fraternise","fraternize","fray","freak","free","freelance","freeload","freestyle","freewheel","freeze","freight","frequent","freshen","fret","frighten","fringe","frisk","fritter","frizz","frizzle","frogmarch","frolic","front","frost","froth","frown","fruit","frustrate","fry","fuck","fudge","fuel","fulfil","fulfill","fulminate","fumble","fume","fumigate","function","fund","funk","funnel","furl","furlough","furnish","furrow","further","fuse","fuss","gab","gabble","gad","gag","gain","gainsay","gall","gallivant","gallop","galumph","galvanise","galvanize","gamble","gambol","gang","gape","garage","garden","gargle","garland","garner","garnish","garrison","garrote","garrotte","gas","gash","gasp","gatecrash","gather","gauge","gawk","gawp","gaze","gazump","gazunder","gear","gee","gel","geld","gen","generalise","generalize","generate","gentrify","genuflect","germinate","gerrymander","gestate","gesticulate","gesture","get","ghost","ghostwrite","gibber","gift","giggle","gild","ginger","gird","girdle","give","gladden","glamorise","glamorize","glance","glare","glass","glaze","gleam","glean","glide","glimmer","glimmering","glimpse","glint","glisten","glister","glitter","gloat","globalise","globalize","glom","glorify","glory","gloss","glow","glower","glue","glug","glut","gnash","gnaw","go","goad","gob","gobble","goggle","goldbrick","goof","google","goose","gore","gorge","gossip","gouge","govern","grab","grace","grade","graduate","graft","grant","grapple","grasp","grass","grate","gratify","gravitate","graze","grease","green","greet","grey","grieve","grill","grimace","grin","grind","grip","gripe","grit","grizzle","groan","grok","groom","grope","gross","grouch","ground","group","grouse","grout","grovel","grow","growl","grub","grudge","grumble","grunt","guarantee","guard","guess","guest","guffaw","guide","guillotine","guilt","gulp","gum","gun","gurgle","gurn","gush","gussy","gust","gut","gutter","guzzle","gybe","gyp","gyrate","hack","haemorrhage","haggle","hail","hallmark","halloo","hallucinate","halt","halve","ham","hammer","hamper","hamstring","hand","handcuff","handicap","handle","hang","hanker","happen","harangue","harass","harbor","harbour","harden","hare","hark","harm","harmonise","harmonize","harness","harp","harpoon","harrow","harrumph","harry","harvest","hash","hassle","hasten","hatch","hate","haul","haunt","have","haw","hawk","hazard","haze","head","headbutt","headhunt","headline","heal","heap","hear","hearken","hearten","heat","heave","heckle","hector","hedge","heed","heel","heft","heighten","heist","help","hem","hemorrhage","herald","herd","hesitate","hew","hex","hibernate","hiccough","hiccup","hide","hie","highball","highlight","hightail","hijack","hike","hinder","hinge","hint","hire","hiss","hit","hitch","hitchhike","hive","hoard","hoax","hobble","hobnob","hock","hoe","hog","hoick","hoist","hold","hole","holiday","holler","hollow","holster","home","homeschool","homestead","hone","honeymoon","honk","honour","hoodwink","hoof","hook","hoon","hoot","hoover","hop","hope","horn","horrify","horse","horsewhip","hose","hosepipe","hospitalise","hospitalize","host","hot","hotfoot","hound","house","hover","howl","huddle","huff","hug","hull","hum","humanise","humanize","humble","humiliate","humour","hump","hunch","hunger","hunker","hunt","hurdle","hurl","hurry","hurt","hurtle","husband","hush","husk","hustle","hybridise","hybridize","hydrate","hydroplane","hype","hyperventilate","hyphenate","hypnotise","hypnotize","hypothesise","hypothesize","ice","iconify","idealise","idealize","ideate","identify","idle","idolise","idolize","ignite","ignore","illuminate","illumine","illustrate","imagine","imagineer","imbibe","imbue","imitate","immerse","immigrate","immobilise","immobilize","immolate","immortalise","immortalize","immunise","immunize","immure","impact","impair","impale","impanel","impart","impeach","impede","impel","imperil","impersonate","impinge","implant","implement","implicate","implode","implore","imply","import","importune","impose","impound","impoverish","impregnate","impress","imprint","imprison","improve","improvise","impugn","inactivate","inaugurate","incapacitate","incarcerate","incarnate","incense","incentivise","incentivize","inch","incinerate","incise","incite","incline","include","incommode","inconvenience","incorporate","increase","incriminate","incubate","inculcate","incur","indemnify","indent","index","indicate","indict","individualise","individualize","individuate","indoctrinate","induce","induct","indulge","industrialise","industrialize","infantilise","infantilize","infect","infer","infest","infill","infiltrate","inflame","inflate","inflect","inflict","influence","inform","infringe","infuriate","infuse","ingest","ingratiate","inhabit","inhale","inhere","inherit","inhibit","initial","initialise","initialize","initiate","inject","injure","ink","inlay","innovate","inoculate","input","inscribe","inseminate","insert","inset","insinuate","insist","inspect","inspire","install","instance","instigate","instil","instill","institute","institutionalise","institutionalize","instruct","insulate","insult","insure","integrate","intend","intensify","inter","interact","interbreed","intercede","intercept","interchange","interconnect","intercut","interest","interface","interfere","interject","interlace","interleave","interlink","interlock","intermarry","intermesh","intermingle","intermix","intern","internalise","internalize","internationalise","internationalize","interpenetrate","interpolate","interpose","interpret","interrelate","interrogate","interrupt","intersect","intersperse","intertwine","intervene","interview","interweave","interwork","intimate","intimidate","intone","intoxicate","intrigue","introduce","intrude","intubate","intuit","inundate","inure","invade","invalid","invalidate","inveigh","inveigle","invent","inventory","invert","invest","investigate","invigilate","invigorate","invite","invoice","invoke","involve","ionise","ionize","irk","iron","irradiate","irrigate","irritate","irrupt","isolate","issue","italicise","italicize","itch","itemise","itemize","iterate","jab","jabber","jack","jackknife","jail","jam","jangle","jar","jaw","jaywalk","jazz","jeer","jell","jeopardise","jeopardize","jerk","jest","jet","jettison","jib","jibe","jig","jiggle","jilt","jingle","jink","jinx","jive","jockey","jog","joggle","join","joint","joke","jol","jolly","jolt","josh","jostle","jot","journey","joust","judder","judge","juggle","juice","jumble","jump","junk","justify","jut","juxtapose","keel","keelhaul","keen","keep","ken","key","keyboard","kibitz","kick","kid","kidnap","kill","kindle","kink","kip","kiss","kit","kite","klap","kludge","knacker","knead","knee","kneecap","kneel","knife","knight","knit","knock","knot","know","knuckle","kowtow","kvetch","label","labour","lace","lacerate","lack","lacquer","lactate","ladder","ladle","lag","lam","lamb","lambast","lambaste","lament","lamp","lampoon","lance","land","lands","landscape","languish","lap","lapse","lard","large","lark","lash","lasso","last","latch","lather","laud","laugh","launch","launder","lavish","lay","layer","laze","leach","lead","leaf","leaflet","leak","lean","leap","leapfrog","learn","lease","leash","leave","leaven","lech","lecture","leer","leg","legalise","legalize","legislate","legitimise","legitimize","lend","lengthen","lessen","let","letter","letterbox","level","lever","leverage","levitate","levy","liaise","libel","liberalise","liberalize","liberate","license","lick","lie","lift","ligate","light","lighten","like","liken","limber","lime","limit","limp","line","linger","link","lionise","lionize","liquefy","liquidate","liquidise","liquidize","lisp","list","listen","litigate","litter","live","liven","load","loads","loaf","loan","loathe","lob","lobby","lobotomise","lobotomize","localise","localize","locate","lock","lodge","loft","log","loiter","loll","lollop","long","look","looks","loom","loop","loose","loosen","loot","lop","lope","lord","lose","lounge","lour","louse","love","low","lowball","lower","lubricate","luck","lug","lull","lumber","lump","lunch","lunge","lurch","lure","lurk","lust","luxuriate","lynch","macerate","machine","madden","magic","magnetise","magnetize","magnify","mail","maim","mainline","mainstream","maintain","major","make","malfunction","malign","malinger","maltreat","man","manacle","manage","mandate","mangle","manhandle","manicure","manifest","manipulate","manoeuvre","mantle","manufacture","manure","map","mar","march","marginalise","marginalize","marinate","mark","market","maroon","marry","marshal","martyr","marvel","masculinise","masculinize","mash","mask","masquerade","mass","massacre","massage","master","mastermind","masticate","masturbate","match","mate","materialise","materialize","matriculate","matter","mature","maul","maunder","max","maximise","maximize","mean","meander","measure","mechanise","mechanize","medal","meddle","mediate","medicate","meditate","meet","meld","mellow","melt","memorialise","memorialize","memorise","memorize","menace","mend","menstruate","mention","meow","mercerise","mercerize","merchandise","merge","merit","mesh","mesmerise","mesmerize","mess","message","metabolise","metabolize","metamorphose","mete","meter","methinks","mew","mewl","miaow","microblog","microchip","micromanage","microwave","micturate","migrate","militarise","militarize","militate","milk","mill","mime","mimic","mince","mind","mine","mingle","miniaturise","miniaturize","minimise","minimize","minister","minor","mint","minute","mirror","misapply","misappropriate","misbehave","miscalculate","miscarry","miscast","misconceive","misconstrue","miscount","misdiagnose","misdial","misdirect","misfile","misfire","misgovern","mishandle","mishear","mishit","misinform","misinterpret","misjudge","miskey","mislay","mislead","mismanage","mismatch","misname","misplace","misplay","mispronounce","misquote","misread","misreport","misrepresent","miss","mission","misspell","misspend","mist","mistake","mistime","mistreat","mistrust","misunderstand","misuse","mitigate","mitre","mix","moan","mob","mobilise","mobilize","mock","mod","model","moderate","modernise","modernize","modify","modulate","moisten","moisturise","moisturize","mold","molder","molest","mollify","mollycoddle","molt","monitor","monopolise","monopolize","moo","mooch","moon","moonlight","moonwalk","moor","moot","mop","mope","moralise","moralize","morph","mortar","mortgage","mortify","mosey","mosh","mothball","mother","motion","motivate","motor","mould","moulder","moult","mount","mourn","mouse","mouth","move","movies","mow","muck","muddle","muddy","muff","muffle","mug","mulch","mull","multicast","multiply","multitask","mumble","mumbling","mummify","munch","murder","murmur","murmuring","murmurings","muscle","muse","mushroom","muss","muster","mutate","mute","mutilate","mutiny","mutter","muzzle","mystify","nab","nag","nail","name","namecheck","nap","narrate","narrow","narrowcast","nasalise","nasalize","nationalise","nationalize","natter","naturalise","naturalize","nauseate","navigate","near","nearer","nearest","neaten","necessitate","neck","necklace","need","needle","negate","negative","neglect","negotiate","neigh","nerve","nest","nestle","net","nettle","network","neuter","neutralise","neutralize","nibble","nick","nickname","niggle","nip","nitrify","nix","nobble","nod","nominalize","nominate","norm","normalise","normalize","nose","nosedive","nosh","notarise","notarize","notch","note","notice","notify","nourish","nudge","nuke","nullify","numb","number","nurse","nurture","nut","nuzzle","obey","obfuscate","object","objectify","oblige","obliterate","obscure","observe","obsess","obstruct","obtain","obtrude","obviate","occasion","occlude","occupy","occur","off","offend","offer","officiate","offload","offset","offshore","ogle","oil","okay","omit","ooze","open","operate","opine","oppose","oppress","opt","optimise","optimize","option","orbit","orchestrate","ordain","order","organise","organize","orient","orientate","originate","ornament","orphan","oscillate","ossify","ostracise","ostracize","oust","out","outbid","outclass","outdistance","outdo","outface","outfit","outflank","outfox","outgrow","outgun","outlast","outlaw","outline","outlive","outmaneuver","outmanoeuvre","outnumber","outpace","outperform","outplay","outpoint","output","outrage","outrank","outrun","outsell","outshine","outsmart","outsource","outstay","outstrip","outvote","outweigh","outwit","overachieve","overact","overawe","overbalance","overbook","overburden","overcharge","overcome","overcompensate","overcook","overdevelop","overdo","overdose","overdraw","overdub","overeat","overemphasize","overestimate","overexpose","overextend","overfeed","overflow","overfly","overgeneralise","overgeneralize","overgraze","overhang","overhaul","overhear","overheat","overindulge","overlap","overlay","overlie","overload","overlook","overpay","overplay","overpower","overprint","overproduce","overrate","overreach","overreact","override","overrule","overrun","oversee","oversell","overshadow","overshoot","oversimplify","oversleep","overspend","overstate","overstay","overstep","overstock","overstretch","overtake","overtax","overthrow","overtrain","overturn","overuse","overvalue","overwhelm","overwinter","overwork","overwrite","ovulate","owe","own","oxidise","oxidize","oxygenate","pace","pacify","pack","package","packetise","packetize","pad","paddle","padlock","page","paginate","pailful","pain","paint","pair","pal","palatalise","palatalize","pale","pall","palliate","palm","palpate","palpitate","pamper","pan","pander","panel","panhandle","panic","pant","paper","parachute","parade","parallel","paralyse","paralyze","paraphrase","parboil","parcel","parch","pardon","pare","park","parlay","parley","parody","parole","parrot","parry","parse","part","partake","participate","particularise","particularize","partition","partner","party","pass","passivise","passivize","paste","pasteurise","pasteurize","pasture","pat","patch","patent","patrol","patronise","patronize","patter","pattern","pause","pave","paw","pawn","pay","peak","peal","peck","pedal","peddle","pedestrianise","pedestrianize","pee","peek","peel","peep","peer","peg","pelt","pen","penalise","penalize","pencil","penetrate","pension","people","pep","pepper","perambulate","perceive","perch","percolate","perfect","perforate","perform","perfume","perish","perjure","perk","perm","permeate","permit","perpetrate","perpetuate","perplex","persecute","persevere","persist","personalise","personalize","personify","perspire","persuade","pertain","perturb","peruse","pervade","pervert","pester","pet","peter","petition","petrify","phase","philosophise","philosophize","phone","photocopy","photograph","photoshop","photosynthesise","photosynthesize","phrase","pick","picket","pickle","picnic","picture","picturise","picturize","piddle","piece","pierce","pig","pigeonhole","piggyback","pike","pile","pilfer","pill","pillage","pillory","pillow","pilot","pimp","pin","pinch","pine","ping","pinion","pink","pinpoint","pioneer","pip","pipe","pique","pirate","pirouette","piss","pit","pitch","pity","pivot","pixelate","pixellate","placate","place","plagiarise","plagiarize","plague","plait","plan","plane","plant","plaster","plasticise","plasticize","plate","plateau","play","plead","please","pledge","plight","plod","plonk","plop","plot","plough","pluck","plug","plumb","plummet","plump","plunder","plunge","plunk","pluralise","pluralize","ply","poach","pocket","point","poise","poison","poke","polarise","polarize","pole","poleax","poleaxe","police","polish","politicise","politicize","poll","pollard","pollinate","pollute","polymerise","polymerize","ponce","ponder","pong","pontificate","pony","poo","pooh","pool","poop","pootle","pop","popularise","popularize","populate","pore","port","portend","portion","portray","pose","posit","position","possess","posset","post","postmark","postpone","postulate","posture","pot","potter","pounce","pound","pour","pout","powder","power","practice","practise","praise","praises","prance","prang","prate","prattle","pray","preach","precede","precipitate","precis","preclude","predate","predecease","predetermine","predicate","predict","predispose","predominate","preen","preface","prefer","prefigure","prefix","preheat","prejudge","prejudice","preload","premaster","premiere","preoccupy","prep","prepare","prepone","preregister","presage","prescind","prescribe","preselect","presell","present","preserve","preset","preside","press","pressure","pressurise","pressurize","presume","presuppose","pretend","pretest","prettify","prevail","prevaricate","prevent","preview","prey","price","prick","prickle","pride","prime","primp","print","prioritise","prioritize","prise","privatise","privatize","privilege","prize","probate","probe","proceed","process","proclaim","procrastinate","procreate","proctor","procure","prod","produce","profane","profess","professionalise","professionalize","proffer","profile","profit","program","programme","progress","prohibit","project","proliferate","prolong","promenade","promise","promote","prompt","promulgate","pronounce","proof","proofread","prop","propagandise","propagandize","propagate","propel","prophesy","propitiate","propose","proposition","propound","proscribe","prosecute","proselytise","proselytize","prospect","prosper","prostitute","prostrate","protect","protest","protrude","prove","provide","provision","provoke","prowl","prune","pry","psych","psychoanalyse","publicise","publicize","publish","pucker","puff","puke","pull","pullulate","pulp","pulsate","pulse","pulverise","pulverize","pummel","pump","pun","punch","punctuate","puncture","punish","punt","pupate","purchase","purge","purify","purl","purloin","purport","purr","purse","pursue","purvey","push","pussyfoot","put","putrefy","putt","putter","puzzle","quack","quadruple","quaff","quail","quake","qualify","quantify","quarantine","quarrel","quarry","quarter","quarterback","quash","quaver","queer","quell","quench","query","quest","question","queue","quibble","quicken","quiet","quieten","quintuple","quip","quirk","quit","quiver","quiz","quote","quoth","rabbit","race","rack","radiate","radicalise","radicalize","radio","raffle","rag","rage","raid","rail","railroad","rain","raise","rake","rally","ram","ramble","ramp","rampage","randomise","randomize","range","rank","rankle","ransack","ransom","rant","rap","rape","rappel","rasp","rasterise","rasterize","rat","ratchet","rate","ratify","ration","rationalise","rationalize","rattle","ravage","rave","ravel","ravish","raze","razz","reach","reacquaint","react","reactivate","read","readdress","readies","readjust","readmit","ready","reaffirm","realign","realise","realize","reallocate","ream","reanimate","reap","reappear","reapply","reappoint","reappraise","rear","rearm","rearrange","reason","reassemble","reassert","reassess","reassign","reassure","reawaken","rebel","reboot","reborn","rebound","rebrand","rebuff","rebuild","rebuke","rebut","recall","recant","recap","recapitulate","recapture","recast","recede","receive","recess","recharge","reciprocate","recite","reckon","reclaim","reclassify","recline","recognise","recognize","recoil","recollect","recommence","recommend","recompense","reconcile","recondition","reconfigure","reconfirm","reconnect","reconnoitre","reconquer","reconsider","reconstitute","reconstruct","reconvene","record","recount","recoup","recover","recreate","recrudesce","recruit","rectify","recuperate","recur","recycle","redact","redden","redecorate","redeem","redefine","redeploy","redesign","redevelop","redial","redirect","rediscover","redistribute","redistrict","redo","redouble","redound","redraft","redraw","redress","reduce","reduplicate","reef","reek","reel","ref","refer","referee","reference","refill","refinance","refine","refit","reflate","reflect","refloat","refocus","reform","reformat","reformulate","refract","refrain","refresh","refrigerate","refuel","refund","refurbish","refuse","refute","regain","regale","regard","regenerate","register","regress","regret","regroup","regularise","regularize","regulate","regurgitate","rehabilitate","rehash","rehear","rehearse","reheat","rehome","rehouse","reign","reignite","reimburse","rein","reincarnate","reinforce","reinstate","reinterpret","reintroduce","reinvent","reinvest","reinvigorate","reissue","reiterate","reject","rejig","rejigger","rejoice","rejoin","rejuvenate","rekindle","relapse","relate","relaunch","relax","relay","release","relegate","relent","relieve","relinquish","relish","relive","reload","relocate","rely","remain","remainder","remake","remand","remap","remark","remarry","remaster","remediate","remedy","remember","remind","reminisce","remit","remix","remodel","remonstrate","remortgage","remould","remount","remove","remunerate","rename","rend","render","rendezvous","renege","renew","renounce","renovate","rent","reoccur","reoffend","reopen","reorder","reorganise","reorganize","reorient","repackage","repair","repatriate","repay","repeal","repeat","repel","repent","rephrase","replace","replay","replenish","replicate","reply","report","repose","repossess","represent","repress","reprieve","reprimand","reprint","reproach","reprocess","reproduce","reprove","repudiate","repulse","repurpose","request","require","requisition","requite","rerun","reschedule","rescind","rescue","research","researches","resect","resell","resemble","resent","reserve","reset","resettle","reshape","reshuffle","reside","resign","resist","resit","resize","reskill","resolve","resonate","resort","resound","resource","respect","respire","respond","respray","rest","restart","restate","restock","restore","restrain","restrict","restring","restructure","result","resume","resupply","resurface","resurrect","resuscitate","retail","retain","retake","retaliate","retard","retch","retell","retest","rethink","retire","retool","retort","retouch","retrace","retract","retrain","retreat","retrench","retrieve","retrofit","retry","return","reunify","reunite","reuse","rev","revalue","revamp","reveal","revel","revenge","reverberate","revere","reverse","revert","review","revile","revise","revisit","revitalise","revitalize","revive","revivify","revoke","revolt","revolutionise","revolutionize","revolve","reward","rewind","rewire","reword","rework","rewrite","rhapsodise","rhapsodize","rhyme","rib","rick","ricochet","rid","riddle","ride","ridge","ridicule","riffle","rifle","rig","right","rightsize","rile","rim","ring","rinse","riot","rip","ripen","riposte","ripple","rise","risk","ritualise","ritualize","rival","rivet","roam","roar","roast","rob","robe","rock","rocket","roger","roll","romance","romanticise","romanticize","romp","roof","room","roost","root","rope","rosin","roster","rot","rotate","rouge","rough","roughen","roughhouse","round","rouse","roust","rout","route","rove","row","rub","rubberneck","rubbish","ruck","rue","ruffle","ruin","ruins","rule","rumble","ruminate","rummage","rumor","rumour","rumple","run","rupture","rush","rust","rustle","sabotage","sack","sacrifice","sadden","saddle","safeguard","sag","sail","salaam","salivate","sally","salt","salute","salvage","salve","sample","sanctify","sanction","sand","sandbag","sandblast","sandpaper","sandwich","sanitise","sanitize","sap","sashay","sass","sate","satiate","satirise","satirize","satisfy","saturate","saunter","savage","save","savor","savour","saw","say","scald","scale","scallop","scalp","scamper","scan","scandalise","scandalize","scapegoat","scar","scare","scarf","scarify","scarper","scatter","scattering","scavenge","scent","schedule","schematise","schematize","scheme","schlep","schlepp","schmooze","school","schtup","schuss","scoff","scold","scoop","scoot","scope","scorch","score","scorn","scotch","scour","scourge","scout","scowl","scrabble","scram","scramble","scrap","scrape","scratch","scrawl","scream","screech","screen","screw","scribble","scrimp","script","scroll","scrounge","scrub","scrummage","scrunch","scruple","scrutinise","scrutinize","scud","scuff","scuffle","scull","sculpt","scupper","scurry","scuttle","scythe","seal","sealift","sear","search","season","seat","secede","seclude","second","secrete","section","secularise","secularize","secure","sedate","seduce","see","seed","seek","seep","seethe","segment","segregate","segue","seize","select","sell","sellotape","semaphore","send","sensationalise","sensationalize","sense","sensitise","sensitize","sentence","sentimentalise","sentimentalize","separate","sequence","sequester","sequestrate","serenade","serialise","serialize","sermonise","sermonize","serve","service","set","settle","sever","sew","sex","sexualise","sexualize","shack","shackle","shade","shadow","shaft","shag","shake","shalt","sham","shamble","shame","shampoo","shanghai","shape","share","sharpen","shatter","shave","shear","sheathe","shed","sheer","shell","shellac","shelter","shelve","shepherd","shield","shift","shimmer","shimmy","shin","shine","shinny","ship","shipwreck","shirk","shit","shiver","shock","shoe","shoehorn","shoo","shoot","shop","shoplift","shore","short","shorten","shortlist","shoulder","shout","shove","shovel","show","showboat","showcase","shower","shred","shriek","shrill","shrink","shrivel","shroom","shroud","shrug","shtup","shuck","shudder","shuffle","shun","shunt","shush","shut","shuttle","shy","sic","sick","sicken","side","sideline","sidestep","sideswipe","sidetrack","sidle","sieve","sift","sigh","sight","sightsee","sign","signal","signify","signpost","silence","silhouette","silt","silver","simmer","simper","simplify","simulate","simulcast","sin","sing","singe","single","sink","sip","siphon","sire","sit","site","situate","size","sizzle","skate","skateboard","skedaddle","sketch","skew","skewer","ski","skid","skim","skimp","skin","skip","skipper","skirmish","skirt","skitter","skive","skivvy","skulk","sky","skyjack","skyrocket","slack","slacken","slag","slake","slam","slander","slant","slap","slash","slate","slather","slaughter","slave","slaver","slay","sledge","sleek","sleep","sleepwalk","sleet","slew","slice","slick","slide","slight","slim","sling","slink","slip","slit","slither","slob","slobber","slog","slop","slope","slosh","slot","slouch","slough","slow","slug","sluice","slum","slumber","slump","slur","slurp","smack","smart","smarten","smash","smear","smell","smelt","smile","smirk","smite","smoke","smooch","smoodge","smooth","smother","smoulder","smudge","smuggle","snack","snaffle","snag","snaggle","snake","snap","snare","snarf","snarl","snatch","sneak","sneer","sneeze","snicker","sniff","sniffle","snigger","snip","snipe","snitch","snivel","snog","snooker","snoop","snooper","snooze","snore","snorkel","snort","snow","snowball","snowplough","snowplow","snub","snuff","snuffle","snuffling","snuggle","soak","soap","soar","sob","sober","socialise","socialize","sock","sod","sodomise","sodomize","soften","soil","sojourn","solace","solder","soldier","sole","solemnise","solemnize","solicit","solidify","soliloquize","solve","somersault","soothe","sorrow","sort","sough","sound","soundproof","soup","sour","source","souse","sow","space","span","spangle","spank","spar","spare","spark","sparkle","spatter","spattering","spawn","spay","speak","spear","spearhead","spec","specialise","specialize","specify","spectacles","spectate","speculate","speed","spell","spellcheck","spend","spew","spice","spiff","spike","spill","spin","spiral","spirit","spit","spite","splash","splatter","splay","splice","splinter","split","splosh","splurge","splutter","spoil","sponge","sponsor","spoof","spook","spool","spoon","sport","sports","spot","spotlight","spout","sprain","sprawl","spray","spread","spreadeagle","spring","springboard","sprinkle","sprint","spritz","sprout","spruce","spur","spurn","spurt","sputter","spy","squabble","squall","squander","square","squash","squat","squawk","squeak","squeal","squeeze","squelch","squint","squirm","squirrel","squirt","squish","stab","stabilise","stabilize","stable","stables","stack","staff","stage","stagger","stagnate","stain","stake","stalk","stall","stammer","stamp","stampede","stanch","stand","standardise","standardize","staple","star","starch","stare","start","startle","starve","stash","state","statement","station","staunch","stave","stay","steady","steal","steam","steamroller","steel","steep","steepen","steer","stem","stencil","step","stereotype","sterilise","sterilize","stew","stick","stickybeak","stiff","stiffen","stifle","stigmatise","stigmatize","still","stimulate","sting","stinger","stink","stint","stipple","stipulate","stir","stitch","stock","stockpile","stoke","stomach","stomp","stone","stonewall","stoop","stop","stopper","store","storm","storyboard","stow","straddle","strafe","straggle","straighten","strain","strand","strangle","strap","stratify","stravage","stravaig","stray","streak","stream","streamline","strengthen","stress","stretch","stretcher","strew","stride","strike","string","strip","strive","stroke","stroll","structure","struggle","strum","strut","stub","stud","study","stuff","stultify","stumble","stump","stun","stunt","stupefy","stutter","style","stymie","sub","subcontract","subdivide","subdue","subedit","subject","subjugate","sublet","sublimate","submerge","submit","subordinate","suborn","subpoena","subscribe","subside","subsidise","subsidize","subsist","substantiate","substitute","subsume","subtend","subtitle","subtract","subvert","succeed","succor","succour","succumb","suck","sucker","suckle","suction","sue","suffer","suffice","suffocate","suffuse","sugar","suggest","suit","sulk","sulks","sully","sum","summarise","summarize","summon","summons","sun","sunbathe","sunder","sunset","sup","superimpose","superintend","superpose","supersede","supersize","supersized","supervene","supervise","supplant","supplement","supply","support","suppose","suppress","suppurate","surcharge","surf","surface","surge","surmise","surmount","surpass","surprise","surrender","surround","survey","survive","suspect","suspend","suspenders","suss","sustain","suture","swab","swaddle","swagger","swallow","swamp","swan","swank","swap","swarm","swat","swath","swathe","sway","swear","sweat","sweep","sweeps","sweeten","swell","swelter","swerve","swig","swill","swim","swindle","swing","swipe","swirl","swish","switch","swivel","swoon","swoop","swoosh","swot","symbolise","symbolize","sympathise","sympathize","symptomize","synchronise","synchronize","syndicate","synthesise","synthesize","syringe","systematise","systematize","tab","table","tabulate","tack","tackle","tag","tail","tailgate","tailor","taint","take","talk","tally","tame","tamp","tamper","tan","tangle","tango","tank","tankful","tantalise","tantalize","tap","tape","taper","tar","target","tarmac","tarnish","tarry","tart","task","taste","tattle","tattoo","taunt","tauten","tax","taxi","taxicab","teach","team","tear","tease","tee","teem","teeter","teethe","telecast","telecommute","teleconference","telegraph","telemeter","teleoperate","telephone","teleport","telescope","televise","telex","tell","telnet","temp","temper","temporise","temporize","tempt","tenant","tend","tender","tenderise","tenderize","tense","tension","tergiversate","term","terminate","terraform","terrify","terrorise","terrorize","test","testify","tether","text","thank","thatch","thaw","theorise","theorize","thicken","thin","think","thirst","thrash","thread","threaten","thresh","thrill","thrive","throb","throbbing","throng","throttle","throw","thrust","thud","thumb","thump","thunder","thwack","thwart","tick","ticket","tickle","tide","tidy","tie","tighten","tile","till","tilt","time","timetable","tinge","tingle","tingling","tinker","tinkle","tinkling","tint","tip","tippex","tipple","tiptoe","tire","titillate","titivate","title","titrate","titter","toady","toast","toboggan","toddle","toe","tog","toggle","toil","toke","tolerate","toll","tone","tongue","tonify","tool","toot","tootle","top","topple","torch","torment","torpedo","torture","toss","tot","total","tote","totter","touch","tough","toughen","tour","tousle","tout","tow","towel","tower","toy","trace","track","trade","traduce","traffic","trail","train","traipse","trammel","tramp","trample","trampoline","tranquilize","tranquillize","transact","transcend","transcribe","transfer","transfigure","transfix","transform","transfuse","transgress","transit","translate","transliterate","transmit","transmogrify","transmute","transpire","transplant","transport","transpose","trap","trash","traumatise","traumatize","travel","traverse","trawl","tread","treasure","treat","treble","trek","tremble","trembling","trepan","trespass","trial","trick","trickle","trifle","trigger","trill","trim","trip","triple","triumph","trivialise","trivialize","troll","tromp","troop","trot","trouble","troubleshoot","trounce","trouser","truant","truck","trudge","trump","trumpet","truncate","trundle","truss","trust","try","tuck","tug","tugboat","tumble","tune","tunnel","turbocharge","turf","turn","tussle","tut","tutor","twang","tweak","tweet","twiddle","twig","twin","twine","twinkle","twirl","twist","twitch","twitter","twittering","type","typecast","typeset","typify","tyrannise","tyrannize","ulcerate","ululate","ump","umpire","unbalance","unban","unbend","unblock","unbuckle","unburden","unbutton","uncoil","uncork","uncouple","uncover","uncurl","undelete","underachieve","underbid","undercharge","undercook","undercut","underestimate","underestimation","underexpose","undergo","underlie","underline","undermine","underpay","underperform","underpin","underplay","underrate","underscore","undersell","undershoot","underspend","understand","understate","understudy","undertake","undervalue","underwrite","undo","undock","undress","undulate","unearth","unfasten","unfold","unfreeze","unfurl","unhand","unhinge","unhitch","unhook","unify","uninstall","unionise","unionize","unite","unlace","unlearn","unleash","unload","unlock","unloose","unloosen","unmask","unnerve","unpack","unpick","unplug","unravel","unroll","unsaddle","unscramble","unscrew","unseat","unsettle","unsubscribe","untangle","untie","unveil","unwind","unwrap","unzip","up","upbraid","upchange","upchuck","update","upend","upgrade","uphold","upholster","uplift","upload","uproot","upsell","upset","upshift","upskill","upstage","urge","urinate","use","usher","usurp","utilise","utilize","utter","vacate","vacation","vaccinate","vacillate","vacuum","valet","validate","value","vamoose","vandalise","vandalize","vanish","vanquish","vaporise","vaporize","varnish","vary","vault","veer","veg","vegetate","veil","vend","veneer","venerate","vent","ventilate","venture","verbalise","verbalize","verge","verify","versify","vest","vet","veto","vex","vibrate","victimise","victimize","vide","video","videotape","vie","view","viewing","vilify","vindicate","violate","visit","visualise","visualize","vitiate","vitrify","vocalize","voice","void","volley","volumise","volumize","volunteer","vomit","vote","vouch","vouchsafe","vow","voyage","vulgarise","vulgarize","wad","waddle","wade","waffle","waft","wag","wage","wager","waggle","wail","wait","waive","wake","wakeboard","waken","walk","wall","wallop","wallow","wallpaper","waltz","wander","wane","wangle","wank","want","warble","ward","warm","warn","warp","warrant","wash","wassail","waste","watch","water","waterproof","waterski","wave","waver","wax","waylay","weaken","wean","weaponise","weaponize","wear","weary","weasel","weather","weatherise","weatherize","weave","wed","wedge","wee","weed","weekend","weep","weigh","weight","weird","welch","welcome","weld","well","welly","welsh","wend","westernise","westernize","wet","whack","wheedle","wheel","wheeze","whelp","whet","whiff","while","whilst","whimper","whine","whinge","whinny","whip","whirl","whirr","whirring","whisk","whisper","whispering","whistle","whiten","whitewash","whittle","whiz","whizz","whoop","whoosh","whup","wick","widen","widow","wield","wig","wiggle","wildcat","will","wilt","wimp","win","wince","winch","wind","winds","windsurf","wine","wing","wink","winkle","winnow","winter","wipe","wire","wiretap","wise","wisecrack","wish","withdraw","wither","withhold","withstand","witness","witter","wobble","wolf","wonder","woo","woof","word","work","worm","worry","worsen","worship","worst","wound","wow","wowee","wrangle","wrap","wreak","wreathe","wreck","wrench","wrest","wrestle","wriggle","wring","wrinkle","writ","write","writhe","wrong","wrought","xerox","yack","yak","yank","yap","yaw","yawn","yearn","yell","yellow","yelp","yield","yodel","yoke","yomp","yowl","yuppify","zap","zero","zigzag","zing","zip","zone","zoom"];var Kd=Object.freeze({adjective:xn,adverb:On,conjunction:Pn,interjection:In,noun:Nn,preposition:$n,verb:Rn}),jn=Kd;var qd=Object.freeze({title:"English",syntax:gn,time:fn,internet:vn,person:En,word:jn}),fe=qd;var At=["male","female"],Pe=Symbol("randomValue"),lr=Symbol("typesValue"),rt=Symbol("localeValue"),Cs=class{[lr];[Pe];[rt];constructor(e={}){this[lr]=new it(e.seed),this[Pe]=new Qt(e.seed),this[rt]=e.locale||fe}seed(e){this[Pe].seed(e),this[lr].seed(e)}locale(e){this[rt]=e||fe}firstName(e){let{person:t}=this[rt],i=e&&At.includes(e)?e:this[Pe].pickOne(At),r;t&&t.firstName&&t.firstName[i]?r=t.firstName:r=fe.person.firstName;let s=r[i];return this[Pe].pickOne(s)}lastName(e){let{person:t}=this[rt];if(!e){let o=t&&t.lastName||fe.person.lastName;if(Array.isArray(o.general)&&o.general.length)return this[Pe].pickOne(o.general);throw new Error("The locale does not have a general last name pool.")}let i=e&&At.includes(e)?e:this[Pe].pickOne(At),r;t&&t.lastName&&t.lastName[i]?r=t.lastName:r=fe.person.lastName;let s=r[i];return this[Pe].pickOne(s)}middleName(e){let{person:t}=this[rt],i=t&&t.middleName||t&&t.firstName||fe.person.firstName,r=e&&At.includes(e)?e:this[Pe].pickOne(At),s=i[r];return this[Pe].pickOne(s)}name(e={}){let{firstName:t,lastName:i,gender:r}=e,s=[];return this[lr].boolean({likelihood:10})&&s.push(this.prefix(r)),s.push(t||this.firstName(r)),s.push(i||this.lastName(r)),this[lr].boolean({likelihood:10})&&s.push(this.suffix(r)),s.join(" ")}gender(e){let{person:t}=this[rt],i=t&&t.gender||fe.person.gender;return e?this[Pe].pickOne(i.binary||fe.person.gender.binary):this[Pe].pickOne(i.pool||fe.person.gender.pool)}prefix(e){let{person:t}=this[rt],i=t&&t.prefix||fe.person.prefix;if(!e&&Array.isArray(i.general)&&i.general.length)return this[Pe].pickOne(i.general);let r=e&&At.includes(e)?e:this[Pe].pickOne(At),s=i[r]||fe.person.prefix[r];return this[Pe].pickOne(s)}suffix(e){let{person:t}=this[rt],i=t&&t.suffix||fe.person.suffix;if(Array.isArray(i.general)&&i.general.length)return this[Pe].pickOne(i.general);let r=e&&At.includes(e)?e:this[Pe].pickOne(At),s=i[r]||fe.person.suffix[r];return this[Pe].pickOne(s)}jobTitle(){let e=this.jobDescriptor(),t=this.jobArea(),i=this.jobType();return`${e} ${t} ${i}`}jobDescriptor(){let{person:e}=this[rt],t;return e&&e.title&&e.title.descriptor?t=e.title:t=fe.person.title,this[Pe].pickOne(t.descriptor)}jobArea(){let{person:e}=this[rt],t;return e&&e.title&&e.title.level?t=e.title:t=fe.person.title,this[Pe].pickOne(t.level)}jobType(){let{person:e}=this[rt],t;return e&&e.title&&e.title.job?t=e.title:t=fe.person.title,this[Pe].pickOne(t.job||[])}};var Ts=Symbol("randomValue"),st=Symbol("typesValue"),Ds=Symbol("localeValue"),Ms=class{[st];[Ts];[Ds];constructor(e={}){this[st]=new it(e.seed),this[Ts]=new Qt(e.seed),this[Ds]=e.locale||fe}seed(e){this[Ts].seed(e),this[st].seed(e)}locale(e){this[Ds]=e||fe}word(e={}){let t={...e};if(typeof t.syllables=="number"&&typeof t.length=="number")throw new RangeError('Cannot specify both "syllables" and "length".');let i="";if(typeof t.length=="number"){do i+=this.syllable();while(i.length<t.length);i=i.substring(0,t.length)}else{let r=t.syllables||this[st].number({min:1,max:3});for(let s=0;s<r;s++)i+=this.syllable()}return t.capitalize&&(i=this.capitalize(i)),i}capitalize(e){return e.charAt(0).toUpperCase()+e.substr(1)}words(e=3){return new Array(e).fill("").map(()=>this.word()).join(" ")}sentence(e={}){let t={...e},{words:i=this[st].number({min:12,max:18})}=t,r=new Array(i).fill("").map(()=>this.word()).join(" ");r=this.capitalize(r);let{punctuation:s}=t;return s!==!1&&!/^[.?;!:]$/.test(String(s))&&(s="."),s&&(r+=s),r}sentences(e={}){let t={};typeof e=="number"?t.size=e:t={...e};let{size:i=this[st].number({min:2,max:6})}=t;return new Array(i).fill("").map(()=>this.sentence()).join(" ")}slug(e){let t=this.words(e);return ln(t)}paragraph(e={}){let t={};typeof e=="number"?t.sentences=e:t={...e};let{lineBreak:i,sentences:r=this[st].number({min:3,max:7})}=t;return new Array(r).fill("").map(()=>this.sentence()).join(i===!0?`\r
35
35
  `:" ")}paragraphs(e={}){let t={};typeof e=="number"?t.size=e:t={...e};let{separator:i=`\r
36
- `,size:r=this[rt].number({min:1,max:7})}=t;return new Array(r).fill("").map(()=>this.paragraph()).join(i)}syllable(e={}){let{syntax:t}=this[Rs],i={...e},r=i.length||this[rt].number({min:2,max:3}),s=t&&t.consonants||fe.syntax.consonants,a=t&&t.vowels||fe.syntax.vowels,o=s+a,l="",c;for(let p=0;p<r;p++)p===0?c=this[rt].character({pool:o}):c&&a.includes(c)?c=this[rt].character({pool:s}):c=this[rt].character({pool:a}),l+=c;return i.capitalize&&(l=this.capitalize(l)),l}lorem(){let e=["word","words","sentence","sentences","paragraph","paragraphs"],t=this[js].pickOne(e);return this[t]()}};var st=Symbol("typesValue"),ar=Symbol("localeValue"),di=class{[st];[ar];constructor(e={}){this[st]=new tt(e.seed),this[ar]=e.locale||fe}seed(e){this[st].seed(e)}locale(e){this[ar]=e||fe}date(e){return this[st].datetime(e)}amPm(){return this[st].boolean()?"am":"pm"}timestamp(e){return this[st].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[st].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[st].number({min:t,max:i})}millisecond(){return this[st].number({max:999})}second(){return this[st].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[st].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[ar],i;return t&&t.month&&t.month.abbr&&t.month.abbr.length>0?i=t.month:i=fe.time.month,e?i.abbr:i.names}weekdays(e=!1){let{time:t}=this[ar],i;return t&&t.weekday&&t.weekday.abbr&&t.weekday.abbr.length>0?i=t.weekday:i=fe.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[st].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"),a=i.getUTCDate().toString().padStart(2,"0"),o=i.getUTCHours().toString().padStart(2,"0"),l=i.getUTCMinutes().toString().padStart(2,"0"),c=i.getUTCSeconds().toString().padStart(2,"0"),p=i.getUTCMilliseconds().toString().padStart(3,"0");return`${r}-${s}-${a}T${o}:${l}:${c}.${p}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"),a=t.getHours().toString().padStart(2,"0"),o=t.getMinutes().toString().padStart(2,"0"),l=t.getSeconds().toString().padStart(2,"0");return`${i}-${r}-${s}T${a}:${o}:${l}`}};var D;(function(n){n[n.ROOT=0]="ROOT",n[n.GROUP=1]="GROUP",n[n.POSITION=2]="POSITION",n[n.SET=3]="SET",n[n.RANGE=4]="RANGE",n[n.REPETITION=5]="REPETITION",n[n.REFERENCE=6]="REFERENCE",n[n.CHAR=7]="CHAR"})(D||(D={}));var Dd=()=>({type:D.POSITION,value:"b"}),Md=()=>({type:D.POSITION,value:"B"}),Ld=()=>({type:D.POSITION,value:"^"}),Ud=()=>({type:D.POSITION,value:"$"}),po=()=>[{type:D.RANGE,from:48,to:57}],Pn=()=>[{type:D.CHAR,value:95},{type:D.RANGE,from:97,to:122},{type:D.RANGE,from:65,to:90},...po()],On=()=>[{type:D.CHAR,value:9},{type:D.CHAR,value:10},{type:D.CHAR,value:11},{type:D.CHAR,value:12},{type:D.CHAR,value:13},{type:D.CHAR,value:32},{type:D.CHAR,value:160},{type:D.CHAR,value:5760},{type:D.CHAR,value:6158},{type:D.CHAR,value:8192},{type:D.CHAR,value:8193},{type:D.CHAR,value:8194},{type:D.CHAR,value:8195},{type:D.CHAR,value:8196},{type:D.CHAR,value:8197},{type:D.CHAR,value:8198},{type:D.CHAR,value:8199},{type:D.CHAR,value:8200},{type:D.CHAR,value:8201},{type:D.CHAR,value:8202},{type:D.CHAR,value:8232},{type:D.CHAR,value:8233},{type:D.CHAR,value:8239},{type:D.CHAR,value:8287},{type:D.CHAR,value:12288},{type:D.CHAR,value:65279}],zd=()=>[{type:D.CHAR,value:10},{type:D.CHAR,value:13},{type:D.CHAR,value:8232},{type:D.CHAR,value:8233}],Nn=()=>({type:D.SET,set:Pn(),not:!1}),$n=()=>({type:D.SET,set:Pn(),not:!0}),In=()=>({type:D.SET,set:po(),not:!1}),jn=()=>({type:D.SET,set:po(),not:!0}),Rn=()=>({type:D.SET,set:On(),not:!1}),Cn=()=>({type:D.SET,set:On(),not:!0}),Vd=()=>({type:D.SET,set:zd(),not:!0}),Fd={0:0,t:9,n:10,v:11,f:12,r:13},Kd=n=>{let e=/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;return n.replace(e,(t,i,r,s,a,o,l,c)=>{if(r)return t;let p=i?8:s?parseInt(s,16):a?parseInt(a,16):o?parseInt(o,8):l?"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?".indexOf(l):Fd[c],u=String.fromCharCode(p);return/[[{}^$.|?*+()]/.test(u)&&(u=`\\${u}`),u})},qd=(n,e)=>{let t=[],i=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g,r,s;for(;(r=i.exec(n))!==null;)if(r[1])t.push(Nn());else if(r[2])t.push(In());else if(r[3])t.push(Rn());else if(r[4])t.push($n());else if(r[5])t.push(jn());else if(r[6])t.push(Cn());else if(r[7])t.push({type:D.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:r[10].charCodeAt(0)});else if(s=r[12])t.push({type:D.CHAR,value:s.charCodeAt(0)});else return[t,i.lastIndex];throw new SyntaxError(`Invalid regular expression: /${e}/: Unterminated character class`)},Ts=(n,e)=>{throw new SyntaxError(`Invalid regular expression: /${n}/: ${e}`)},Tn=n=>{let e=0,t={type:D.ROOT,stack:[]},i=t,r=t.stack,s=[],a=l=>Ts(n,`Nothing to repeat at column ${l-1}`),o=Kd(n);for(;e<o.length;){let l=o[e++];switch(l){case"\\":switch(l=o[e++],l){case"b":r.push(Dd());break;case"B":r.push(Md());break;case"w":r.push(Nn());break;case"W":r.push($n());break;case"d":r.push(In());break;case"D":r.push(jn());break;case"s":r.push(Rn());break;case"S":r.push(Cn());break;default:/\d/.test(l)?r.push({type:D.REFERENCE,value:parseInt(l,10)}):r.push({type:D.CHAR,value:l.charCodeAt(0)})}break;case"^":r.push(Ld());break;case"$":r.push(Ud());break;case"[":{let c=!1;o[e]==="^"&&(c=!0,e++);let[p,u]=qd(o.slice(e),n);e+=u,r.push({type:D.SET,set:p,not:c});break}case".":r.push(Vd());break;case"(":{let c={type:D.GROUP,stack:[],remember:!0};o[e]==="?"&&(l=o[e+1],e+=2,l==="="?c.followedBy=!0:l==="!"?c.notFollowedBy=!0:l!==":"&&Ts(n,`Invalid group, character '${l}' after '?' at column ${e-1}`),c.remember=!1),r.push(c),s.push(i),i=c,r=c.stack;break}case")":s.length===0&&Ts(n,`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 c=[];i.options.push(c),r=c}break;case"{":{let c=/^(\d+)(,(\d+)?)?\}/.exec(o.slice(e));if(c){r.length===0&&a(e);let p=parseInt(c[1],10),u=c[2]?c[3]?parseInt(c[3],10):1/0:p;e+=c[0].length,r.push({type:D.REPETITION,min:p,max:u,value:r.pop()})}else r.push({type:D.CHAR,value:123});break}case"?":r.length===0&&a(e),r.push({type:D.REPETITION,min:0,max:1,value:r.pop()});break;case"+":r.length===0&&a(e),r.push({type:D.REPETITION,min:1,max:1/0,value:r.pop()});break;case"*":r.length===0&&a(e),r.push({type:D.REPETITION,min:0,max:1/0,value:r.pop()});break;default:r.push({type:D.CHAR,value:l.charCodeAt(0)})}}return s.length!==0&&Ts(n,"Unterminated group"),t};var or=class n{types;constructor(e={}){this.types=new tt(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 a=Tn(i),o=Array.from({length:95},(l,c)=>c+32);return this._gen(a,[],r,o,s)}_gen(e,t,i,r,s){let a,o,l,c;switch(e.type){case D.ROOT:case D.GROUP:if(e.followedBy||e.notFollowedBy)return"";for(e.remember&&e.groupNumber===void 0&&(e.groupNumber=t.push(null)-1),a=e.options?this._choice(e.options):e.stack,o="",l=0,c=a.length;l<c;l++)o+=this._gen(a[l],t,i,r,s);return e.remember&&(t[e.groupNumber]=o),o;case D.POSITION:return"";case D.SET:{let p=this._processSet(e,i,r);return p.length?String.fromCharCode(this._choice(p)):""}case D.REPETITION:{let p=e.max===1/0?Math.max(e.min,s):e.max,u=this.types.number({min:e.min,max:p});for(o="",l=0;l<u;l++)o+=this._gen(e.value,t,i,r,s);return o}case D.REFERENCE:return t[e.value-1]||"";case D.CHAR:{let p=i&&this._coin()?n._toCaseInverse(e.value):e.value;return String.fromCharCode(p)}}return""}_processSet(e,t,i){if(e.type===D.CHAR)return[e.value];if(e.type===D.RANGE){let s=[];for(let a=e.from;a<=e.to;a++)s.push(a);return s}let r=new Set;for(let s of e.set){let a=this._processSet(s,t,i);if(a.forEach(o=>r.add(o)),t)for(let o of a){let l=o,c=n._toCaseInverse(l);l!==c&&r.add(c)}}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 Zt=class n{static types=new tt;static person=new Is;static lorem=new Cs;static regExp=new or;static readInputValue(e,t,i={}){let{required:r}=e,{defaultValueStr:s,values:a}=t;if(!(!r&&i.requiredOnly===!0)){if(s)return n.readTypedValue(s,t.dataType);if(Array.isArray(a)&&a.length){let o=a[0];return n.readTypedValue(o.value,o.dataType)}if(i.fromExamples){let o;if(Array.isArray(e.examples)&&e.examples.length?o=e.examples.filter(l=>typeof l!="string"):Array.isArray(t.examples)&&t.examples.length&&(o=t.examples),o&&o.length)return n.inputValueFromExamples(o)}return n.generateDefaultValue(t)}}static readInputValues(e,t,i={}){if(!e.required&&i.requiredOnly===!0)return[];let{defaultValue:r}=t;if(r){let o=new Ye().processNode(r);if(Array.isArray(o))return o}let s=t;if(i.fromExamples){let a;return Array.isArray(e.examples)&&e.examples.length?a=e.examples.filter(o=>typeof o!="string"):Array.isArray(s.examples)&&s.examples.length&&(a=s.examples),n.arrayValuesFromExamples(a)}return[]}static inputValueFromExamples(e){if(!Array.isArray(e)||!e.length)return;let[t]=e,{structuredValue:i}=t;if(i&&i.types.includes(d.aml.vocabularies.data.Scalar)){let r=i;return n.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(d.aml.vocabularies.data.Array))return t;let r=i.structuredValue,{members:s}=r;return!Array.isArray(s)||!s.length||s.forEach(a=>{let o=a;if(!o.value)return;let l=n.readTypedValue(o.value,o.dataType);typeof r<"u"&&r!==null&&t.push(l)}),t}static generateDefaultValue(e){let{dataType:t}=e;return this.defaultValue(t)}static generateMockedValue(e){let{dataType:t}=e;switch(t){case d.w3.xmlSchema.string:case d.aml.vocabularies.shapes.password:return this.generateStringValue(e);case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:return this.generateNumberValue(e);case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return this.types.boolean();case d.aml.vocabularies.shapes.nil:case d.w3.xmlSchema.nil:return null;case d.w3.xmlSchema.date:return new di().dateOnly();case d.w3.xmlSchema.dateTime:return new di().dateTime(e.format==="date-time"?"rfc3339":e.format);case d.aml.vocabularies.shapes.dateTimeOnly:return new di().dateTimeOnly();case d.w3.xmlSchema.time:return new di().timeOnly();default:return}}static defaultValue(e){switch(e){case d.w3.xmlSchema.string:case d.aml.vocabularies.shapes.password:return"";case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:return 0;case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return!1;case d.aml.vocabularies.shapes.nil:case d.w3.xmlSchema.nil:return null;case d.w3.xmlSchema.date:return"";case d.w3.xmlSchema.dateTime:return"";case d.aml.vocabularies.shapes.dateTimeOnly:return"";case d.w3.xmlSchema.time:return"";default:return}}static generateNumberValue(e){let{minimum:t,maximum:i,format:r,multipleOf:s}=e,a={};typeof t=="number"&&(a.min=t),typeof i=="number"&&(a.max=i);let o;return r&&["float","double"].includes(r)?o=this.types.float.bind(this.types):r&&["uint32","uint64","fixed32","fixed64"].includes(r)&&(a.min=0,a.max&&a.max<0&&delete a.max),o||(o=this.types.number.bind(this.types)),typeof s=="number"&&(a.precision=s),o(a)}static generateStringValue(e){let{minLength:t,maxLength:i,name:r="",format:s,pattern:a}=e;if(a)return new or().fromPattern(a,{max:10});let o=r.toLowerCase();if(o==="description")return this.lorem.paragraph();if(s==="uuid")return this.types.uuid();if(o==="id"){let p={length:12},u=typeof t=="number";return u?p.length=t:!u&&typeof i=="number"&&(p.length=i),this.types.hash(p)}if(["name","fullname"].includes(o))return this.person.name();if(o==="firstname")return this.person.firstName();if(o==="lastname")return this.person.lastName();let l={},c=typeof t=="number";return c?l.length=t:!c&&typeof i=="number"&&(l.length=i),this.lorem.word(l)}static readTypedValue(e,t){return _s(e,t)}static readInputType(e){switch(e){case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:return"number";case d.w3.xmlSchema.date:return"date";case d.w3.xmlSchema.time:return"time";case d.w3.xmlSchema.dateTime:case d.aml.vocabularies.shapes.dateTimeOnly:return"datetime-local";case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return"boolean";case d.aml.vocabularies.shapes.password:return"password";default:return"text"}}static parseNumberInput(e,t){return qa(e,t)}static parseBooleanInput(e,t){return Ja(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?n.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(d.aml.vocabularies.shapes.ScalarShape)?n.parseScalarInput(e,t):i.includes(d.aml.vocabularies.shapes.ArrayShape)||i.includes(d.aml.vocabularies.shapes.MatrixShape)?n.parseArrayInput(e,t):e}static parseScalarInput(e,t){return this.parseScalar(e,t.dataType,t.format)}static parseScalar(e,t,i){switch(t){case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:return n.parseNumberInput(e);case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return n.parseBooleanInput(e);case d.w3.xmlSchema.date:return n.parseDateOnlyInput(e);case d.w3.xmlSchema.time:return n.parseTimeOnlyInput(e);case d.w3.xmlSchema.dateTime:return n.parseDateTimeInput(e,i);case d.aml.vocabularies.shapes.dateTimeOnly:return n.parseDateTimeOnlyInput(e);default:return String(e)}}};var pi=class{opts;constructor(e={}){this.opts=Object.freeze({...e})}_scalarValue(e){let{defaultValue:t,examples:i,values:r,inherits:s,dataType:a}=e;if(this.opts.renderExamples&&i&&i.length){let o=i.find(c=>!!c.structuredValue),l=this._exampleToObject(o);if(typeof l<"u")return Zt.readTypedValue(l,a)}if(t)return new Ye().processNode(t);if(r&&r.length){let o=r[0];if(o.value!==void 0)return Zt.readTypedValue(o.value,a)}if(Array.isArray(s)&&s.length)for(let o=0,l=s.length;o<l;o+=1){let c=this._scalarValue(s[o]);if(c!==void 0)return c}return this.opts.renderMocked?Zt.generateMockedValue(e):Zt.generateDefaultValue(e)}_isNotRequiredUnion(e){let t=0,i=!1;return e.forEach(r=>{r.types.includes(d.aml.vocabularies.shapes.NilShape)?i=!0:r.types.includes(d.aml.vocabularies.shapes.ScalarShape)?r.dataType===d.w3.xmlSchema.nil?i=!0:t+=1:r.types.includes(d.aml.vocabularies.shapes.FileShape)&&(t+=1)}),i?t===e.length-1:!1}};var nr=class extends pi{generate(e){let t;return e.types.includes(d.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(d.aml.vocabularies.shapes.ScalarShape)?this._scalarShapeObject(e):t.includes(d.w3.shacl.NodeShape)?this._nodeShapeObject(e):t.includes(d.aml.vocabularies.shapes.UnionShape)?this._unionShapeObject(e):t.includes(d.aml.vocabularies.shapes.FileShape)?this._fileShapeObject():t.includes(d.aml.vocabularies.shapes.SchemaShape)?this._schemaShapeObject():t.includes(d.aml.vocabularies.shapes.TupleShape)?this._tupleShapeObject(e):t.includes(d.aml.vocabularies.shapes.ArrayShape)||t.includes(d.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(a=>{let o=a;Array.isArray(o.examples)&&o.examples.length&&(i=i.concat(o.examples))}),this.opts.renderExamples&&i.length){let a=i.find(l=>!!l.structuredValue),o=this._exampleToObject(a);if(o!==void 0)return o}let r={},{properties:s}=e;return Array.isArray(t)&&t.length&&t.forEach(a=>{let o=this.toObject(a);typeof o=="object"&&(r={...r,...o})}),s.forEach(a=>{let{name:o}=a,l=this._propertyShapeObject(a);typeof l<"u"&&o&&(r[o]=l)}),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(o=>{let l=o;Array.isArray(l.examples)&&l.examples.length&&(i=i.concat(l.examples));let c=o;Array.isArray(c.anyOf)&&c.anyOf.length&&(t=t.concat(c.anyOf))});let{opts:r}=this;if(this._isNotRequiredUnion(t))return;if(this.opts.renderExamples){let o=i.find(c=>!!c.structuredValue),l=this._exampleToObject(o);if(l!==void 0)return l}if(e.defaultValue)return this._unionDefaultValue(t,e.defaultValue);let{selectedUnions:s}=r,a;if(s&&s.length?a=t.find(o=>s.includes(o.id)):[a]=t,a)return this.toObject(a)}_oneOfUnion(e){let{examples:t=[]}=e,{xone:i=[]}=e;Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(o=>{let l=o;Array.isArray(l.examples)&&l.examples.length&&(t=t.concat(l.examples))});let{opts:r}=this;if(this.opts.renderExamples){let o=t.find(c=>!!c.structuredValue),l=this._exampleToObject(o);if(l!==void 0)return l}if(e.defaultValue)return this._unionDefaultValue(i,e.defaultValue);let{selectedUnions:s}=r,a;if(s&&s.length?a=i.find(o=>s.includes(o.id)):[a]=i,a)return this.toObject(a)}_allOfUnion(e){let{examples:t=[]}=e,{and:i=[]}=e;if(Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(s=>{let a=s;Array.isArray(a.examples)&&a.examples.length&&(t=t.concat(a.examples))}),this.opts.renderExamples){let s=t.find(o=>!!o.structuredValue),a=this._exampleToObject(s);if(a!==void 0)return a}let r={};return i.forEach(s=>{let a=this.toObject(s);typeof a=="object"&&(r={...r,...a})}),r}_unionDefaultValue(e,t){let r=new Ye().generate(t),s=!1,a=!1,o=!1;if(e.forEach(l=>{if(l.types.includes(d.aml.vocabularies.shapes.NilShape)&&(o=!0),!l.types.includes(d.aml.vocabularies.shapes.ScalarShape))return;let c=l;a||(a=c.dataType===d.w3.xmlSchema.boolean),s||(s=[d.w3.xmlSchema.number,d.w3.xmlSchema.long,d.w3.xmlSchema.integer,d.w3.xmlSchema.float,d.w3.xmlSchema.double,d.aml.vocabularies.shapes.number,d.aml.vocabularies.shapes.long,d.aml.vocabularies.shapes.integer,d.aml.vocabularies.shapes.float,d.aml.vocabularies.shapes.double].includes(c.dataType)),o||(o=c.dataType===d.w3.xmlSchema.nil)}),s){let l=Number(r);if(!Number.isNaN(l))return l}if(a){if(r==="true")return!0;if(r==="false")return!1}return o&&(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 a=r.find(l=>!!l.structuredValue),o=this._exampleToObject(a);if(Array.isArray(o))return o;if(typeof o<"u")return[o]}if(i){let o=new Ye().processNode(i);if(Array.isArray(o))return o;if(o)return[o]}if(t){let a=this.toObject(t);if(typeof a<"u")return[a]}return[]}_tupleShapeObject(e){let{items:t,examples:i}=e;if(this.opts.renderExamples&&i&&i.length){let r=i.find(a=>!!a.structuredValue),s=this._exampleToObject(r);if(typeof s<"u")return[s]}if(e.defaultValue){let s=new Ye().processNode(e.defaultValue);if(Array.isArray(s))return s}if(t.length){let r=[];return t.forEach(s=>{let a=this.toObject(s);typeof a<"u"&&r.push(a)}),r}return[]}_anyShapeObject(e){let{and:t=[],xone:i=[],or:r=[]}=e;if(t.length){let s={};return t.forEach(a=>{let o=this.toObject(a);typeof o=="object"&&(s={...s,...o})}),s}if(i.length){let{selectedUnions:s=[]}=this.opts,a=i.find(o=>s.includes(o.id));return a||(a=i[0]),this.toObject(a)}if(r.length){let{selectedUnions:s=[]}=this.opts,a=r.find(o=>s.includes(o.id));return a||(a=r[0]),this.toObject(a)}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(d.aml.vocabularies.shapes.ScalarShape)){let s=i;return this._scalarShapeObject(s)}return this.toObject(i)}_exampleToObject(e){if(e&&e.structuredValue)return new Ye().processNode(e.structuredValue)}_fileShapeObject(){}_schemaShapeObject(){}};var Be=n=>n.replace(/[^a-zA-Z0-9-_.]/g,""),uo="unknown-type";function _t(n){let{name:e,inherits:t=[],xmlSerialization:i}=n,r=i&&i.name?i.name:e||uo;if(r==="schema"&&t.length){let s=t.find(a=>a.name&&a.name!=="schema");s&&(r=s.name==="type"&&s.displayName||s.name)}return Be(String(r))}var lr=class extends pi{generate(e){let t;return e.types.includes(d.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(d.aml.vocabularies.shapes.ScalarShape)?this._scalarShapeObject(e,t):r.includes(d.w3.shacl.NodeShape)?this._nodeShapeObject(e,t):r.includes(d.aml.vocabularies.shapes.UnionShape)?this._unionShapeObject(e):r.includes(d.aml.vocabularies.shapes.FileShape)?this._fileShapeObject():r.includes(d.aml.vocabularies.shapes.SchemaShape)?this._schemaShapeObject():r.includes(d.aml.vocabularies.shapes.TupleShape)?this._tupleShapeObject():r.includes(d.aml.vocabularies.shapes.ArrayShape)||r.includes(d.aml.vocabularies.shapes.MatrixShape)?this._arrayShapeObject(e,t,i):this._anyShapeObject(e)}serialize(e){return e}_readCurrentUnion(e){let{selectedUnions:t}=this.opts;return Ba(e,t)}_collectProperties(e){let{selectedUnions:t}=this.opts;return As(e,t)}_nodeShapeObject(e,t={}){let i=t.forceName||_t(e),r=[],s=t.indent||0,a=this._collectExamples(e,{tagFill:new Array(s*2+0).fill(" ").join(""),indent:s+1,nodeName:i});if(a)return a;let o=[];if(this._collectProperties(e).forEach(u=>{let{range:m,minCount:h=0}=u;if(h===0&&!this.opts.renderOptional||!m)return;let f=m;if(f.xmlSerialization&&f.xmlSerialization.attribute&&f.types.includes(d.aml.vocabularies.shapes.ScalarShape)){let w=Be(f.xmlSerialization.name?f.xmlSerialization.name:u.name||f.name||uo);f.xmlSerialization.prefix&&(w=`${f.xmlSerialization.prefix}:${w}`);let E=this._scalarValue(f);o.push(`${w}="${E}"`);return}let v=this._propertyShapeObject(u,{indent:s});if(typeof v<"u"){let w=t.noWrap?0:2,E=new Array(s*2+w).fill(" ").join("");r.push(Ss(E,v))}}),t.noWrap)return r.join(`
37
- `);let c=`<${i}`;o.length&&(c+=" ",c+=o.join(" ")),r.unshift(`${c}>`);let p=new Array(s*2).fill(" ").join("");return r.push(`${p}</${i}>`),r.join(`
38
- `)}_scalarShapeObject(e,t={}){let{xmlSerialization:i,defaultValue:r}=e,s;r?s=new Ve().processNode(r):s=this._scalarValue(e);let a=t.forceName||_t(e),o=[],l=[];if(i){let{namespace:p,prefix:u}=i;if(p){let m=u?`xmlns:${u}`:"xmlns";o.push(`${m}="${p}"`)}u&&(a=`${u}:${a}`)}let c=`<${a}`;return o.length&&(c+=" ",c+=o.join(" ")),c+=">",l.push(c),l.push(s),l.push(`</${a}>`),l.join("")}_nilShapeObject(e,t={}){let{xmlSerialization:i}=e,r="",s=t.forceName||_t(e),a=[],o=[];if(i){let{namespace:c,prefix:p}=i;if(c){let u=p?`xmlns:${p}`:"xmlns";a.push(`${u}="${c}"`)}p&&(s=`${p}:${s}`)}let l=`<${s}`;return a.length&&(l+=" ",l+=a.join(" ")),l+=">",o.push(l),o.push(r),o.push(`</${s}>`),o.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(d.aml.vocabularies.shapes.ScalarShape))return this._scalarShapeObject(i,{...t});if(s.includes(d.aml.vocabularies.shapes.NilShape)){let o=_t(e);return this._nilShapeObject(i,{...t,forceName:o})}if(s.includes(d.aml.vocabularies.shapes.RecursiveShape))return;if(s.includes(d.w3.shacl.NodeShape))return this._nodePropertyObject(e,t);if(s.includes(d.aml.vocabularies.shapes.ArrayShape)||s.includes(d.aml.vocabularies.shapes.MatrixShape))return this._nodePropertyArray(e,t);let a=_t(e);return this.processNode(i,{...t,forceName:a})}_collectExamples(e,t={}){if(!this.opts.renderExamples)return;let{isWrapped:i,nodeName:r,tagFill:s="",indent:a=0}=t,{examples:o=[]}=e,{inherits:l}=e;Array.isArray(l)&&l.length&&l.forEach(m=>{let h=m;if(h.types.includes(d.aml.vocabularies.shapes.UnionShape)){let v=h,{anyOf:w=[]}=v;h=this._readCurrentUnion(w)}let f=h;Array.isArray(f.examples)&&f.examples.length&&(o=o.concat(f.examples))});let c=o.filter(m=>!!m.structuredValue);if(!c.length)return;let p=[];i&&p.push(`${s}<${r}>`);let u=new Ve;return c.forEach(m=>{let h=u.generate(m.structuredValue,r,{indent:a+1});h!==void 0&&p.push(h)}),i&&p.push(`${s}</${r}>`),p.join(`
39
- `)}_createTabs(e=0,t=0){return new Array(e*2+t).fill(" ").join("")}_nodePropertyObject(e,t={}){let i=[],r=Be(String(e.name)),{indent:s=0}=t,a=this._createTabs(s),o,l=e.range,c=this._collectExamples(l,{tagFill:a,indent:s+1,nodeName:r}),p=[];if(c)o=c;else{let m=[];this._collectProperties(l).forEach(f=>{let{range:v,minCount:w=0}=f;if(w===0&&!this.opts.renderOptional)return;let E=v;if(E.xmlSerialization){let{prefix:R,attribute:C}=E.xmlSerialization;if(C&&E.types.includes(d.aml.vocabularies.shapes.ScalarShape)){let N=Be(E.xmlSerialization.name?E.xmlSerialization.name:f.name||E.name||uo);R&&(N=`${R}:${N}`);let T=this._scalarValue(E);p.push(`${N}="${T}"`);return}}let I=this._propertyShapeObject(f,{indent:s});if(I!==void 0){let R=this._createTabs(s,2);m.push(Ss(R,I))}}),o=m.join(`
40
- `)}let u=`${a}<${r}`;return p.length&&(u+=" ",u+=p.join(" ")),i.unshift(`${u}>`),i.push(o),i.push(`${a}</${r}>`),i.join(`
41
- `)}_nodePropertyArray(e,t={}){let i=e.range,r=[],s;i.xmlSerialization&&i.xmlSerialization.name?s=Be(i.xmlSerialization.name):s=Be(String(e.name));let{indent:a=0}=t,o=!!i.items&&i.items.types.includes(d.aml.vocabularies.shapes.ScalarShape),l=this._createTabs(a);o||r.push(`${l}<${s}>`);let c=this._arrayShapeObject(i,{...t,indent:a});return r.push(c),o||r.push(`${l}</${s}>`),r.join(`
42
- `)}_arrayShapeObject(e,t={},i=!1){let{items:r}=e,s=!!r&&r.types.includes(d.aml.vocabularies.shapes.ScalarShape),a;i&&e.xmlSerialization&&e.xmlSerialization.name?a=Be(e.xmlSerialization.name):i&&e.name?a=Be(e.name):!s&&r?.name?a=Be(r.name):e.name&&(a=Be(e.name));let o=!1;e.xmlSerialization&&typeof e.xmlSerialization.wrapped=="boolean"&&(o=!0);let l=!!e.xmlSerialization&&!!e.xmlSerialization.wrapped,c=t.indent||0,p=new Array(c*2+0).fill(" ").join(""),u=new Array(c*2+(l?2:0)).fill(" ").join("");if(this.opts.renderExamples){let{examples:m=[]}=e,h=m.filter(f=>!!f.structuredValue);if(h.length){let f=[],v=new Ve;if(s&&!l){let[w]=h;!a&&r?.name&&(a=Be(r.name));let E=v.generate(w.structuredValue,a,{indent:c});E!==void 0&&f.push(E)}else if(s&&l){let[w]=h,E=v.generate(w.structuredValue,a,{indent:c});f.push(`${p}<${a}>`),E!==void 0&&f.push(E),f.push(`${p}</${a}>`)}else l?h.forEach(w=>{f.push(`${p}<${a}>`);let E=v.generate(w.structuredValue,void 0,{indent:c+2});E!==void 0&&f.push(E),f.push(`${p}</${a}>`)}):h.forEach(w=>{let E=v.generate(w.structuredValue,void 0,{indent:c});E!==void 0&&f.push(E)});return f.join(`
43
- `)}}if(s&&e.defaultValue){let h=new Ve().generate(e.defaultValue);return!a&&r?.name&&(a=Be(r.name)),`<${a}>${h?.trim()}</${a}>`}if(r){let m=[];l&&s&&m.push(`${p}<${a}>`);let h={indent:c+1};a&&(h.forceName=a),!i&&(!o||o&&!l)&&(h.noWrap=!0);let f=this.processNode(r,h);return f!==void 0&&m.push(`${u}${f}`),l&&s&&m.push(`${p}</${a}>`),m.join(`
44
- `)}return""}_scalarItems(e,t={}){let i=e.items,r=t.indent||0,s=new Array(r*2).fill(" ").join(""),a="";if(i.xmlSerialization&&i.xmlSerialization.name?a=Be(i.xmlSerialization.name):a=_t(e.name?e:i),this.opts.renderExamples){let{examples:c=[]}=e;Array.isArray(i.examples)&&(c=c.concat(i.examples));let p=c.filter(u=>!!u.structuredValue);if(p.length){let u=[],m=new Ve;return p.forEach(h=>{let f=m.generate(h.structuredValue,a);f!==void 0&&u.push(`${s}${f}`)}),u.join(`
45
- `)}}if(e.defaultValue){let p=new Ve().generate(e.defaultValue,a);if(p!==void 0)return`${s}${p}`}let o={indent:r+1,forceName:a},l=this.processNode(i,o);return`${s}${l}`}_nodeItems(e,t={}){let i=e.items,r=t.indent||0,s=new Array(r*2).fill(" ").join(""),a=e.xmlSerialization&&!!e.xmlSerialization.wrapped,o=e.defaultValue||i.defaultValue,l="";i.xmlSerialization&&i.xmlSerialization.name?l=Be(i.xmlSerialization.name):l=_t(e.name?e:i);let c=a?new Array(r*2+2).fill(" ").join(""):s,p=[];a&&p.push(`${s}<${l}>`);let u=!1;if(this.opts.renderExamples){let{examples:m=[]}=e;Array.isArray(i.examples)&&(m=m.concat(i.examples));let h=m.filter(f=>!!f.structuredValue);if(h.length){let f=[],v=new Ve;h.forEach(w=>{let E=v.generate(w.structuredValue,l);E!==void 0&&f.push(`${s}${E}`)}),u=!0}}if(!u&&o){let h=new Ve().generate(o,l);h!==void 0&&(p.push(`${s}${h}`),u=!0)}return u||this._collectProperties(i).forEach(h=>{let f=this._propertyShapeObject(h);f&&p.push(`${c}${f}`)}),a&&p.push(`${s}</${l}>`),p.join(`
46
- `)}_exampleToObject(e){if(e&&e.structuredValue)return new Ve().generate(e.structuredValue)}_unionShapeObject(e,t={}){let{anyOf:i=[],examples:r=[]}=e;if(Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(s=>{let a=s;Array.isArray(a.examples)&&a.examples.length&&(r=r.concat(a.examples));let o=s;Array.isArray(o.anyOf)&&o.anyOf.length&&(i=i.concat(o.anyOf))}),Array.isArray(i)&&i.length){if(this._isNotRequiredUnion(i))return;let s=r.find(l=>!!l.structuredValue),a=this._exampleToObject(s);if(a!==void 0){let l=_t(e),c=t.indent||0,p=new Array(c*2).fill(" ").join(""),u=new Array(c*2+2).fill(" ").join(""),m=[];m.push(`${p}<${l}>`);let h=String(a).split(`
36
+ `,size:r=this[st].number({min:1,max:7})}=t;return new Array(r).fill("").map(()=>this.paragraph()).join(i)}syllable(e={}){let{syntax:t}=this[Ds],i={...e},r=i.length||this[st].number({min:2,max:3}),s=t&&t.consonants||fe.syntax.consonants,o=t&&t.vowels||fe.syntax.vowels,a=s+o,l="",c;for(let p=0;p<r;p++)p===0?c=this[st].character({pool:a}):c&&o.includes(c)?c=this[st].character({pool:s}):c=this[st].character({pool:o}),l+=c;return i.capitalize&&(l=this.capitalize(l)),l}lorem(){let e=["word","words","sentence","sentences","paragraph","paragraphs"],t=this[Ts].pickOne(e);return this[t]()}};var ot=Symbol("typesValue"),cr=Symbol("localeValue"),pi=class{[ot];[cr];constructor(e={}){this[ot]=new it(e.seed),this[cr]=e.locale||fe}seed(e){this[ot].seed(e)}locale(e){this[cr]=e||fe}date(e){return this[ot].datetime(e)}amPm(){return this[ot].boolean()?"am":"pm"}timestamp(e){return this[ot].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[ot].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[ot].number({min:t,max:i})}millisecond(){return this[ot].number({max:999})}second(){return this[ot].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[ot].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[cr],i;return t&&t.month&&t.month.abbr&&t.month.abbr.length>0?i=t.month:i=fe.time.month,e?i.abbr:i.names}weekdays(e=!1){let{time:t}=this[cr],i;return t&&t.weekday&&t.weekday.abbr&&t.weekday.abbr.length>0?i=t.weekday:i=fe.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[ot].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"),l=i.getUTCMinutes().toString().padStart(2,"0"),c=i.getUTCSeconds().toString().padStart(2,"0"),p=i.getUTCMilliseconds().toString().padStart(3,"0");return`${r}-${s}-${o}T${a}:${l}:${c}.${p}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"),l=t.getSeconds().toString().padStart(2,"0");return`${i}-${r}-${s}T${o}:${a}:${l}`}};var M;(function(n){n[n.ROOT=0]="ROOT",n[n.GROUP=1]="GROUP",n[n.POSITION=2]="POSITION",n[n.SET=3]="SET",n[n.RANGE=4]="RANGE",n[n.REPETITION=5]="REPETITION",n[n.REFERENCE=6]="REFERENCE",n[n.CHAR=7]="CHAR"})(M||(M={}));var Jd=()=>({type:M.POSITION,value:"b"}),Bd=()=>({type:M.POSITION,value:"B"}),Gd=()=>({type:M.POSITION,value:"^"}),Hd=()=>({type:M.POSITION,value:"$"}),ka=()=>[{type:M.RANGE,from:48,to:57}],Cn=()=>[{type:M.CHAR,value:95},{type:M.RANGE,from:97,to:122},{type:M.RANGE,from:65,to:90},...ka()],Tn=()=>[{type:M.CHAR,value:9},{type:M.CHAR,value:10},{type:M.CHAR,value:11},{type:M.CHAR,value:12},{type:M.CHAR,value:13},{type:M.CHAR,value:32},{type:M.CHAR,value:160},{type:M.CHAR,value:5760},{type:M.CHAR,value:6158},{type:M.CHAR,value:8192},{type:M.CHAR,value:8193},{type:M.CHAR,value:8194},{type:M.CHAR,value:8195},{type:M.CHAR,value:8196},{type:M.CHAR,value:8197},{type:M.CHAR,value:8198},{type:M.CHAR,value:8199},{type:M.CHAR,value:8200},{type:M.CHAR,value:8201},{type:M.CHAR,value:8202},{type:M.CHAR,value:8232},{type:M.CHAR,value:8233},{type:M.CHAR,value:8239},{type:M.CHAR,value:8287},{type:M.CHAR,value:12288},{type:M.CHAR,value:65279}],Wd=()=>[{type:M.CHAR,value:10},{type:M.CHAR,value:13},{type:M.CHAR,value:8232},{type:M.CHAR,value:8233}],Dn=()=>({type:M.SET,set:Cn(),not:!1}),Mn=()=>({type:M.SET,set:Cn(),not:!0}),Ln=()=>({type:M.SET,set:ka(),not:!1}),Un=()=>({type:M.SET,set:ka(),not:!0}),zn=()=>({type:M.SET,set:Tn(),not:!1}),Vn=()=>({type:M.SET,set:Tn(),not:!0}),Xd=()=>({type:M.SET,set:Wd(),not:!0}),Yd={0:0,t:9,n:10,v:11,f:12,r:13},Zd=n=>{let e=/(\[\\b\])|(\\)?\\(?:u([A-F0-9]{4})|x([A-F0-9]{2})|(0?[0-7]{2})|c([@A-Z[\\\]^?])|([0tnvfr]))/g;return n.replace(e,(t,i,r,s,o,a,l,c)=>{if(r)return t;let p=i?8:s?parseInt(s,16):o?parseInt(o,16):a?parseInt(a,8):l?"@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^ ?".indexOf(l):Yd[c],u=String.fromCharCode(p);return/[[{}^$.|?*+()]/.test(u)&&(u=`\\${u}`),u})},Qd=(n,e)=>{let t=[],i=/\\(?:(w)|(d)|(s)|(W)|(D)|(S))|((?:(?:\\)(.)|([^\]\\]))-(?:\\)?([^\]]))|(\])|(?:\\)?(.)/g,r,s;for(;(r=i.exec(n))!==null;)if(r[1])t.push(Dn());else if(r[2])t.push(Ln());else if(r[3])t.push(zn());else if(r[4])t.push(Mn());else if(r[5])t.push(Un());else if(r[6])t.push(Vn());else if(r[7])t.push({type:M.RANGE,from:(r[8]||r[9]).charCodeAt(0),to:r[10].charCodeAt(0)});else if(s=r[12])t.push({type:M.CHAR,value:s.charCodeAt(0)});else return[t,i.lastIndex];throw new SyntaxError(`Invalid regular expression: /${e}/: Unterminated character class`)},Ls=(n,e)=>{throw new SyntaxError(`Invalid regular expression: /${n}/: ${e}`)},Fn=n=>{let e=0,t={type:M.ROOT,stack:[]},i=t,r=t.stack,s=[],o=l=>Ls(n,`Nothing to repeat at column ${l-1}`),a=Zd(n);for(;e<a.length;){let l=a[e++];switch(l){case"\\":switch(l=a[e++],l){case"b":r.push(Jd());break;case"B":r.push(Bd());break;case"w":r.push(Dn());break;case"W":r.push(Mn());break;case"d":r.push(Ln());break;case"D":r.push(Un());break;case"s":r.push(zn());break;case"S":r.push(Vn());break;default:/\d/.test(l)?r.push({type:M.REFERENCE,value:parseInt(l,10)}):r.push({type:M.CHAR,value:l.charCodeAt(0)})}break;case"^":r.push(Gd());break;case"$":r.push(Hd());break;case"[":{let c=!1;a[e]==="^"&&(c=!0,e++);let[p,u]=Qd(a.slice(e),n);e+=u,r.push({type:M.SET,set:p,not:c});break}case".":r.push(Xd());break;case"(":{let c={type:M.GROUP,stack:[],remember:!0};a[e]==="?"&&(l=a[e+1],e+=2,l==="="?c.followedBy=!0:l==="!"?c.notFollowedBy=!0:l!==":"&&Ls(n,`Invalid group, character '${l}' after '?' at column ${e-1}`),c.remember=!1),r.push(c),s.push(i),i=c,r=c.stack;break}case")":s.length===0&&Ls(n,`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 c=[];i.options.push(c),r=c}break;case"{":{let c=/^(\d+)(,(\d+)?)?\}/.exec(a.slice(e));if(c){r.length===0&&o(e);let p=parseInt(c[1],10),u=c[2]?c[3]?parseInt(c[3],10):1/0:p;e+=c[0].length,r.push({type:M.REPETITION,min:p,max:u,value:r.pop()})}else r.push({type:M.CHAR,value:123});break}case"?":r.length===0&&o(e),r.push({type:M.REPETITION,min:0,max:1,value:r.pop()});break;case"+":r.length===0&&o(e),r.push({type:M.REPETITION,min:1,max:1/0,value:r.pop()});break;case"*":r.length===0&&o(e),r.push({type:M.REPETITION,min:0,max:1/0,value:r.pop()});break;default:r.push({type:M.CHAR,value:l.charCodeAt(0)})}}return s.length!==0&&Ls(n,"Unterminated group"),t};var dr=class n{types;constructor(e={}){this.types=new it(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=Fn(i),a=Array.from({length:95},(l,c)=>c+32);return this._gen(o,[],r,a,s)}_gen(e,t,i,r,s){let o,a,l,c;switch(e.type){case M.ROOT:case M.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="",l=0,c=o.length;l<c;l++)a+=this._gen(o[l],t,i,r,s);return e.remember&&(t[e.groupNumber]=a),a;case M.POSITION:return"";case M.SET:{let p=this._processSet(e,i,r);return p.length?String.fromCharCode(this._choice(p)):""}case M.REPETITION:{let p=e.max===1/0?Math.max(e.min,s):e.max,u=this.types.number({min:e.min,max:p});for(a="",l=0;l<u;l++)a+=this._gen(e.value,t,i,r,s);return a}case M.REFERENCE:return t[e.value-1]||"";case M.CHAR:{let p=i&&this._coin()?n._toCaseInverse(e.value):e.value;return String.fromCharCode(p)}}return""}_processSet(e,t,i){if(e.type===M.CHAR)return[e.value];if(e.type===M.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 l=a,c=n._toCaseInverse(l);l!==c&&r.add(c)}}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 ei=class n{static types=new it;static person=new Cs;static lorem=new Ms;static regExp=new dr;static readInputValue(e,t,i={}){let{required:r}=e,{defaultValueStr:s,values:o}=t;if(!(!r&&i.requiredOnly===!0)){if(s)return n.readTypedValue(s,t.dataType);if(Array.isArray(o)&&o.length){let a=o[0];return n.readTypedValue(a.value,a.dataType)}if(i.fromExamples){let a;if(Array.isArray(e.examples)&&e.examples.length?a=e.examples.filter(l=>typeof l!="string"):Array.isArray(t.examples)&&t.examples.length&&(a=t.examples),a&&a.length)return n.inputValueFromExamples(a)}return n.generateDefaultValue(t)}}static readInputValues(e,t,i={}){if(!e.required&&i.requiredOnly===!0)return[];let{defaultValue:r}=t;if(r){let a=new Ye().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),n.arrayValuesFromExamples(o)}return[]}static inputValueFromExamples(e){if(!Array.isArray(e)||!e.length)return;let[t]=e,{structuredValue:i}=t;if(i&&i.types.includes(d.aml.vocabularies.data.Scalar)){let r=i;return n.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(d.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 l=n.readTypedValue(a.value,a.dataType);typeof r<"u"&&r!==null&&t.push(l)}),t}static generateDefaultValue(e){let{dataType:t}=e;return this.defaultValue(t)}static generateMockedValue(e){let{dataType:t}=e;switch(t){case d.w3.xmlSchema.string:case d.aml.vocabularies.shapes.password:return this.generateStringValue(e);case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:return this.generateNumberValue(e);case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return this.types.boolean();case d.aml.vocabularies.shapes.nil:case d.w3.xmlSchema.nil:return null;case d.w3.xmlSchema.date:return new pi().dateOnly();case d.w3.xmlSchema.dateTime:return new pi().dateTime(e.format==="date-time"?"rfc3339":e.format);case d.aml.vocabularies.shapes.dateTimeOnly:return new pi().dateTimeOnly();case d.w3.xmlSchema.time:return new pi().timeOnly();default:return}}static defaultValue(e){switch(e){case d.w3.xmlSchema.string:case d.aml.vocabularies.shapes.password:return"";case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:return 0;case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return!1;case d.aml.vocabularies.shapes.nil:case d.w3.xmlSchema.nil:return null;case d.w3.xmlSchema.date:return"";case d.w3.xmlSchema.dateTime:return"";case d.aml.vocabularies.shapes.dateTimeOnly:return"";case d.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 dr().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 p={length:12},u=typeof t=="number";return u?p.length=t:!u&&typeof i=="number"&&(p.length=i),this.types.hash(p)}if(["name","fullname"].includes(a))return this.person.name();if(a==="firstname")return this.person.firstName();if(a==="lastname")return this.person.lastName();let l={},c=typeof t=="number";return c?l.length=t:!c&&typeof i=="number"&&(l.length=i),this.lorem.word(l)}static readTypedValue(e,t){return xs(e,t)}static readInputType(e){switch(e){case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:return"number";case d.w3.xmlSchema.date:return"date";case d.w3.xmlSchema.time:return"time";case d.w3.xmlSchema.dateTime:case d.aml.vocabularies.shapes.dateTimeOnly:return"datetime-local";case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return"boolean";case d.aml.vocabularies.shapes.password:return"password";default:return"text"}}static parseNumberInput(e,t){return Qo(e,t)}static parseBooleanInput(e,t){return ea(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?n.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(d.aml.vocabularies.shapes.ScalarShape)?n.parseScalarInput(e,t):i.includes(d.aml.vocabularies.shapes.ArrayShape)||i.includes(d.aml.vocabularies.shapes.MatrixShape)?n.parseArrayInput(e,t):e}static parseScalarInput(e,t){return this.parseScalar(e,t.dataType,t.format)}static parseScalar(e,t,i){switch(t){case d.aml.vocabularies.shapes.number:case d.aml.vocabularies.shapes.integer:case d.aml.vocabularies.shapes.float:case d.aml.vocabularies.shapes.long:case d.aml.vocabularies.shapes.double:case d.w3.xmlSchema.number:case d.w3.xmlSchema.integer:case d.w3.xmlSchema.float:case d.w3.xmlSchema.long:case d.w3.xmlSchema.double:return n.parseNumberInput(e);case d.aml.vocabularies.shapes.boolean:case d.w3.xmlSchema.boolean:return n.parseBooleanInput(e);case d.w3.xmlSchema.date:return n.parseDateOnlyInput(e);case d.w3.xmlSchema.time:return n.parseTimeOnlyInput(e);case d.w3.xmlSchema.dateTime:return n.parseDateTimeInput(e,i);case d.aml.vocabularies.shapes.dateTimeOnly:return n.parseDateTimeOnlyInput(e);default:return String(e)}}};var ui=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(c=>!!c.structuredValue),l=this._exampleToObject(a);if(typeof l<"u")return ei.readTypedValue(l,o)}if(t)return new Ye().processNode(t);if(r&&r.length){let a=r[0];if(a.value!==void 0)return ei.readTypedValue(a.value,o)}if(Array.isArray(s)&&s.length)for(let a=0,l=s.length;a<l;a+=1){let c=this._scalarValue(s[a]);if(c!==void 0)return c}return this.opts.renderMocked?ei.generateMockedValue(e):ei.generateDefaultValue(e)}_isNotRequiredUnion(e){let t=0,i=!1;return e.forEach(r=>{r.types.includes(d.aml.vocabularies.shapes.NilShape)?i=!0:r.types.includes(d.aml.vocabularies.shapes.ScalarShape)?r.dataType===d.w3.xmlSchema.nil?i=!0:t+=1:r.types.includes(d.aml.vocabularies.shapes.FileShape)&&(t+=1)}),i?t===e.length-1:!1}};var pr=class extends ui{generate(e){let t;return e.types.includes(d.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(d.aml.vocabularies.shapes.ScalarShape)?this._scalarShapeObject(e):t.includes(d.w3.shacl.NodeShape)?this._nodeShapeObject(e):t.includes(d.aml.vocabularies.shapes.UnionShape)?this._unionShapeObject(e):t.includes(d.aml.vocabularies.shapes.FileShape)?this._fileShapeObject():t.includes(d.aml.vocabularies.shapes.SchemaShape)?this._schemaShapeObject():t.includes(d.aml.vocabularies.shapes.TupleShape)?this._tupleShapeObject(e):t.includes(d.aml.vocabularies.shapes.ArrayShape)||t.includes(d.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(l=>!!l.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,l=this._propertyShapeObject(o);typeof l<"u"&&a&&(r[a]=l)}),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 l=a;Array.isArray(l.examples)&&l.examples.length&&(i=i.concat(l.examples));let c=a;Array.isArray(c.anyOf)&&c.anyOf.length&&(t=t.concat(c.anyOf))});let{opts:r}=this;if(this._isNotRequiredUnion(t))return;if(this.opts.renderExamples){let a=i.find(c=>!!c.structuredValue),l=this._exampleToObject(a);if(l!==void 0)return l}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 l=a;Array.isArray(l.examples)&&l.examples.length&&(t=t.concat(l.examples))});let{opts:r}=this;if(this.opts.renderExamples){let a=t.find(c=>!!c.structuredValue),l=this._exampleToObject(a);if(l!==void 0)return l}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 Ye().generate(t),s=!1,o=!1,a=!1;if(e.forEach(l=>{if(l.types.includes(d.aml.vocabularies.shapes.NilShape)&&(a=!0),!l.types.includes(d.aml.vocabularies.shapes.ScalarShape))return;let c=l;o||(o=c.dataType===d.w3.xmlSchema.boolean),s||(s=[d.w3.xmlSchema.number,d.w3.xmlSchema.long,d.w3.xmlSchema.integer,d.w3.xmlSchema.float,d.w3.xmlSchema.double,d.aml.vocabularies.shapes.number,d.aml.vocabularies.shapes.long,d.aml.vocabularies.shapes.integer,d.aml.vocabularies.shapes.float,d.aml.vocabularies.shapes.double].includes(c.dataType)),a||(a=c.dataType===d.w3.xmlSchema.nil)}),s){let l=Number(r);if(!Number.isNaN(l))return l}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(l=>!!l.structuredValue),a=this._exampleToObject(o);if(Array.isArray(a))return a;if(typeof a<"u")return[a]}if(i){let a=new Ye().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 Ye().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(d.aml.vocabularies.shapes.ScalarShape)){let s=i;return this._scalarShapeObject(s)}return this.toObject(i)}_exampleToObject(e){if(e&&e.structuredValue)return new Ye().processNode(e.structuredValue)}_fileShapeObject(){}_schemaShapeObject(){}};var He=n=>n.replace(/[^a-zA-Z0-9-_.]/g,""),va="unknown-type";function _t(n){let{name:e,inherits:t=[],xmlSerialization:i}=n,r=i&&i.name?i.name:e||va;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 He(String(r))}var ur=class extends ui{generate(e){let t;return e.types.includes(d.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(d.aml.vocabularies.shapes.ScalarShape)?this._scalarShapeObject(e,t):r.includes(d.w3.shacl.NodeShape)?this._nodeShapeObject(e,t):r.includes(d.aml.vocabularies.shapes.UnionShape)?this._unionShapeObject(e):r.includes(d.aml.vocabularies.shapes.FileShape)?this._fileShapeObject():r.includes(d.aml.vocabularies.shapes.SchemaShape)?this._schemaShapeObject():r.includes(d.aml.vocabularies.shapes.TupleShape)?this._tupleShapeObject():r.includes(d.aml.vocabularies.shapes.ArrayShape)||r.includes(d.aml.vocabularies.shapes.MatrixShape)?this._arrayShapeObject(e,t,i):this._anyShapeObject(e)}serialize(e){return e}_readCurrentUnion(e){let{selectedUnions:t}=this.opts;return ta(e,t)}_collectProperties(e){let{selectedUnions:t}=this.opts;return Os(e,t)}_nodeShapeObject(e,t={}){let i=t.forceName||_t(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(u=>{let{range:m,minCount:h=0}=u;if(h===0&&!this.opts.renderOptional||!m)return;let f=m;if(f.xmlSerialization&&f.xmlSerialization.attribute&&f.types.includes(d.aml.vocabularies.shapes.ScalarShape)){let v=He(f.xmlSerialization.name?f.xmlSerialization.name:u.name||f.name||va);f.xmlSerialization.prefix&&(v=`${f.xmlSerialization.prefix}:${v}`);let E=this._scalarValue(f);a.push(`${v}="${E}"`);return}let k=this._propertyShapeObject(u,{indent:s});if(typeof k<"u"){let v=t.noWrap?0:2,E=new Array(s*2+v).fill(" ").join("");r.push(Es(E,k))}}),t.noWrap)return r.join(`
37
+ `);let c=`<${i}`;a.length&&(c+=" ",c+=a.join(" ")),r.unshift(`${c}>`);let p=new Array(s*2).fill(" ").join("");return r.push(`${p}</${i}>`),r.join(`
38
+ `)}_scalarShapeObject(e,t={}){let{xmlSerialization:i,defaultValue:r}=e,s;r?s=new qe().processNode(r):s=this._scalarValue(e);let o=t.forceName||_t(e),a=[],l=[];if(i){let{namespace:p,prefix:u}=i;if(p){let m=u?`xmlns:${u}`:"xmlns";a.push(`${m}="${p}"`)}u&&(o=`${u}:${o}`)}let c=`<${o}`;return a.length&&(c+=" ",c+=a.join(" ")),c+=">",l.push(c),l.push(s),l.push(`</${o}>`),l.join("")}_nilShapeObject(e,t={}){let{xmlSerialization:i}=e,r="",s=t.forceName||_t(e),o=[],a=[];if(i){let{namespace:c,prefix:p}=i;if(c){let u=p?`xmlns:${p}`:"xmlns";o.push(`${u}="${c}"`)}p&&(s=`${p}:${s}`)}let l=`<${s}`;return o.length&&(l+=" ",l+=o.join(" ")),l+=">",a.push(l),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(d.aml.vocabularies.shapes.ScalarShape))return this._scalarShapeObject(i,{...t});if(s.includes(d.aml.vocabularies.shapes.NilShape)){let a=_t(e);return this._nilShapeObject(i,{...t,forceName:a})}if(s.includes(d.aml.vocabularies.shapes.RecursiveShape))return;if(s.includes(d.w3.shacl.NodeShape))return this._nodePropertyObject(e,t);if(s.includes(d.aml.vocabularies.shapes.ArrayShape)||s.includes(d.aml.vocabularies.shapes.MatrixShape))return this._nodePropertyArray(e,t);let o=_t(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:l}=e;Array.isArray(l)&&l.length&&l.forEach(m=>{let h=m;if(h.types.includes(d.aml.vocabularies.shapes.UnionShape)){let k=h,{anyOf:v=[]}=k;h=this._readCurrentUnion(v)}let f=h;Array.isArray(f.examples)&&f.examples.length&&(a=a.concat(f.examples))});let c=a.filter(m=>!!m.structuredValue);if(!c.length)return;let p=[];i&&p.push(`${s}<${r}>`);let u=new qe;return c.forEach(m=>{let h=u.generate(m.structuredValue,r,{indent:o+1});h!==void 0&&p.push(h)}),i&&p.push(`${s}</${r}>`),p.join(`
39
+ `)}_createTabs(e=0,t=0){return new Array(e*2+t).fill(" ").join("")}_nodePropertyObject(e,t={}){let i=[],r=He(String(e.name)),{indent:s=0}=t,o=this._createTabs(s),a,l=e.range,c=this._collectExamples(l,{tagFill:o,indent:s+1,nodeName:r}),p=[];if(c)a=c;else{let m=[];this._collectProperties(l).forEach(f=>{let{range:k,minCount:v=0}=f;if(v===0&&!this.opts.renderOptional)return;let E=k;if(E.xmlSerialization){let{prefix:j,attribute:C}=E.xmlSerialization;if(C&&E.types.includes(d.aml.vocabularies.shapes.ScalarShape)){let I=He(E.xmlSerialization.name?E.xmlSerialization.name:f.name||E.name||va);j&&(I=`${j}:${I}`);let T=this._scalarValue(E);p.push(`${I}="${T}"`);return}}let $=this._propertyShapeObject(f,{indent:s});if($!==void 0){let j=this._createTabs(s,2);m.push(Es(j,$))}}),a=m.join(`
40
+ `)}let u=`${o}<${r}`;return p.length&&(u+=" ",u+=p.join(" ")),i.unshift(`${u}>`),i.push(a),i.push(`${o}</${r}>`),i.join(`
41
+ `)}_nodePropertyArray(e,t={}){let i=e.range,r=[],s;i.xmlSerialization&&i.xmlSerialization.name?s=He(i.xmlSerialization.name):s=He(String(e.name));let{indent:o=0}=t,a=!!i.items&&i.items.types.includes(d.aml.vocabularies.shapes.ScalarShape),l=this._createTabs(o);a||r.push(`${l}<${s}>`);let c=this._arrayShapeObject(i,{...t,indent:o});return r.push(c),a||r.push(`${l}</${s}>`),r.join(`
42
+ `)}_arrayShapeObject(e,t={},i=!1){let{items:r}=e,s=!!r&&r.types.includes(d.aml.vocabularies.shapes.ScalarShape),o;i&&e.xmlSerialization&&e.xmlSerialization.name?o=He(e.xmlSerialization.name):i&&e.name?o=He(e.name):!s&&r?.name?o=He(r.name):e.name&&(o=He(e.name));let a=!1;e.xmlSerialization&&typeof e.xmlSerialization.wrapped=="boolean"&&(a=!0);let l=!!e.xmlSerialization&&!!e.xmlSerialization.wrapped,c=t.indent||0,p=new Array(c*2+0).fill(" ").join(""),u=new Array(c*2+(l?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 qe;if(s&&!l){let[v]=h;!o&&r?.name&&(o=He(r.name));let E=k.generate(v.structuredValue,o,{indent:c});E!==void 0&&f.push(E)}else if(s&&l){let[v]=h,E=k.generate(v.structuredValue,o,{indent:c});f.push(`${p}<${o}>`),E!==void 0&&f.push(E),f.push(`${p}</${o}>`)}else l?h.forEach(v=>{f.push(`${p}<${o}>`);let E=k.generate(v.structuredValue,void 0,{indent:c+2});E!==void 0&&f.push(E),f.push(`${p}</${o}>`)}):h.forEach(v=>{let E=k.generate(v.structuredValue,void 0,{indent:c});E!==void 0&&f.push(E)});return f.join(`
43
+ `)}}if(s&&e.defaultValue){let h=new qe().generate(e.defaultValue);return!o&&r?.name&&(o=He(r.name)),`<${o}>${h?.trim()}</${o}>`}if(r){let m=[];l&&s&&m.push(`${p}<${o}>`);let h={indent:c+1};o&&(h.forceName=o),!i&&(!a||a&&!l)&&(h.noWrap=!0);let f=this.processNode(r,h);return f!==void 0&&m.push(`${u}${f}`),l&&s&&m.push(`${p}</${o}>`),m.join(`
44
+ `)}return""}_scalarItems(e,t={}){let i=e.items,r=t.indent||0,s=new Array(r*2).fill(" ").join(""),o="";if(i.xmlSerialization&&i.xmlSerialization.name?o=He(i.xmlSerialization.name):o=_t(e.name?e:i),this.opts.renderExamples){let{examples:c=[]}=e;Array.isArray(i.examples)&&(c=c.concat(i.examples));let p=c.filter(u=>!!u.structuredValue);if(p.length){let u=[],m=new qe;return p.forEach(h=>{let f=m.generate(h.structuredValue,o);f!==void 0&&u.push(`${s}${f}`)}),u.join(`
45
+ `)}}if(e.defaultValue){let p=new qe().generate(e.defaultValue,o);if(p!==void 0)return`${s}${p}`}let a={indent:r+1,forceName:o},l=this.processNode(i,a);return`${s}${l}`}_nodeItems(e,t={}){let i=e.items,r=t.indent||0,s=new Array(r*2).fill(" ").join(""),o=e.xmlSerialization&&!!e.xmlSerialization.wrapped,a=e.defaultValue||i.defaultValue,l="";i.xmlSerialization&&i.xmlSerialization.name?l=He(i.xmlSerialization.name):l=_t(e.name?e:i);let c=o?new Array(r*2+2).fill(" ").join(""):s,p=[];o&&p.push(`${s}<${l}>`);let u=!1;if(this.opts.renderExamples){let{examples:m=[]}=e;Array.isArray(i.examples)&&(m=m.concat(i.examples));let h=m.filter(f=>!!f.structuredValue);if(h.length){let f=[],k=new qe;h.forEach(v=>{let E=k.generate(v.structuredValue,l);E!==void 0&&f.push(`${s}${E}`)}),u=!0}}if(!u&&a){let h=new qe().generate(a,l);h!==void 0&&(p.push(`${s}${h}`),u=!0)}return u||this._collectProperties(i).forEach(h=>{let f=this._propertyShapeObject(h);f&&p.push(`${c}${f}`)}),o&&p.push(`${s}</${l}>`),p.join(`
46
+ `)}_exampleToObject(e){if(e&&e.structuredValue)return new qe().generate(e.structuredValue)}_unionShapeObject(e,t={}){let{anyOf:i=[],examples:r=[]}=e;if(Array.isArray(e.inherits)&&e.inherits&&e.inherits.forEach(s=>{let o=s;Array.isArray(o.examples)&&o.examples.length&&(r=r.concat(o.examples));let a=s;Array.isArray(a.anyOf)&&a.anyOf.length&&(i=i.concat(a.anyOf))}),Array.isArray(i)&&i.length){if(this._isNotRequiredUnion(i))return;let s=r.find(l=>!!l.structuredValue),o=this._exampleToObject(s);if(o!==void 0){let l=_t(e),c=t.indent||0,p=new Array(c*2).fill(" ").join(""),u=new Array(c*2+2).fill(" ").join(""),m=[];m.push(`${p}<${l}>`);let h=String(o).split(`
47
47
  `).filter(f=>!!f).map(f=>`${u}${f}`).join(`
48
48
  `);return m.push(`${h}`),m.push(`${p}</${l}>`),m.join(`
49
- `)}if(e.defaultValue)return this._unionDefaultValue(e,e.defaultValue);let o=this._readCurrentUnion(i);if(o)return this.processNode(o,{...t,forceName:e.name})}}_unionDefaultValue(e,t,i={}){let s=new Ve().generate(t),o=_t(e),l=i.indent||0,c=new Array(l*2).fill(" ").join(""),p=[`${c}<${o}>`],u=new Array(l*2+2).fill(" ").join("");return p.push(`${u}${String(s).trim()}`),p.push(`${c}</${o}>`),p.join(`
50
- `)}_fileShapeObject(){}_schemaShapeObject(){}_tupleShapeObject(){}_anyShapeObject(e){let{and:t=[],xone:i=[],or:r=[]}=e;if(t.length){let o=structuredClone(e);return o.and=[],o.properties=[],t.forEach(l=>{let{types:c}=l;if(c.includes(d.aml.vocabularies.shapes.ScalarShape)){let p=l;o.properties.push(p)}else if(c.includes(d.w3.shacl.NodeShape))l.properties.forEach(u=>o.properties.push(u));else if(c.includes(d.aml.vocabularies.shapes.ArrayShape)||c.includes(d.aml.vocabularies.shapes.MatrixShape)){let p=l;p.items&&o.properties.push(p.items)}}),this._nodeShapeObject(o)}if(i.length){let{selectedUnions:o=[]}=this.opts,l=i.find(c=>o.includes(c.id));return l||(l=i[0]),this.processNode(l)}if(r.length){let{selectedUnions:o=[]}=this.opts,l=r.find(c=>o.includes(c.id));return l||(l=r[0]),this.processNode(l)}let{examples:s=[]}=e,a=_t(e);if(this.opts.renderExamples&&s&&s.length){let o=s.find(p=>!!p.structuredValue),l=this._exampleToObject(o),c=[];if(typeof l<"u"){let p=" ";c.push(`<${a}>`),c.push(`${p}${l}`),c.push(`</${a}>`)}return c.join(`
51
- `)}return this._scalarShapeObject(e)}};var Bn=Kl(Kn(),1);var Ms=Symbol("findAmfType"),qn=Symbol("findReferenceObject"),_e=Symbol("getArrayItems"),Jn=Symbol("computeReferenceSecurity"),fo=n=>{class e extends n{_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 Bn.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 a=r||s&&s["@context"];if(!a||!i)return i;let o=this.__cachedKeys;if(i in o)return o[i];i=String(i);let l=i.indexOf("#"),c=i.substring(0,l+1),p=Object.keys(a);for(let u=0,m=p.length;u<m;u++){let h=p[u];if(a[h]===i)return o[i]=h,h;if(l===-1&&i.indexOf(a[h])===0){let f=i.replace(a[h],`${h}:`);return o[i]=f,f}if(a[h]===c){let f=`${h}:${i.substring(l+1)}`;return o[i]=f,f}}return i}_ensureAmfModel(i){if(i&&(Array.isArray(i)&&([i]=i),this._hasType(i,d.aml.vocabularies.document.Document)))return i}_ensureArray(i){if(i)return i instanceof Array?i:[i]}_getValue(i,r,s){let a=this._getAmfKey(r,s);if(!a)return;let o=i&&i[a];if(!o)return o;if(Array.isArray(o)&&([o]=o),!o)return;let l=typeof o;return["string","number","boolean","undefined"].includes(l)?o:o["@value"]}_getValueArray(i,r,s){let a=this._getAmfKey(r,s);if(!a)return;let o=i&&this._ensureArray(i[a]);if(Array.isArray(o))return o.map(l=>l["@value"]||l)}[_e](i,r,s){let a=this._getAmfKey(r,s);if(!a)return;let o=i&&this._ensureArray(i[a]);if(Array.isArray(o))return o}_getLinkValue(i,r,s){let a=this._getAmfKey(r,s);if(!a)return;let o=i&&i[a];if(o&&(Array.isArray(o)&&([o]=o),!!o))return o["@id"]}_getLinkValues(i,r,s){let a=this._getAmfKey(r,s);if(!a)return;let o=i&&i[a];if(o)return Array.isArray(o)||(o=[o]),o.map(l=>l["@id"])}_hasType(i,r,s){let a=this._ensureArray(i&&i["@type"]);if(!a||!a.length)return!1;let o=this._getAmfKey(r,s);for(let l of a)if(l===o)return!0;return!1}_hasProperty(i,r,s){let a=this._getAmfKey(r,s);return!!(i&&a&&a in i)}_computePropertyArray(i,r,s){if(!i)return;let a=this._getAmfKey(r,s);if(!a)return;let o=this._ensureArray(i&&i[a]);if(!(!o||!Array.isArray(o)))return o}_computeApiVersion(i,r){let s=this._computeApi(i);if(s)return this._getValue(s,d.aml.vocabularies.core.version,r)}_computeEncodes(i,r){if(!i)return;Array.isArray(i)&&([i]=i);let s=this._getAmfKey(d.aml.vocabularies.document.encodes,r);if(!s)return;let a=i[s];if(a)return Array.isArray(a)?a[0]:a}_computeDeclares(i,r){if(!i||(Array.isArray(i)&&([i]=i),!i))return;let s=this._getAmfKey(d.aml.vocabularies.document.declares,r);if(!s)return;let a=this._ensureArray(i[s]);return Array.isArray(a)?a:void 0}_computeReferences(i,r){if(!i||(Array.isArray(i)&&([i]=i),!i))return;let s=this._getAmfKey(d.aml.vocabularies.document.references,r);if(!s)return;let a=this._ensureArray(i[s]);return a instanceof Array?a:void 0}_computeWebApi(i,r){let s=this._computeEncodes(i,r);if(s&&this._hasType(s,d.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,d.aml.vocabularies.apiContract.WebAPI,r):!1}_isAsyncAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,d.aml.vocabularies.apiContract.AsyncAPI,r):!1}_isAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,d.aml.vocabularies.apiContract.API,r):!1}_isValidServerPartial(i,r){if(Array.isArray(i)&&([i]=i),!i)return!1;let s=d.aml.vocabularies.apiContract.Operation,a=d.aml.vocabularies.apiContract.EndPoint,o=[this._getAmfKey(s,r),this._getAmfKey(a,r)],l=i["@type"];for(let c of l)if(o.indexOf(c)!==-1)return!0;return!1}_getServers(i={},r){let{endpointId:s,methodId:a}=i,{amf:o}=this;if(!o)return;let l=this._computeApi(o,r);if(Array.isArray(l)&&([l]=l),!l)if(this._isValidServerPartial(o,r))l=o;else return;let c=this._getAmfKey(d.aml.vocabularies.apiContract.server,r),p=()=>this[_e](l,c,r),u=()=>{let h=this._computeEndpointModel(l,s,r),f=this[_e](h,c,r);return f||p()},m=()=>{let h=this._computeMethodModel(l,a,r),f=this[_e](h,c,r);return f||u()};return a?m():s?u():p()}_computeExpects(i,r){let s=d.aml.vocabularies.apiContract.Operation,a=d.aml.vocabularies.apiContract.expects;if(this._hasType(i,s,r)){let o=this._getAmfKey(a,r),l=this._ensureArray(i[o]);if(l)return Array.isArray(l)?l[0]:l}}_computeEndpoints(i,r){if(!i)return[];let s=d.aml.vocabularies.apiContract.endpoint,a=this._getAmfKey(s,r);return this._ensureArray(i[a])}_computeEndpointModel(i,r,s){if(this._hasType(i,d.aml.vocabularies.apiContract.EndPoint,s))return i;let a=this._computeEndpoints(i,s);if(a)return a.find(o=>o["@id"]===r)}_computeMethodModel(i,r,s){let a=this.__computeMethodsListForMethod(i,r,s);if(a)return a.find(o=>o["@id"]===r)}_computeMethodEndpoint(i,r,s){if(!i||!r)return;if(this._hasType(i,d.aml.vocabularies.apiContract.EndPoint,s))return i;let a=this._computeEndpoints(i,s);if(!a)return;let o=this._getAmfKey(d.aml.vocabularies.apiContract.supportedOperation,s);for(let l=0,c=a.length;l<c;l++){let p=a[l],u=p[o];if(u){Array.isArray(u)||(u=[u]);for(let m=0,h=u.length;m<h;m++)if(u[m]["@id"]===r)return p}}}__computeMethodsListForMethod(i,r,s){let a=this._computeMethodEndpoint(i,r,s);if(!a)return;let o=this._getAmfKey(d.aml.vocabularies.apiContract.supportedOperation,s);return this._ensureArray(a[o])}_computeType(i,r,s,a){if(!i&&!r||!s)return;let o=s.replace("amf://id",""),l=i&&i.find(c=>c["@id"]===s||c["@id"]===o);if(!l&&r&&r.length)for(let c=0,p=r.length;c<p&&!(this._hasType(r[c],d.aml.vocabularies.document.Module)&&(l=this._computeReferenceType(r[c],s,a),l));c++);return l}[Ms](i,r){let{amf:s}=this;if(!s||!i)return;Array.isArray(s)&&([s]=s);let a=this._computeDeclares(s,r),o=i.replace("amf://id","");if(Array.isArray(a)){let l=a.find(c=>c["@id"]===i||c["@id"]===o);if(l)return l}return this[qn](i)}[qn](i,r){let{amf:s}=this;if(Array.isArray(s)&&([s]=s),!s)return;let a=this._computeReferences(s,r);if(!Array.isArray(a)||!a.length)return;let o=i.replace("amf://id","");for(let l=0,c=a.length;l<c;l++){let p=a[l],u=this._computeDeclares(p,r);if(Array.isArray(u))for(let m=0,h=u.length;m<h;m++){let f=u[m];if(Array.isArray(f)&&([f]=f),f["@id"]===i||f["@id"]===o)return f}}}_computeReferenceType(i,r,s){let a=this._computeDeclares(i,s);if(!a||!r)return;let o=r.replace("amf://id",""),l=a.find(c=>(Array.isArray(c)&&([c]=c),c["@id"]===r||c["@id"]===o));return Array.isArray(l)&&([l]=l),this._resolve(l)}_computeDocument(i,r,s){if(!i||!r)return;let a=this._getAmfKey(d.aml.vocabularies.core.documentation,s),o=this._ensureArray(i[a]);return o&&o.find(l=>l["@id"]===r)}_resolve(i,r){let{amf:s}=this;if(typeof i!="object"||Array.isArray(i)||!s||i.__apicResolved)return i;let a=this._getAmfKey(d.aml.vocabularies.document.linkTarget,r),o=this._ensureArray(i[a]),l;if(o){let u=o[0]["@id"];if(u===i["@id"])return i.__apicResolved=!0,i;l=this._getLinkTarget(s,u,r)}else if(a=this._getAmfKey(d.aml.vocabularies.document.referenceId,r),o=this._ensureArray(i[a]),o){let u=o[0]["@id"];if(u===i["@id"])return i.__apicResolved=!0,i;l=this._getReferenceId(s,u,r)}if(!l)return this._resolveRecursive(i),i.__apicResolved=!0,i;let c={...l};delete c["@id"];let p=c["@type"];return p&&(i["@type"]?i["@type"]=i["@type"].concat(p):i["@type"]=p,delete c["@type"]),this._mergeShapes(i,c,r),i.__apicResolved=!0,this._resolveRecursive(i),i}_getLinkTarget(i,r,s){if(!i||!r)return;let a,o=this._computeDeclares(i,s);if(o&&(a=this._findById(o,r)),!a){let l=this._computeReferences(i,s);a=this._obtainShapeFromReferences(l,r,s)}if(a)return a=this._resolve(a),a}_obtainShapeFromReferences(i,r,s){if(!Array.isArray(i)||!i.length)return;let a;for(let o of i){let l=this._computeEncodes(o,s);if(l&&l["@id"]===r){a=l;break}if(!l&&(a=this._findById(this._computeDeclares(o,s),r),a))break}return a}_findById(i,r){if(!i)return;let s;for(let a of i)if(a&&a["@id"]===r){s=a;break}return s}_getReferenceId(i,r,s){if(!i||!r)return;let a=this._computeReferences(i,s);if(a)for(let o of a){let l=this._computeEncodes(o,s);if(l&&l["@id"]===r)return l}}_resolveRecursive(i,r){Object.keys(i).forEach(s=>{let a=i[s];if(Array.isArray(a))for(let o=0,l=a.length;o<l;o++)a[o]=this._resolve(a[o]);else typeof a=="object"&&(i[s]=this._resolve(a,r))})}_mergeShapes(i,r,s){let a={...i,...r};return[{key:this._getAmfKey(d.aml.vocabularies.docSourceMaps.sources,s),merger:this._mergeSourceMapsSources.bind(this)}].forEach(({key:l,merger:c})=>{this._hasProperty(a,l,s)&&(a[l]=c(i,r,s))}),Object.assign(i,a)}_mergeSourceMapsSources(i,r,s){let a=this._getAmfKey(d.aml.vocabularies.docSourceMaps.sources,s),o=i[a]||{};Array.isArray(o)&&(o=o[0]);let l=r[a]||{};return Array.isArray(l)&&(l=l[0]),[Object.assign(o,l)]}_expandKey(i,r){let{amf:s}=this;if(!i||typeof i!="string"||!s&&!r)return i;Array.isArray(s)&&([s]=s);let a=r||s&&s["@context"];if(!a)return i;let[o,l]=i.split(":");if(!o||!l)return i;let c=a[o];return c?`${c}${l}`:i}findSecurityScheme(i,r){let{amf:s}=this,a=this._computeDeclares(s,r),o;if(a&&(o=a.find(c=>c["@id"]===i)),o)return o=this._resolve(o),o;let l=this._computeReferences(s,r);if(Array.isArray(l)&&l.length){for(let c of l)if(this._hasType(c,d.aml.vocabularies.document.Module,r)&&(o=this[Jn](c,i,r),o))return o=this._resolve(o),o}}[Jn](i,r,s){let a=this._computeDeclares(i,s);if(!a)return;let o=a.find(l=>{let c=l;return Array.isArray(c)&&([c]=c),c["@id"]===r});return Array.isArray(o)&&([o]=o),this._resolve(o)}getByType(i,r,s){if(!i)return[];let a=[],o=this._computeDeclares(i),l=this._getAmfKey(r,s);o&&o.length&&o.forEach(p=>{this._hasType(p,l)&&a.push(p)});let c=this._computeReferences(i);if(Array.isArray(c)&&c.length){for(let p of c)if(this._hasType(p,d.aml.vocabularies.document.Module)){let u=this.getByType(p,r,s);u.length&&(a=a.concat(u))}}return a}}return e};var go=class extends fo(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,d.aml.vocabularies.core.name,t);r&&typeof r=="string"&&(i.name=r);let s=this._getValue(e,d.aml.vocabularies.core.description,t);s&&typeof s=="string"&&(i.description=s);let a=this._getValue(e,d.aml.vocabularies.core.version,t);a&&typeof a=="string"&&(i.version=a);let o=this._getValue(e,d.aml.vocabularies.core.termsOfService,t);o&&typeof o=="string"&&(i.termsOfService=o);let l=e[this._getAmfKey(d.aml.vocabularies.apiContract.accepts,t)];Array.isArray(l)&&l.length&&(i.accepts=this._getValueArray(e,d.aml.vocabularies.apiContract.accepts,t));let c=e[this._getAmfKey(d.aml.vocabularies.apiContract.contentType,t)];Array.isArray(c)&&c.length&&(i.contentType=this._getValueArray(e,d.aml.vocabularies.apiContract.contentType,t));let p=e[this._getAmfKey(d.aml.vocabularies.apiContract.scheme,t)];Array.isArray(p)&&p.length&&(i.schemes=this._getValueArray(e,d.aml.vocabularies.apiContract.scheme,t));let u=e[this._getAmfKey(d.aml.vocabularies.core.provider,t)];Array.isArray(u)&&([u]=u),u&&(i.provider=this.provider(u));let m=e[this._getAmfKey(d.aml.vocabularies.core.license,t)];Array.isArray(m)&&([m]=m),m&&(i.license=this.license(m));let h=e[this._getAmfKey(d.aml.vocabularies.apiContract.tag,t)];Array.isArray(h)&&h.length&&(i.tags=h.map(v=>this.tag(v)));let f=e[this._getAmfKey(d.aml.vocabularies.core.documentation,t)];return Array.isArray(f)&&f.length&&(i.documentations=f.map(v=>this.documentation(v))),i}api(e,t){let i=t||e["@context"],r=this.apiSummary(e);r.endPoints=[],r.servers=[],r.security=[];let s=e[this._getAmfKey(d.aml.vocabularies.apiContract.endpoint,i)];Array.isArray(s)&&s.length&&(r.endPoints=s.map(l=>this.endPoint(l,i)));let a=e[this._getAmfKey(d.aml.vocabularies.apiContract.server,i)];Array.isArray(a)&&a.length&&(r.servers=a.map(l=>this.server(l,i)));let o=e[this._getAmfKey(d.aml.vocabularies.security.security,i)];return Array.isArray(o)&&o.length&&(r.security=o.map(l=>this.securityRequirement(l,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getLinkValue(e,d.aml.vocabularies.core.url,i);a&&typeof a=="string"&&(r.url=a);let o=this._getValue(e,d.aml.vocabularies.core.email,i);return o&&typeof o=="string"&&(r.email=o),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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getLinkValue(e,d.aml.vocabularies.core.url,i);return a&&typeof a=="string"&&(r.url=a),r}server(e,t){let i=t||e["@context"],r=this._getValue(e,d.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)},a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(s.description=a);let o=e[this._getAmfKey(d.aml.vocabularies.apiContract.variable,i)];Array.isArray(o)&&o.length&&(s.variables=o.map(u=>this.parameter(u,i)));let l=this._getValue(e,d.aml.vocabularies.apiContract.protocol,i),c=this._getValue(e,d.aml.vocabularies.apiContract.protocolVersion,i);l&&(s.protocol=l),c&&(s.protocolVersion=c);let p=e[this._getAmfKey(d.aml.vocabularies.security.security,i)];return Array.isArray(p)&&p.length&&(s.security=p.map(u=>this.securityRequirement(u,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.apiContract.paramName,i);a&&typeof a=="string"&&(r.paramName=a);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let l=this._getValue(e,d.aml.vocabularies.apiContract.required,i);typeof l=="boolean"&&(r.required=l);let c=this._getValue(e,d.aml.vocabularies.apiContract.allowEmptyValue,i);typeof c=="boolean"&&(r.allowEmptyValue=c);let p=this._getValue(e,d.aml.vocabularies.document.deprecated,i);typeof p=="boolean"&&(r.deprecated=p);let u=this._getValue(e,d.aml.vocabularies.apiContract.explode,i);typeof u=="boolean"&&(r.explode=u);let m=this._getValue(e,d.aml.vocabularies.apiContract.allowReserved,i);typeof m=="boolean"&&(r.allowReserved=m);let h=this._getValue(e,d.aml.vocabularies.apiContract.style,i);h&&typeof h=="string"&&(r.style=h);let f=this._getValue(e,d.aml.vocabularies.apiContract.binding,i);f&&typeof f=="string"&&(r.binding=f);let v=e[this._getAmfKey(d.aml.vocabularies.shapes.schema,i)];if(Array.isArray(v)&&v.length){let[I]=v;r.schema=this.unknownShape(I,{trackedId:e["@id"]},i)}let w=e[this._getAmfKey(d.aml.vocabularies.apiContract.payload,i)];Array.isArray(w)&&w.length&&(r.payloads=w.map(I=>this.payload(I,i)));let E=e[this._getAmfKey(d.aml.vocabularies.apiContract.examples,i)];return Array.isArray(E)&&E.length&&(r.examples=E.map(I=>this.example(I,i))),r}unknownShape(e,t,i){let r=i||e["@context"],s=this.readTypes(e["@type"],r);return s.includes(d.aml.vocabularies.shapes.ScalarShape)?this.scalarShape(e,t,r):s.includes(d.w3.shacl.NodeShape)?this.nodeShape(e,t,r):s.includes(d.aml.vocabularies.shapes.UnionShape)?this.unionShape(e,t,r):s.includes(d.aml.vocabularies.shapes.FileShape)?this.fileShape(e,t,r):s.includes(d.aml.vocabularies.shapes.SchemaShape)?this.schemaShape(e,t,r):s.includes(d.aml.vocabularies.shapes.TupleShape)?this.tupleShape(e,t,r):s.includes(d.aml.vocabularies.shapes.ArrayShape)||s.includes(d.aml.vocabularies.shapes.MatrixShape)?this.arrayShape(e,t,r):s.includes(d.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,d.aml.vocabularies.document.linkTarget,i)}getLinkTarget(e,t){let i=t||e["@context"],r=this._getLinkValue(e,d.aml.vocabularies.document.linkTarget,i);if(r)return this[Ms](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,d.aml.vocabularies.document.linkLabel,i);let V=this._getLinkValue(s,d.aml.vocabularies.document.linkTarget,i),O=this[Ms](V,i);O&&(s=O)}let a={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&&(a.linkLabel=r);let o=this._getValue(s,d.w3.shacl.name,i);o&&typeof o=="string"&&(a.name=o);let l=this._getValue(s,d.aml.vocabularies.core.displayName,i);if(l&&typeof l=="string")a.displayName=l;else{let V=this._getValue(s,d.aml.vocabularies.core.name,i);V&&typeof V=="string"&&(a.displayName=V)}let c=this._getValue(s,d.aml.vocabularies.core.description,i);c&&typeof c=="string"&&(a.description=c);let p=this._getValue(s,d.w3.shacl.defaultValueStr,i);p&&typeof p=="string"&&(a.defaultValueStr=p);let u=this._getValue(s,d.aml.vocabularies.shapes.deprecated,i);typeof u=="boolean"&&(a.deprecated=u);let m=this._getValue(s,d.aml.vocabularies.shapes.readOnly,i);typeof m=="boolean"&&(a.readOnly=m);let h=this._getValue(s,d.aml.vocabularies.shapes.writeOnly,i);typeof h=="boolean"&&(a.writeOnly=h);let f=s[this._getAmfKey(d.w3.shacl.defaultValue,i)];Array.isArray(f)&&f.length&&(a.defaultValue=this.unknownDataNode(f[0],i));let v=this._getAmfKey(d.w3.shacl.or,i),w=s[v];Array.isArray(w)&&w.length&&(a.or=w.map(V=>this.unknownShape(V,void 0,i)));let E=this._getAmfKey(d.w3.shacl.and,i),I=s[E];Array.isArray(I)&&I.length&&(a.and=I.map(V=>this.unknownShape(V,void 0,i)));let R=this._getAmfKey(d.w3.shacl.xone,i),C=s[R];Array.isArray(C)&&C.length&&(a.xone=C.map(V=>this.unknownShape(V,void 0,i)));let N=s[this._getAmfKey(d.w3.shacl.in,i)];if(Array.isArray(N)&&N.length){let[V]=N,O=d.w3.rdfSchema.key,k=this._getAmfKey(O,i);Object.keys(V).forEach(P=>{if(P.startsWith(O)||P.startsWith(k)){let U=V[P];Array.isArray(U)&&([U]=U);let z=this.unknownDataNode(U,i);z&&a.values.push(z)}})}let T=this._getAmfKey(d.w3.shacl.not,i),L=s[T];return L&&(Array.isArray(L)&&([L]=L),a.not=this.unknownShape(L,void 0,i)),a}anyShape(e,t={},i){let r=i||e["@context"],s=e,a=this.shape(s,r);if(this.isLink(s)){let p=this.getLinkTarget(s,r);p&&(s=p)}a.examples=[];let o=s[this._getAmfKey(d.aml.vocabularies.apiContract.examples,r)];if(Array.isArray(o)&&o.length)if(t.trackedId){let p=this.filterTrackedExamples(o,t.trackedId,r);a.examples=p.map(u=>this.example(u,r))}else{let p=this.filterNonTrackedExamples(o,r);a.examples=p.map(u=>this.example(u,r))}let l=s[this._getAmfKey(d.aml.vocabularies.core.documentation,r)];if(Array.isArray(l)&&l.length){let[p]=l;a.documentation=this.documentation(p,r)}let c=s[this._getAmfKey(d.aml.vocabularies.shapes.xmlSerialization,r)];return Array.isArray(c)&&c.length&&(a.xmlSerialization=this.xmlSerializer(c[0],r)),a}filterTrackedExamples(e,t,i){let{docSourceMaps:r}=d.aml.vocabularies,s=this._getAmfKey(r.sources,i),a=this._getAmfKey(r.trackedElement,i),o=t.indexOf("amf")===-1?`amf://id${t}`:t;return e.filter(l=>{let c=l;Array.isArray(c)&&([c]=c);let p=c[s];if(!p)return!0;Array.isArray(p)&&([p]=p);let u=p[a];if(!u)return!0;Array.isArray(u)&&([u]=u);let{value:m}=this.synthesizedField(u,i);if(!m)return!0;let h=m.split(",");return h.indexOf(o)!==-1||h.indexOf(t)!==-1})}filterNonTrackedExamples(e,t){let{docSourceMaps:i}=d.aml.vocabularies,r=this._getAmfKey(i.sources,t),s=this._getAmfKey(i.trackedElement,t);return e.filter(a=>{let o=a;Array.isArray(o)&&([o]=o);let l=o[r];if(!l)return!0;Array.isArray(l)&&([l]=l);let c=l[s];if(!c)return!0;Array.isArray(c)&&([c]=c);let{value:p}=this.synthesizedField(c,t);return!p})}scalarShape(e,t={},i){let r=i||e["@context"],s=e,a=this.anyShape(s,t,r);if(this.isLink(s)){let v=this.getLinkTarget(s,r);v&&(s=v)}let o=this._getValue(s,d.w3.shacl.pattern,r);o&&typeof o=="string"&&(a.pattern=o);let l=this._getLinkValue(s,d.w3.shacl.datatype,r);l&&typeof l=="string"&&(a.dataType=l);let c=this._getValue(s,d.aml.vocabularies.shapes.format,r);c&&typeof c=="string"&&(a.format=c);let p=this._getValue(s,d.aml.vocabularies.shapes.multipleOf,r);typeof p=="number"&&(a.multipleOf=p);let u=this._getValue(s,d.w3.shacl.minInclusive,r);typeof u=="number"&&(a.minimum=u,a.exclusiveMinimum=!1);let m=this._getValue(s,d.w3.shacl.maxInclusive,r);typeof m=="number"&&(a.maximum=m,a.exclusiveMaximum=!1);let h=this._getValue(s,d.w3.shacl.minLength,r);typeof h=="number"&&(a.minLength=h);let f=this._getValue(s,d.w3.shacl.maxLength,r);return typeof f=="number"&&(a.maxLength=f),a}nodeShape(e,t={},i){let r=i||e["@context"],s=e,a=this.anyShape(s,t,r);if(this.isLink(s)){let m=this.getLinkTarget(s,r);m&&(s=m)}let o=this._getValue(s,d.aml.vocabularies.shapes.discriminator,r);o&&typeof o=="string"&&(a.discriminator=o);let l=this._getValue(s,d.aml.vocabularies.shapes.discriminatorValue,r);l&&typeof l=="string"&&(a.discriminatorValue=l);let c=this._getValue(s,d.w3.shacl.closed,r);typeof c=="boolean"&&(a.closed=c),a.customShapeProperties=[],a.customShapePropertyDefinitions=[],a.dependencies=[];let p=s[this._getAmfKey(d.w3.shacl.property,r)];Array.isArray(p)&&p.length?a.properties=p.map(m=>this.propertyShape(m,r)):a.properties=[];let u=s[this._getAmfKey(d.w3.shacl.additionalPropertiesSchema,r)];if(Array.isArray(u)&&u.length===1){let[m]=u;a.additionalPropertiesSchema=this.unknownShape(m,void 0,r)}return a}propertyShape(e,t){let i=t||e["@context"],r=e,s=this.shape(r,i);if(this.isLink(r)){let p=this.getLinkTarget(r,i);p&&(r=p)}let a=this._getLinkValue(r,d.w3.shacl.path,i);a&&typeof a=="string"&&(s.path=a);let o=this._getValue(r,d.w3.shacl.minCount,i);typeof o=="number"&&(s.minCount=o);let l=this._getValue(r,d.w3.shacl.maxCount,i);typeof l=="number"&&(s.maxCount=l);let c=r[this._getAmfKey(d.aml.vocabularies.shapes.range,i)];if(Array.isArray(c)&&c.length){let[p]=c;s.range=this.unknownShape(p,void 0,i)}return s}unionShape(e,t={},i){let r=i||e["@context"],s=e[this._getAmfKey(d.aml.vocabularies.shapes.anyOf,r)],a=this.anyShape(e,t,r);if(Array.isArray(s)&&s.length){let o={...t,trackedId:void 0};a.anyOf=s.map(l=>this.unknownShape(l,o,r))}else a.anyOf=[];return a}fileShape(e,t={},i){let r=i||e["@context"],s=e,a=this.anyShape(s,t,r);if(this.isLink(s)){let v=this.getLinkTarget(s,r);v&&(s=v)}let o=this._getValue(s,d.w3.shacl.pattern,r);o&&typeof o=="string"&&(a.pattern=o);let l=this._getValueArray(s,d.aml.vocabularies.shapes.fileType,r);Array.isArray(l)&&l.length&&(a.fileTypes=l);let c=this._getValue(s,d.w3.shacl.minLength,r);typeof c=="number"&&(a.minLength=c);let p=this._getValue(s,d.w3.shacl.maxLength,r);typeof p=="number"&&(a.maxLength=p);let u=this._getValue(s,d.w3.shacl.minInclusive,r);typeof u=="number"&&(a.minimum=u,a.exclusiveMinimum=!1);let m=this._getValue(s,d.w3.shacl.maxInclusive,r);typeof m=="number"&&(a.maximum=m,a.exclusiveMaximum=!1);let h=this._getValue(s,d.aml.vocabularies.shapes.format,r);h&&typeof h=="string"&&(a.format=h);let f=this._getValue(s,d.aml.vocabularies.shapes.multipleOf,r);return typeof f=="number"&&(a.multipleOf=f),a}schemaShape(e,t={},i){let r=i||e["@context"],s=e,a=this.anyShape(s,t,r);if(this.isLink(s)){let c=this.getLinkTarget(s,r);c&&(s=c)}let o=this._getValue(s,d.aml.vocabularies.core.mediaType,r);o&&typeof o=="string"&&(a.mediaType=o);let l=this._getValue(s,d.aml.vocabularies.document.raw,r);return l&&typeof l=="string"&&(a.raw=l),a}recursiveShape(e,t){let i=t||e["@context"],r=e,s=this.shape(r,i);if(this.isLink(r)){let o=this.getLinkTarget(r,i);o&&(r=o)}let a=this._getLinkValue(r,d.aml.vocabularies.shapes.fixPoint,i);return a&&typeof a=="string"&&(s.fixPoint=a),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,a=this.dataArrangeShape(s,t,r);if(this.isLink(s)){let l=this.getLinkTarget(s,r);l&&(s=l)}let o=s[this._getAmfKey(d.aml.vocabularies.shapes.items,r)];if(Array.isArray(o)&&o.length){let[l]=o;a.items=this.unknownShape(l,void 0,r)}return a}tupleShape(e,t,i){let r=i||e["@context"],s=e,a=this.dataArrangeShape(s,t,r);if(this.isLink(s)){let c=this.getLinkTarget(s,r);c&&(s=c)}let o=s[this._getAmfKey(d.aml.vocabularies.shapes.items,r)],l=this._getAmfKey(d.w3.rdfSchema.key,r);return Array.isArray(o)&&o.length?(a.items=[],o.forEach(c=>{Array.isArray(c)&&([c]=c),Object.keys(c).filter(p=>p.startsWith(l)).forEach(p=>{let u=c[p];Array.isArray(u)&&([u]=u);let m=this.unknownShape(u,void 0,r);a.items.push(m)})})):a.items=[],a}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,d.aml.vocabularies.core.url,i);s&&typeof s=="string"&&(r.url=s);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let o=this._getValue(e,d.aml.vocabularies.core.title,i);return o&&typeof o=="string"&&(r.title=o),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,d.aml.vocabularies.document.strict,i);typeof s=="boolean"&&(r.strict=s);let a=this._getValue(e,d.aml.vocabularies.core.name,i);a&&typeof a=="string"&&(r.name=a);let o=this._getValue(e,d.aml.vocabularies.core.displayName,i);o&&typeof o=="string"&&(r.displayName=o);let l=this._getValue(e,d.aml.vocabularies.core.description,i);l&&typeof l=="string"&&(r.description=l);let c=this._getValue(e,d.aml.vocabularies.document.raw,i);c&&typeof c=="string"&&(r.value=c);let p=this._getValue(e,d.aml.vocabularies.document.location,i);p&&typeof p=="string"&&(r.location=p);let u=e[this._getAmfKey(d.aml.vocabularies.document.structuredValue,i)];if(Array.isArray(u)&&u.length){let[m]=u;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,d.aml.vocabularies.shapes.xmlAttribute,i);typeof s=="boolean"&&(r.attribute=s);let a=this._getValue(e,d.aml.vocabularies.shapes.xmlWrapped,i);typeof a=="boolean"&&(r.wrapped=a);let o=this._getValue(e,d.aml.vocabularies.shapes.xmlName,i);o&&typeof o=="string"&&(r.name=o);let l=this._getValue(e,d.aml.vocabularies.shapes.xmlNamespace,i);l&&typeof l=="string"&&(r.namespace=l);let c=this._getValue(e,d.aml.vocabularies.shapes.xmlPrefix,i);return c&&typeof c=="string"&&(r.prefix=c),r}unknownDataNode(e,t){let i=this.readTypes(e["@type"],t);if(i.includes(d.aml.vocabularies.data.Scalar))return this.scalarNode(e,t);if(i.includes(d.aml.vocabularies.data.Object))return this.objectNode(e,t);if(i.includes(d.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,d.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,d.aml.vocabularies.data.value,i);s&&typeof s=="string"&&(r.value=s);let a=this._getLinkValue(e,d.w3.shacl.datatype,i);return a&&typeof a=="string"&&(r.dataType=a),r}objectNode(e,t){let i=t||e["@context"],r=this.dataNode(e,t);r.properties={};let s=d.aml.vocabularies.data.key,a=`${this._getAmfKey(s,i)}:`;return Object.keys(e).forEach(o=>{if(o.startsWith(s)||o.startsWith(a)){let l=e[o];Array.isArray(l)&&([l]=l);let c=o.replace(s,"").replace(a,""),p=this.unknownDataNode(l,t);p&&(r.properties[c]=p)}}),r}arrayNode(e,t){let i=t||e["@context"],r=this.dataNode(e,i);r.members=[];let s=this._computePropertyArray(e,d.w3.rdfSchema.member);return Array.isArray(s)&&s.length&&s.forEach(a=>{let o=this.unknownDataNode(a);o&&r.members.push(o)}),r}customDomainProperties(e,t){let i=[],r=t||e["@context"],s=this._getLinkValues(e,d.aml.vocabularies.document.customDomainProperties,r);return Array.isArray(s)&&s.length&&s.forEach(a=>{let o=`@base:${a}`,l=e[a]||e[o];if(!l)return;Array.isArray(l)&&([l]=l);let c=this.unknownDataNode(l,r),p=this._getValue(l,d.aml.vocabularies.core.extensionName,r);if(!p||!c)return;let u={id:a,name:p,extension:c};i.push(u)}),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,d.aml.vocabularies.apiContract.path,i);s&&typeof s=="string"&&(r.path=s);let a=this._getValue(e,d.aml.vocabularies.core.name,i);a&&typeof a=="string"&&(r.name=a);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let l=this._getValue(e,d.aml.vocabularies.core.summary,i);l&&typeof l=="string"&&(r.summary=l);let c=this[_e](e,d.aml.vocabularies.apiContract.supportedOperation,i);Array.isArray(c)&&c.length&&(r.operations=c.map(v=>this.operation(v,i)));let p=this[_e](e,d.aml.vocabularies.apiContract.parameter,i);Array.isArray(p)&&p.length&&(r.parameters=p.map(v=>this.parameter(v,i)));let u=this[_e](e,d.aml.vocabularies.apiContract.payload,i);Array.isArray(u)&&u.length&&(r.payloads=u.map(v=>this.payload(v,i)));let m=this[_e](e,d.aml.vocabularies.apiContract.server,i);Array.isArray(m)&&m.length&&(r.servers=m.map(v=>this.server(v,i)));let h=this[_e](e,d.aml.vocabularies.security.security,i);Array.isArray(h)&&h.length&&(r.security=h.map(v=>this.securityRequirement(v,i)));let f=this[_e](e,d.aml.vocabularies.document.extends,i);return Array.isArray(f)&&f.length&&(r.extends=[],f.forEach(v=>{let w=v;Array.isArray(w)&&([w]=w),this._hasType(w,d.aml.vocabularies.apiContract.ParametrizedResourceType,i)?r.extends.push(this.parametrizedResourceType(w,i)):this._hasType(w,d.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,d.aml.vocabularies.apiContract.method,i);s&&typeof s=="string"&&(r.method=s);let a=this._getValue(e,d.aml.vocabularies.core.name,i);a&&typeof a=="string"&&(r.name=a);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let l=this._getValue(e,d.aml.vocabularies.apiContract.guiSummary,i);l&&typeof l=="string"&&(r.summary=l);let c=this._getValue(e,d.aml.vocabularies.core.deprecated,i);typeof c=="boolean"&&(r.deprecated=c);let p=this._getValue(e,d.aml.vocabularies.apiContract.operationId,i);p&&typeof p=="string"&&(r.operationId=p);let u=this._getValueArray(e,d.aml.vocabularies.apiContract.accepts,i);Array.isArray(u)&&(r.accepts=u);let m=this._getValueArray(e,d.aml.vocabularies.apiContract.scheme,i);Array.isArray(m)&&(r.schemes=m);let h=this._getValueArray(e,d.aml.vocabularies.apiContract.contentType,i);Array.isArray(h)&&(r.contentType=h);let f=e[this._getAmfKey(d.aml.vocabularies.apiContract.expects,i)];f&&(Array.isArray(f)&&([f]=f),r.request=this.request(f,i));let v=e[this._getAmfKey(d.aml.vocabularies.core.documentation,i)];v&&(Array.isArray(v)&&([v]=v),r.documentation=this.documentation(v,i));let w=e[this._getAmfKey(d.aml.vocabularies.apiContract.returns,i)];Array.isArray(w)&&(r.responses=w.map(T=>this.response(T,i)));let E=e[this._getAmfKey(d.aml.vocabularies.apiContract.callback,i)];Array.isArray(E)&&(r.callbacks=E.map(T=>this.callback(T,i)));let I=e[this._getAmfKey(d.aml.vocabularies.apiContract.server,i)];Array.isArray(I)&&(r.servers=I.map(T=>this.server(T)));let R=e[this._getAmfKey(d.aml.vocabularies.security.security,i)];Array.isArray(R)&&(r.security=R.map(T=>this.securityRequirement(T,i)));let C=e[this._getAmfKey(d.aml.vocabularies.apiContract.tag,i)];Array.isArray(C)&&C.length&&(r.tags=C.map(T=>this.tag(T,i)));let N=e[this._getAmfKey(d.aml.vocabularies.document.extends,i)];return Array.isArray(N)&&N.length&&(r.extends=N.map(T=>this.parametrizedTrait(T,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let o=e[this._getAmfKey(d.aml.vocabularies.core.documentation,i)];return o&&(Array.isArray(o)&&([o]=o),r.documentation=this.documentation(o,i)),r}tagListItem(e,t){let i=t||e["@context"],r={id:e["@id"],name:""},s=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.apiContract.expression,i);a&&typeof a=="string"&&(r.expression=a);let o=e[this._getAmfKey(d.aml.vocabularies.apiContract.endpoint,i)];return o&&(Array.isArray(o)&&([o]=o),r.endpoint=this.endPoint(o,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,d.aml.vocabularies.core.description,i);s&&typeof s=="string"&&(r.description=s);let a=this._getValue(e,d.aml.vocabularies.apiContract.required,i);a&&typeof a=="boolean"&&(r.required=a);let o=e[this._getAmfKey(d.aml.vocabularies.apiContract.queryString,i)];o&&(Array.isArray(o)&&([o]=o),r.queryString=this.unknownShape(o,void 0,i));let l=this[_e](e,d.aml.vocabularies.apiContract.header,i);Array.isArray(l)&&l.length&&(r.headers=l.map(h=>this.parameter(h,i)));let c=this[_e](e,d.aml.vocabularies.apiContract.parameter,i);Array.isArray(c)&&c.length&&(r.queryParameters=c.map(h=>this.parameter(h,i)));let p=this[_e](e,d.aml.vocabularies.apiContract.uriParameter,i);Array.isArray(p)&&p.length&&(r.uriParameters=p.map(h=>this.parameter(h,i)));let u=this[_e](e,d.aml.vocabularies.apiContract.cookieParameter,i);Array.isArray(u)&&u.length&&(r.cookieParameters=u.map(h=>this.parameter(h,i)));let m=this[_e](e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let o=this._getValue(e,d.aml.vocabularies.apiContract.statusCode,i);o&&typeof o=="string"&&(r.statusCode=o);let l=this[_e](e,d.aml.vocabularies.apiContract.header,i);Array.isArray(l)&&l.length&&(r.headers=l.map(m=>this.parameter(m,i)));let c=this[_e](e,d.aml.vocabularies.apiContract.payload,i);Array.isArray(c)&&c.length&&(r.payloads=c.map(m=>this.payload(m,i)));let p=e[this._getAmfKey(d.aml.vocabularies.apiContract.examples,i)];Array.isArray(p)&&p.length&&(r.examples=p.map(m=>this.example(m,i)));let u=e[this._getAmfKey(d.aml.vocabularies.apiContract.link,i)];return Array.isArray(u)&&u.length&&(r.links=u.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.core.mediaType,i);a&&typeof a=="string"&&(r.mediaType=a);let o=e[this._getAmfKey(d.aml.vocabularies.shapes.schema,i)];o&&(Array.isArray(o)&&([o]=o),r.schema=this.unknownShape(o,{trackedId:r.id},i));let l=e[this._getAmfKey(d.aml.vocabularies.apiContract.examples,i)];return Array.isArray(l)&&l.length&&(r.examples=l.map(c=>this.example(c,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let o=this._getValue(e,d.aml.vocabularies.apiContract.operationId,i);o&&typeof o=="string"&&(r.operationId=o);let l=e[this._getAmfKey(d.aml.vocabularies.apiContract.server,i)];l&&(Array.isArray(l)&&([l]=l),r.server=this.server(l,i));let c=e[this._getAmfKey(d.aml.vocabularies.apiContract.mapping,i)];return c&&(c&&!Array.isArray(c)&&(c=[c]),c&&(r.mapping=c.map(p=>this.iriTemplateMapping(p,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,d.aml.vocabularies.apiContract.templateVariable,i);s&&typeof s=="string"&&(r.templateVariable=s);let a=this._getValue(e,d.aml.vocabularies.apiContract.linkExpression,i);return a&&typeof a=="string"&&(r.linkExpression=a),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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=e[this._getAmfKey(d.aml.vocabularies.security.scheme,i)];a&&(Array.isArray(a)&&([a]=a),r.scheme=this.securityScheme(a,i));let o=e[this._getAmfKey(d.aml.vocabularies.security.settings,i)];return o&&(Array.isArray(o)&&([o]=o),r.settings=this.securitySettings(o,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,d.aml.vocabularies.security.type,i);s&&typeof s=="string"&&(r.type=s);let a=this._getValue(e,d.aml.vocabularies.core.name,i);a&&typeof a=="string"&&(r.name=a);let o=this._getValue(e,d.aml.vocabularies.core.displayName,i);return o&&typeof o=="string"&&(r.displayName=o),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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.core.displayName,i);a&&typeof a=="string"&&(r.displayName=a);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let l=this._getValue(e,d.aml.vocabularies.security.type,i);l&&typeof l=="string"&&(r.type=l);let c=e[this._getAmfKey(d.aml.vocabularies.security.settings,i)];c&&(Array.isArray(c)&&([c]=c),r.settings=this.securitySettings(c,i));let p=e[this._getAmfKey(d.aml.vocabularies.apiContract.queryString,i)];p&&(Array.isArray(p)&&([p]=p),r.queryString=this.unknownShape(p,void 0,i));let u=this[_e](e,d.aml.vocabularies.apiContract.header,i);Array.isArray(u)&&u.length&&(r.headers=u.map(f=>this.parameter(f,i)));let m=this[_e](e,d.aml.vocabularies.apiContract.parameter,i);Array.isArray(m)&&m.length&&(r.queryParameters=m.map(f=>this.parameter(f,i)));let h=this[_e](e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=e[this._getAmfKey(d.aml.vocabularies.security.schemes,i)];return Array.isArray(a)&&a.length&&(r.schemes=a.map(o=>this.parametrizedSecurityScheme(o,i))),r}securitySettings(e,t){let i=t||e["@context"],r=this.readTypes(e["@type"],i);return r.includes(d.aml.vocabularies.security.OAuth1Settings)?this.oAuth1Settings(e,i):r.includes(d.aml.vocabularies.security.OAuth2Settings)?this.oAuth2Settings(e,i):r.includes(d.aml.vocabularies.security.ApiKeySettings)?this.apiKeySettings(e,i):r.includes(d.aml.vocabularies.security.HttpSettings)?this.httpSettings(e,i):r.includes(d.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,d.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let a=this._getValue(e,d.aml.vocabularies.security.requestTokenUri,i);a&&typeof a=="string"&&(r.requestTokenUri=a);let o=this._getValue(e,d.aml.vocabularies.security.tokenCredentialsUri,i);o&&typeof o=="string"&&(r.tokenCredentialsUri=o);let l=this._getValueArray(e,d.aml.vocabularies.security.signature,i);return Array.isArray(l)&&l.length?r.signatures=l:r.signatures=[],r}oAuth2Settings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValueArray(e,d.aml.vocabularies.security.authorizationGrant,i);Array.isArray(s)&&s.length?r.authorizationGrants=s:r.authorizationGrants=[];let a=e[this._getAmfKey(d.aml.vocabularies.security.flows,i)];return Array.isArray(a)&&a.length?r.flows=a.map(o=>this.oAuth2Flow(o,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,d.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let a=this._getValue(e,d.aml.vocabularies.security.accessTokenUri,i);a&&typeof a=="string"&&(r.accessTokenUri=a);let o=this._getValue(e,d.aml.vocabularies.security.flow,i);o&&typeof o=="string"&&(r.flow=o);let l=this._getValue(e,d.aml.vocabularies.security.refreshUri,i);l&&typeof l=="string"&&(r.refreshUri=l);let c=e[this._getAmfKey(d.aml.vocabularies.security.scope,i)];return Array.isArray(c)&&c.length&&(r.scopes=c.map(p=>this.scope(p,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.core.description,i);return a&&typeof a=="string"&&(r.description=a),r}apiKeySettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=this._getValue(e,d.aml.vocabularies.security.in,i);return a&&typeof a=="string"&&(r.in=a),r}httpSettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,d.aml.vocabularies.security.scheme,i);s&&typeof s=="string"&&(r.scheme=s);let a=this._getValue(e,d.aml.vocabularies.security.bearerFormat,i);return a&&typeof a=="string"&&(r.bearerFormat=a),r}openIdConnectSettings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValue(e,d.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(d.aml.vocabularies.docSourceMaps.sources,i)];if(!r)return;Array.isArray(r)&&([r]=r);let s={id:r["@id"],types:this.readTypes(r["@type"])},a=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.synthesizedField,i)];Array.isArray(a)&&a.length&&(s.synthesizedField=a.map(m=>this.synthesizedField(m,i)));let o=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.lexical,i)];Array.isArray(o)&&o.length&&(s.lexical=o.map(m=>this.synthesizedField(m,i)));let l=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.trackedElement,i)];Array.isArray(l)&&l.length&&(s.trackedElement=this.synthesizedField(l[0],i));let c=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.autoGeneratedName,i)];Array.isArray(c)&&c.length&&(s.autoGeneratedName=c.map(m=>this.synthesizedField(m,i)));let p=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.parsedJsonSchema,i)];Array.isArray(p)&&p.length&&(s.parsedJsonSchema=this.synthesizedField(p[0],i));let u=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.declaredElement,i)];return Array.isArray(u)&&u.length&&(s.declaredElement=this.synthesizedField(u[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,d.aml.vocabularies.docSourceMaps.element,t);typeof r=="string"&&(i.element=r);let s=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let a=e[this._getAmfKey(d.aml.vocabularies.document.variable,i)];Array.isArray(a)&&a.forEach(l=>{r.variables.push(this.variableValue(l,i))});let o=e[this._getAmfKey(d.aml.vocabularies.document.target,i)];if(Array.isArray(o)&&o.length){let[l]=o;r.target=this.abstractDeclaration(l,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,d.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},a=e[this._getAmfKey(d.aml.vocabularies.document.value,i)];if(Array.isArray(a)){let[o]=a;s.value=this.unknownDataNode(o,i)}return s}abstractDeclaration(e,t){let i=t||e["@context"],r=this._getValue(e,d.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:[]},a=this._getValueArray(e,d.aml.vocabularies.document.variable,i);Array.isArray(a)&&(s.variables=a);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(s.description=o);let l=e[this._getAmfKey(d.aml.vocabularies.document.dataNode,i)];if(Array.isArray(l)){let[c]=l;s.dataNode=this.unknownDataNode(c,i)}return s}endPointWithOperationsListItem(e,t){let i=this._getValue(e,d.aml.vocabularies.apiContract.path,t),r={id:e["@id"],path:i,operations:[]},s=this[_e](e,d.aml.vocabularies.apiContract.supportedOperation,t);Array.isArray(s)&&s.length&&(r.operations=s.map(o=>this.operationListItem(o,t)));let a=this._getValue(e,d.aml.vocabularies.core.name,t);return a&&typeof a=="string"&&(r.name=a),r}operationListItem(e,t){let i={id:e["@id"],method:""},r=this._getValue(e,d.aml.vocabularies.apiContract.method,t);r&&typeof r=="string"&&(i.method=r);let s=this._getValue(e,d.aml.vocabularies.core.name,t);return s&&typeof s=="string"&&(i.name=s),i}};var ui=class n{mime;opts;generator;constructor(e,t={}){this.mime=e,this.opts=Object.freeze({...t}),e.includes("json")?this.generator=new nr(t):e.includes("xml")&&(this.generator=new lr(t))}static asExample(e,t,i){return new n(t,i).toExample(e)}static asSchema(e,t,i){return new n(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:[d.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 Ii=Object.freeze({processApiLink:"amfprocessapilink",processBuffer:"amfprocessbuffer",processApiFile:"amfprocessapifile",selectApiMainFile:"amfselectapimainfile"});var tp=Object.freeze({processApiLink:async(n,e,t,i,r=globalThis)=>{let s=new CustomEvent(Ii.processApiLink,{bubbles:!0,composed:!0,cancelable:!0,detail:{url:n,mainFile:e,md5:t,packaging:i}});return r.dispatchEvent(s),s.detail.result},processBuffer:async(n,e,t=globalThis)=>{let i=new CustomEvent(Ii.processBuffer,{bubbles:!0,composed:!0,cancelable:!0,detail:{buffer:n,opts:e}});return t.dispatchEvent(i),i.detail.result},processApiFile:async(n,e=globalThis)=>{let t=new CustomEvent(Ii.processApiFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{file:n}});return e.dispatchEvent(t),t.detail.result},selectApiMainFile:async(n,e=globalThis)=>{let t=new CustomEvent(Ii.selectApiMainFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{candidates:n}});return e.dispatchEvent(t),t.detail.result}});var yo=["string","number","boolean","date","datetime","time","binary","json"],cr;(function(n){n.string="string",n.number="number",n.boolean="boolean",n.date="date",n.datetime="datetime",n.time="time",n.file="binary",n.json="json"})(cr||(cr={}));var Gn=["required","multiple","primary","index","unique","search","readOnly","writeOnly","deprecated"],Hn=["required","multiple"],Wn=["float","double","int32","int64"];function Ls(n,e){return n==="number"?e?.format==="int32"||e?.format==="int64"?d.w3.xmlSchema.integer:d.w3.xmlSchema.number:n==="boolean"?d.aml.vocabularies.shapes.boolean:n==="date"?d.w3.xmlSchema.date:n==="datetime"?d.w3.xmlSchema.dateTime:n==="time"?d.aml.vocabularies.shapes.dateTimeOnly:d.w3.xmlSchema.string}var mi=Symbol("noValue"),dr=class{increment=0;static noValue=mi;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):mi}generateString(e){switch(e){case"random":return Q(8);case"uuid-v4":return crypto.randomUUID();default:return mi}}generateNumber(e){return e==="incremental"?`${this.increment++}`:mi}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 mi}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 mi}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"),a=`${t.getHours()}`.padStart(2,"0"),o=`${t.getMinutes()}`.padStart(2,"0"),l=`${t.getSeconds()}`.padStart(2,"0");return`${i}-${r}-${s}T${a}:${o}:${l}`}return mi}};var bo="anyOf",ip="allOf",rp="oneOf",sp="not",ko="string",Xn="binary",ei=class{#e;get valueGenerator(){return this.#e||(this.#e=new dr),this.#e}entity(e,t=new Set){if(t.has(e.key))return this.createRecursiveShape(e);t.add(e.key);let i=Je.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 a=this.property(r);i.properties.push(a)}for(let r of e.listAssociations()){let s=r.readBinding("web");if(s&&s.hidden)continue;let a=this.associationProperty(r,t);i.properties.push(a)}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=Je.propertyShape(i);return r.path=`${d.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=Je.propertyShape(r);return s.path=`${d.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||bo)===sp){let a=Je.anyShape(e.key);return a.id=`not-shape-${e.key}`,a.not=r,a}return e.multiple?this.refactorShapeToArray(e.key,r):r}createLinkedShape(e){let t=Je.scalarShape(e.key);return t.id=`link-${e.key}`,t.dataType=Ls(ko),t}createUnionShape(e,t){let i=Je.unionShape(e.key);this.updateBaseProperties(e,i),i.anyOf=[];let r=e.schema&&e.schema.unionType||bo;return r===bo?i.anyOf=t:r===ip?i.and=t:r===rp?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===Xn?this.createFileShape(e,t):this.createScalarShape(e,i,t)}setShapeSchema(e,t,i,r,s){if(i.defaultValue){let{type:a}=i.defaultValue,{value:o}=i.defaultValue;if(a==="function"){let l=this.valueGenerator.generate(o,e.type);if(l!==dr.noValue){let c=kt.scalar(l,a);t.defaultValue=c.toJSON()}}else{let l=kt.scalar(o,r);t.defaultValue=l.toJSON()}}Array.isArray(i.enum)&&(t.values=i.enum.map(a=>kt.scalar(a,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=Je.arrayShape(e.key),{type:s}=e;if(s===Xn?r.items=this.createFileShape(e,i):r.items=this.createScalarShape(e,void 0,i),t){let a=r.items.dataType;this.setShapeSchema(e,r,t,a,e.multiple)}return r}createScalarShape(e,t,i){let r=Je.scalarShape(e.key);return this.updateBaseProperties(e,r),this.setScalarCommonProperties(r,e,i),r.dataType||(r.dataType=Ls(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:Q(),customDomainProperties:[],strict:!0,types:[...er.IAmfExampleTypes],structuredValue:kt.scalar(r,t).toJSON()};i.push(s)}return i}createArrayExamples(e,t){let i={id:Q(),customDomainProperties:[],strict:!0,types:[...er.IAmfExampleTypes]},r=new kt("array");for(let s of e){let a=kt.scalar(s,t);r.addMember(a)}return i.structuredValue=r.toJSON(),[i]}createFileShape(e,t){let i=Je.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===ko?e.minLength=r.minimum:e.minimum=r.minimum),typeof r.maximum=="number"&&(s===ko?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=d.w3.xmlSchema.double;break;case"float":e.format=d.w3.xmlSchema.float;break;case"int32":e.format=d.w3.xmlSchema.integer;break;case"int64":e.format=d.w3.xmlSchema.integer;break}typeof t.readOnly=="boolean"&&(e.readOnly=t.readOnly),typeof t.writeOnly=="boolean"&&(e.writeOnly=t.writeOnly);let a=r?.examples&&r.examples.length>0,o=r?.defaultValue?.value!==void 0;if(t.required&&!t.readOnly&&!a&&!o){let l="";t.type==="number"?l=0:t.type==="boolean"&&(l=!1);let c=("dataType"in e?e.dataType:void 0)||Ls(t.type,i);e.examples=this.createExamples([String(l)],c)}}updateBaseProperties(e,t){t.name=e.info.name,t.displayName=e.info.displayName,t.description=e.info.description,(e.kind===he||e.kind===j)&&(t.deprecated=e.deprecated)}createRecursiveShape(e){return Je.recursiveShape(e.key,e.key)}refactorShapeToArray(e,t){let i=Je.arrayShape(e);return i.items=t,i}};var ti=class n extends et{kind;info;required;multiple;primary;unique;index;search;readOnly;writeOnly;deprecated;tags=[];semantics=[];type="string";jsonSchema;jsonIndex;schema;bindings=[];lineage;static createSchema(e={}){let{key:t=Q(),multiple:i,required:r,type:s=cr.string,index:a,search:o,primary:l,unique:c,readOnly:p,writeOnly:u,tags:m,semantics:h,deprecated:f,schema:v,bindings:w,jsonSchema:E,jsonIndex:I,lineage:R}=e;if(typeof s=="string"&&!yo.includes(s))throw new Error(`Invalid data property type ${s}`);let C=pe.fromJSON(e.info,{name:"new_property"}).toJSON(),N={kind:he,key:t,info:C,type:s};return E&&(N.jsonSchema=structuredClone(E)),I&&(N.jsonIndex=structuredClone(I)),typeof i=="boolean"&&(N.multiple=i),typeof r=="boolean"&&(N.required=r),typeof a=="boolean"&&(N.index=a),typeof o=="boolean"&&(N.search=o),typeof l=="boolean"&&(N.primary=l),typeof c=="boolean"&&(N.unique=c),typeof p=="boolean"&&(N.readOnly=p),typeof u=="boolean"&&(N.writeOnly=u),typeof f=="boolean"&&(N.deprecated=f),Array.isArray(m)&&(N.tags=[...m]),Array.isArray(h)&&(N.semantics=[...h]),v&&(N.schema=structuredClone(v)),Array.isArray(w)?N.bindings=w.map(T=>structuredClone(T)):N.bindings=[],R&&(N.lineage=structuredClone(R)),N}parent;constructor(e,t,i={}){let r=n.createSchema(i);super(e,r.key),this.parent=t,this.kind=he,this.info=new pe(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.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!==he)}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON(),type:this.type||cr.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.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:yo.includes(e)}static isValidAttribute(e){return typeof e!="string"?!1:Gn.includes(e)}static isValidFormat(e){return e===void 0?!0:typeof e!="string"?!1:!!Wn.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 g(`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 ei().property(this)}toExample(e,t={}){let i=this.toApiShape();return i.range?new ui(e,{renderExamples:t.renderExamples??!0,renderMocked:t.renderMocked??!0,renderOptional:t.renderOptional??!0,selectedUnions:t.selectedUnions}).generate(i):void 0}addSemantic(e){this.root.ensureWritable();let t=dt[e.id];if(!ls(t))throw new Error(`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 Error(`Cannot duplicate property ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(c=>c.key===this.key);if(t===-1)throw new Error(`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 a=e.addProperty(s),o=e.fields.length-1,l=e.fields[o];return e.fields.splice(o,1),e.fields.splice(t+1,0,l),a}setLineage(e,t){this.lineage={id:t,key:e.key,kind:e.kind},e.namespace!==this.root.key&&(this.lineage.domain=e.namespace)}};var ii=class extends g{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 Le(n,e){if(!n.hasNode(e))return;let t=n.node(e);if(t){if(t.kind===de){n.removeNode(e);return}for(let i of n.children(e))Le(n,i);for(let i of n.outEdges(e)){let r=n.edge(i);r&&(r.type==="association"||r.type==="property")&&Le(n,i.w)}n.removeNode(e)}}var ji=class n extends et{kind;info;required;multiple;schema;bindings;parent;targets;semantics=[];onDelete;readOnly;fields;static createSchema(e={}){let{key:t=Q(),semantics:i=[]}=e,r=pe.fromJSON(e.info,{name:"new_association"}).toJSON(),s={kind:de,key:t,info:r};return 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(a=>structuredClone(a))),Array.isArray(e.targets)&&(s.targets=e.targets.map(a=>({...a}))),Array.isArray(e.fields)&&(s.fields=[...e.fields]),s}constructor(e,t,i){let r=n.createSchema(i);super(e,r.key),this.parent=t,this.kind=de,this.info=new pe(r.info),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)}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 ti(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(){for(let{key:e}of this.fields){let t=this.root.graph.node(e);!t||t.kind!==he||(yield t)}}removeProperty(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e&&r.type==="property");if(!this.root.graph.hasNode(e))throw new ii(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new ii(`Trying to remove the ${e} property, but it doesn't belong to this association`);Le(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(){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(){return this.schema||(this.schema={}),this.schema}static isValidAttribute(e){return typeof e!="string"?!1:Hn.includes(e)}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 g(`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){this.root.ensureWritable();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(o=>o.key===i&&o.domain===t)){let o=`Target ${i} already exists.`;throw new Error(o)}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,a={type:"association"};t&&(a.domain=t,a.foreign=!0),this.root.graph.setEdge(this.key,s,a)}removeTarget(e){this.root.ensureWritable();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)}*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 ei().associationProperty(this)}checkPreconditions(e){let t=dt[e];if(!(!t||!cs(t)||!t.preconditions||t.preconditions.length===0)){for(let i of t.preconditions)if(i.kind==="associationMultiple"){if(this.multiple!==i.multiple)throw new g(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 g(i.unmetMessage||`Parent entity is required to evaluate entity pairing preconditions for semantic ${e}.`,{status:400});if(!i.entityPairs.some(o=>(Array.isArray(o.parent)?o.parent.some(p=>r.hasSemantic(p)):r.hasSemantic(o.parent))?s.some(p=>Array.isArray(o.target)?o.target.some(u=>p.hasSemantic(u)):p.hasSemantic(o.target)):!1))throw new g(i.unmetMessage||`Association entity pairing precondition check failed for semantic ${e}.`,{status:400})}}}getReciprocalAssociations(e){let t=[],i=this.root,r=this.getParentInstance()?.key??"";for(let s of i.listEntities())for(let a of s.listAssociations())if(!(a.key===this.key&&s.key===r)){for(let o of a.semantics)if(o.link&&o.link.key===this.key&&(!e||o.id===e)){t.push(a);break}}return t}toggleOptionalSemanticProperty(e,t,i){this.root.ensureWritable();let r=dt[e];if(!r||!cs(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 a=r.properties?.find(c=>c.value.info?.name===t);if(!a)throw new Error(`Property "${t}" is not defined in semantic blueprint ${e}.`);let l=Array.from(this.listProperties()).find(c=>c.info.name===t||c.lineage?.id===e&&c.info.name===t);if(i){if(l)return l;let c={...a.value,lineage:{key:this.key,kind:de,domain:this.root.key,id:e}};return this.addProperty(c)}else{l&&l.remove();return}}addSemantic(e){this.root.ensureWritable();let t=dt[e.id];if(!cs(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(o=>o.info.name===s||o.lineage?.id===e.id&&o.info.name===s)){let o={...r.value,lineage:{key:this.key,kind:de,domain:this.root.key,id:e.id}};this.addProperty(o)}})}removeSemantic(e){this.root.ensureWritable();let t=this.semantics.findIndex(s=>s.id===e);t>=0&&this.semantics.splice(t,1);let i=Array.from(this.listProperties()).filter(s=>s.lineage?.id===e);for(let s of i)s.remove();let r=this.getReciprocalAssociations(e);for(let s of r)s.removeSemantic(e),s.semantics.length===0&&s.remove()}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 Error(`Cannot duplicate association ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(c=>c.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 a=e.addAssociation(s);for(let c of this.listProperties()){let p=c.toJSON();delete p.key,a.addProperty(p)}for(let c of this.targets)a.addTarget(c.key,c.domain);let o=e.fields.length-1,l=e.fields[o];return e.fields.splice(o,1),e.fields.splice(t+1,0,l),a}};var hi=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 Yn=n=>{let e=n.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 Zn from"dompurify";var vo;function ap(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}if(ap()){let{JSDOM:n}=await import("jsdom"),{window:e}=new n("<!DOCTYPE html>");vo=Zn(e)}else vo=Zn;var Qn=vo;function op(n){return Qn.sanitize(n)}function el(n,e="untitled_column"){let t=op(n);return t=Yn(t),t=t.replace(/[\s-]+/g,"_"),t=t.replace(/[^a-z0-9_]/g,""),t=t.replace(/^_+|_+$/g,""),t||e}function tl(n,e,t="untitled_table"){let i=el(n,t);return`${el(e.slice(0,8))}_${i}`}function il(n){let{entityName:e,assocName:t,targetEntityName:i,pkName:r,isMultiple:s,isOrgResources:a,useTargetTableInColumnName:o}=n,l;return a&&s?l=`${e}_${r}`:o&&i?l=`${e}_${t}_${i}_${r}`:l=`${e}_${t}_${r}`,lp(l)}function np(n,e=0){let t=3735928559^e,i=1103547991^e;for(let r=0,s;r<n.length;r++)s=n.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 lp(n){if(n.length<=63)return n;let e=np(n).toString(16).padStart(8,"0").substring(0,8);return`${n.substring(0,54)}_${e}`}var Ri=class n extends et{kind;#e;#t;#i;#r;info;tags;semantics=[];fields;deprecated;static createSchema(e={}){let{key:t=Q(),tags:i,semantics:r,fields:s,deprecated:a}=e,o=pe.fromJSON(e.info,{name:"new_entity"}).toJSON(),l={kind:j,key:t,info:o};return Array.isArray(i)&&(l.tags=[...i]),Array.isArray(r)&&(l.semantics=[...r]),Array.isArray(s)&&(l.fields=[...s]),typeof a=="boolean"&&(l.deprecated=a),l}constructor(e,t){let i=n.createSchema(t);super(e,i.key),this.kind=j,this.info=new pe(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 g(`Entity ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}getDatabaseTableName(){return tl(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 ti(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 ii(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new ii(`Trying to remove the ${e} property, but it doesn't belong to this entity`);Le(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!==he||(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 a=r[s++];t.has(a.key)||(t.add(a.key),i.push(a),r.push(...a.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 hi([{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 hi([{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 hi([{field:"parents",message:s,rule:"circular"}],{message:s})}if(r.outEdges(this.key,i).next().value){let s=`Parent ${e} already exists`;throw new hi([{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 a=`Trying to remove a parent ${e} from ${this.key}, but it doesn't exist`;throw t&&(a=`Trying to remove a foreign parent ${e} from domain "${t}" from ${this.key}, but it doesn't exist`),new Error(a)}let s=i.edge(this.key,r);if(!s||s.type!=="parent"){let a=`Edge between ${this.key} and ${e} exists but is not a parent relationship`;throw t&&(a=`Edge between ${this.key} and ${e} in domain "${t}" exists but is not a parent relationship`),new Error(a)}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:j});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 o of r){if(!o.key)throw new Error("Missing key for target");if(o.domain&&o.domain!==this.root.key){let l=`${o.domain}:${o.key}`;if(!t.hasNode(l))throw new Error(`Foreign entity ${l} not found`)}else if(!t.hasNode(o.key))throw new Error(`Target entity ${o.key} not found`)}let a=new ji(this.root,this.key,i);if(t.setNode(a.key,a),t.setEdge(this.key,a.key,{type:"association"}),s)for(let o of r)a.addTarget(o.key,o.domain);return this.fields.push({type:"association",key:a.key}),a}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()}Le(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!==de||(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===de||t.kind===he)&&(yield t)}}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}toApiShape(){return new ei().entity(this)}toExample(e,t={}){let i=this.toApiShape();return new ui(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=dt[e.id];if(!Jo(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.semantics.some(l=>l.id===y.OrganizationMembers||l.id===y.ProjectMembers))continue;let r=t.getParentInstance();if(!r)continue;let s=r.primaryKey();if(!s)continue;let a=t.hasSemantic(y.OrganizationResource)||t.hasSemantic(y.ProjectResource);yield{name:il({entityName:r.getExposedName(),assocName:t.getExposedName(),pkName:s.getExposedName(),isMultiple:!0,isOrgResources:a}),primaryKey:s,sourceEntity:r,association:t}}}};var Ci=class extends g{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 Ge=class extends g{static code="E_ATTACH";static status=500;static message="Error attaching the object.";static help="Make sure you are attaching the right object."};var At=class extends g{static code="E_DETACH";static status=500;static message="Error detaching the object.";static help="Make sure you are detaching the right object."};var ri=class n extends et{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=Q(),fields:i,deprecated:r}=e,s=pe.fromJSON(e.info,{name:"New model"}).toJSON(),a={kind:Ee,key:t,info:s};return Array.isArray(i)&&(a.fields=[...i]),typeof r=="boolean"&&(a.deprecated=r),a}constructor(e,t){let i=n.createSchema(t);super(e,i.key),this.kind=Ee,this.info=new pe(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 Ri(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 Ci(`Trying to remove the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==j)throw new Ci(`Trying to remove the ${e} entity, but it is not an entity`);if(t.getParentInstance()!==this)throw new Ci(`Trying to remove the ${e} entity, but it is not a child of this model`);Le(this.root.graph,e),this.removeField(e)}attachEntity(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Ge(`Trying to attach the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==j)throw new Ge(`Trying to attach the ${e} entity, but it is not a entity`);if(t.domain.key!==this.root.key)throw new Ge(`Trying to attach the ${e} entity, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Ge(`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 Ge(`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 At(`Trying to detach the ${e} entity, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==j)throw new At(`Trying to detach the ${e} entity, but it is not an entity`);if(i.getParentInstance()!==this)throw new At(`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!==j||(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:Ee});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 fi=class extends g{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 pr=class extends g{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 Ti=class n extends et{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=Q(),fields:i,deprecated:r}=e,s=pe.fromJSON(e.info,{name:"New namespace"}).toJSON(),a={kind:Ie,key:t,info:s};return Array.isArray(i)&&(a.fields=[...i]),typeof r=="boolean"&&(a.deprecated=r),a}constructor(e,t){let i=n.createSchema(t);super(e,i.key),this.kind=Ie,this.info=new pe(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 n(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 fi(`Trying to remove the ${e} namespace, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Ie)throw new fi(`Trying to remove the ${e} namespace, but it is not a namespace`);return Le(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!==Ie)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 Ge(`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 fi(`Trying to detach the ${e} namespace, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Ie)throw new fi(`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!==Ie||(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 ri(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 pr(`Trying to remove the ${e} model, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Ee)throw new pr(`Trying to remove the ${e} model, but it is not a model`);return Le(this.root.graph,e),this.removeField(e),this}attachModel(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new Ge(`Trying to attach the ${e} model, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Ee)throw new Ge(`Trying to attach the ${e} model, but it is not a model`);if(t.domain.key!==this.root.key)throw new Ge(`Trying to attach the ${e} model, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new Ge(`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 At(`Trying to detach the ${e} model, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Ee)throw new At(`Trying to detach the ${e} model, but it is not a model`);if(i.getParentInstance()!==this)throw new At(`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!==Ee||(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===Ie||t.kind===Ee)&&(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 Di(n,e,t){return n+""+e+""+(t||"\0")}function wo(n,e,t){let i={v:n,w:e};return t&&(i.name=t),i}var Us=class n{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 n({directed:this.isDirectedValue,multigraph:this.isMultigraphValue,compound:this.isCompoundValue}),i=this.graph();t.setGraph(i);let r=new Set;if(this.nodesValue.forEach((s,a)=>{e(a)&&(t.setNode(a,s),r.add(a))}),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 a of t.nodes()){let o=[...this.parents(a)],l=[];for(;o.length>0;){let c=!1;for(let u of o)t.hasNode(u)&&(l.push(u),c=!0);if(c)break;let p=[];for(let u of o)for(let m of this.parents(u))p.push(m);o=p}l.length===0&&l.push("\0"),s.set(a,l)}for(let[a,o]of s){this.removeParent(a);for(let l of o)t.addParent(a,l)}}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=wo(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 a=Di(t.v,t.w,t.name);if(this.edgeLabelsValue.has(a)){if(r&&this.edgeLabelsValue.set(a,s),e.loop===0&&!this.isDirectedValue&&t.w!==t.v){let u=wo(t.w,t.v,t.name);r?this._setEdge({loop:1},u,i):this._setEdge({loop:1},u)}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 l=r?s:this.defaultEdgeLabelFn(t.v,t.w,t.name);this.edgeLabelsValue.set(a,l),this.edgeObjectsValue.set(a,t);let c=this.predecessorsValue.get(t.w);if(c){let u=(c.get(t.v)||0)+1;c.set(t.v,u)}let p=this.successorsValue.get(t.v);if(p){let u=(p.get(t.w)||0)+1;p.set(t.w,u)}if(this.inValue.get(t.w).set(a,t),this.outValue.get(t.v).set(a,t),this.edgeCountValue++,e.loop===0&&!this.isDirectedValue&&t.w!==t.v){let u=wo(t.w,t.v,t.name);r?this._setEdge({loop:1},u,i):typeof l=="object"&&l!==null?this._setEdge({loop:1},u,l):this._setEdge({loop:1},u)}}edge(e,t,i){let r;return typeof e=="object"?r=Di(e.v,e.w,e.name):r=Di(e,t,i),this.edgeLabelsValue.get(r)}hasEdge(e,t,i){let r;return typeof e=="object"?r=Di(e.v,e.w,e.name):r=Di(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=Di(t,i,r),a=this.edgeObjectsValue.get(s);if(a){this.edgeLabelsValue.delete(s),this.edgeObjectsValue.delete(s);let o=this.predecessorsValue.get(a.w);if(o){let c=(o.get(a.v)||0)-1;c<=0?o.delete(a.v):o.set(a.v,c)}let l=this.successorsValue.get(a.v);if(l){let c=(l.get(a.w)||0)-1;c<=0?l.delete(a.w):l.set(a.w,c)}this.inValue.get(a.w)?.delete(s),this.outValue.get(a.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 cp(n,e){let t=[];for(let i of n.nodes()){let r=n.node(i);if(!r||r.domain.key!==e)continue;let s=[...n.parents(i)],a={v:i};a.value=r.toJSON(),s.length&&(a.parents=s),t.push(a)}return t}function dp(n,e){let t=[];for(let i of n.edges()){let r=n.edge(i);if(!r)continue;let s=n.node(i.v),a=n.node(i.w);if(!s||!a||s.domain.key!==e||a.domain.key!==e&&r.type!=="association"&&r.type!=="parent")continue;let o={v:i.v,w:i.w};i.name&&(o.name=i.name),o.value=structuredClone(r),t.push(o)}return t}function pp(n,e){let t=[],i=new Set;for(let r of n.nodes()){let s=n.node(r);s&&s.domain.key===e&&i.add(r)}for(let r of i){let s=n.node(r);if(s){if(s.kind===he||s.kind===de){let o=[...n.inEdges(r)].filter(l=>{let c=n.node(l.v);return c&&c.domain.key===e});if(o.length===0){let l=s.kind===he?"Property":"Association";t.push(`${l} "${s.info.name}" (${r}) has no parent entity edge. This will cause deserialization to fail.`)}else if(o.length>1){let l=s.kind===he?"Property":"Association",c=o.map(p=>p.v).join(", ");t.push(`${l} "${s.info.name}" (${r}) has multiple parent edges: ${c}. This may cause deserialization issues.`)}else{let l=o[0],c=n.node(l.v);if(!c||c.kind!==j&&c.kind!==de){let p=s.kind===he?"Property":"Association";t.push(`${p} "${s.info.name}" (${r}) has a parent that is not an entity or association. Parent: ${c?.kind||"unknown"} (${l.v})`)}}}if(s.kind===j&&([...n.parents(r)].some(l=>{let c=n.node(l);return c&&c.kind===Ee})||t.push(`Entity "${s.info.name}" (${r}) has no model parent. Entities must belong to a model.`)),s.kind===Ee){let a=[...n.parents(r)],o=a.some(l=>{let c=n.node(l);return c&&c.kind===Ie});if(a.length>0&&!o){let l=a.map(c=>`${n.node(c)?.kind||"unknown"} (${c})`).join(", ");t.push(`Model "${s.info.name}" (${r}) has invalid parent types: ${l}. Models can only belong to namespaces or be at root level.`)}}}}for(let r of i){let s=n.node(r);if(s&&s.kind===de){let a=s,l=[...n.outEdges(r)].filter(c=>{let p=n.edge(c);return p&&p.type==="association"});l.length;for(let c of l){let p=n.node(c.w);p?p.kind!==j&&t.push(`Association "${a.info.name}" (${r}) references non-entity target: ${p.kind} (${c.w})`):t.push(`Association "${a.info.name}" (${r}) references non-existent target: ${c.w}`)}}}if(t.length>0)throw new Error(`Graph consistency validation failed for domain "${e}":
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 qe().generate(t),a=_t(e),l=i.indent||0,c=new Array(l*2).fill(" ").join(""),p=[`${c}<${a}>`],u=new Array(l*2+2).fill(" ").join("");return p.push(`${u}${String(s).trim()}`),p.push(`${c}</${a}>`),p.join(`
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(l=>{let{types:c}=l;if(c.includes(d.aml.vocabularies.shapes.ScalarShape)){let p=l;a.properties.push(p)}else if(c.includes(d.w3.shacl.NodeShape))l.properties.forEach(u=>a.properties.push(u));else if(c.includes(d.aml.vocabularies.shapes.ArrayShape)||c.includes(d.aml.vocabularies.shapes.MatrixShape)){let p=l;p.items&&a.properties.push(p.items)}}),this._nodeShapeObject(a)}if(i.length){let{selectedUnions:a=[]}=this.opts,l=i.find(c=>a.includes(c.id));return l||(l=i[0]),this.processNode(l)}if(r.length){let{selectedUnions:a=[]}=this.opts,l=r.find(c=>a.includes(c.id));return l||(l=r[0]),this.processNode(l)}let{examples:s=[]}=e,o=_t(e);if(this.opts.renderExamples&&s&&s.length){let a=s.find(p=>!!p.structuredValue),l=this._exampleToObject(a),c=[];if(typeof l<"u"){let p=" ";c.push(`<${o}>`),c.push(`${p}${l}`),c.push(`</${o}>`)}return c.join(`
51
+ `)}return this._scalarShapeObject(e)}};var Qn=Zl(Xn(),1);var zs=Symbol("findAmfType"),Yn=Symbol("findReferenceObject"),xe=Symbol("getArrayItems"),Zn=Symbol("computeReferenceSecurity"),Aa=n=>{class e extends n{_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 Qn.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 l=i.indexOf("#"),c=i.substring(0,l+1),p=Object.keys(o);for(let u=0,m=p.length;u<m;u++){let h=p[u];if(o[h]===i)return a[i]=h,h;if(l===-1&&i.indexOf(o[h])===0){let f=i.replace(o[h],`${h}:`);return a[i]=f,f}if(o[h]===c){let f=`${h}:${i.substring(l+1)}`;return a[i]=f,f}}return i}_ensureAmfModel(i){if(i&&(Array.isArray(i)&&([i]=i),this._hasType(i,d.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 l=typeof a;return["string","number","boolean","undefined"].includes(l)?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(l=>l["@value"]||l)}[xe](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(l=>l["@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 l of o)if(l===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,d.aml.vocabularies.core.version,r)}_computeEncodes(i,r){if(!i)return;Array.isArray(i)&&([i]=i);let s=this._getAmfKey(d.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(d.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(d.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,d.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,d.aml.vocabularies.apiContract.WebAPI,r):!1}_isAsyncAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,d.aml.vocabularies.apiContract.AsyncAPI,r):!1}_isAPI(i,r){let s=this._computeEncodes(i,r);return s?this._hasType(s,d.aml.vocabularies.apiContract.API,r):!1}_isValidServerPartial(i,r){if(Array.isArray(i)&&([i]=i),!i)return!1;let s=d.aml.vocabularies.apiContract.Operation,o=d.aml.vocabularies.apiContract.EndPoint,a=[this._getAmfKey(s,r),this._getAmfKey(o,r)],l=i["@type"];for(let c of l)if(a.indexOf(c)!==-1)return!0;return!1}_getServers(i={},r){let{endpointId:s,methodId:o}=i,{amf:a}=this;if(!a)return;let l=this._computeApi(a,r);if(Array.isArray(l)&&([l]=l),!l)if(this._isValidServerPartial(a,r))l=a;else return;let c=this._getAmfKey(d.aml.vocabularies.apiContract.server,r),p=()=>this[xe](l,c,r),u=()=>{let h=this._computeEndpointModel(l,s,r),f=this[xe](h,c,r);return f||p()},m=()=>{let h=this._computeMethodModel(l,o,r),f=this[xe](h,c,r);return f||u()};return o?m():s?u():p()}_computeExpects(i,r){let s=d.aml.vocabularies.apiContract.Operation,o=d.aml.vocabularies.apiContract.expects;if(this._hasType(i,s,r)){let a=this._getAmfKey(o,r),l=this._ensureArray(i[a]);if(l)return Array.isArray(l)?l[0]:l}}_computeEndpoints(i,r){if(!i)return[];let s=d.aml.vocabularies.apiContract.endpoint,o=this._getAmfKey(s,r);return this._ensureArray(i[o])}_computeEndpointModel(i,r,s){if(this._hasType(i,d.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,d.aml.vocabularies.apiContract.EndPoint,s))return i;let o=this._computeEndpoints(i,s);if(!o)return;let a=this._getAmfKey(d.aml.vocabularies.apiContract.supportedOperation,s);for(let l=0,c=o.length;l<c;l++){let p=o[l],u=p[a];if(u){Array.isArray(u)||(u=[u]);for(let m=0,h=u.length;m<h;m++)if(u[m]["@id"]===r)return p}}}__computeMethodsListForMethod(i,r,s){let o=this._computeMethodEndpoint(i,r,s);if(!o)return;let a=this._getAmfKey(d.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",""),l=i&&i.find(c=>c["@id"]===s||c["@id"]===a);if(!l&&r&&r.length)for(let c=0,p=r.length;c<p&&!(this._hasType(r[c],d.aml.vocabularies.document.Module)&&(l=this._computeReferenceType(r[c],s,o),l));c++);return l}[zs](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 l=o.find(c=>c["@id"]===i||c["@id"]===a);if(l)return l}return this[Yn](i)}[Yn](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 l=0,c=o.length;l<c;l++){let p=o[l],u=this._computeDeclares(p,r);if(Array.isArray(u))for(let m=0,h=u.length;m<h;m++){let f=u[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",""),l=o.find(c=>(Array.isArray(c)&&([c]=c),c["@id"]===r||c["@id"]===a));return Array.isArray(l)&&([l]=l),this._resolve(l)}_computeDocument(i,r,s){if(!i||!r)return;let o=this._getAmfKey(d.aml.vocabularies.core.documentation,s),a=this._ensureArray(i[o]);return a&&a.find(l=>l["@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(d.aml.vocabularies.document.linkTarget,r),a=this._ensureArray(i[o]),l;if(a){let u=a[0]["@id"];if(u===i["@id"])return i.__apicResolved=!0,i;l=this._getLinkTarget(s,u,r)}else if(o=this._getAmfKey(d.aml.vocabularies.document.referenceId,r),a=this._ensureArray(i[o]),a){let u=a[0]["@id"];if(u===i["@id"])return i.__apicResolved=!0,i;l=this._getReferenceId(s,u,r)}if(!l)return this._resolveRecursive(i),i.__apicResolved=!0,i;let c={...l};delete c["@id"];let p=c["@type"];return p&&(i["@type"]?i["@type"]=i["@type"].concat(p):i["@type"]=p,delete c["@type"]),this._mergeShapes(i,c,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 l=this._computeReferences(i,s);o=this._obtainShapeFromReferences(l,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 l=this._computeEncodes(a,s);if(l&&l["@id"]===r){o=l;break}if(!l&&(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 l=this._computeEncodes(a,s);if(l&&l["@id"]===r)return l}}_resolveRecursive(i,r){Object.keys(i).forEach(s=>{let o=i[s];if(Array.isArray(o))for(let a=0,l=o.length;a<l;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(d.aml.vocabularies.docSourceMaps.sources,s),merger:this._mergeSourceMapsSources.bind(this)}].forEach(({key:l,merger:c})=>{this._hasProperty(o,l,s)&&(o[l]=c(i,r,s))}),Object.assign(i,o)}_mergeSourceMapsSources(i,r,s){let o=this._getAmfKey(d.aml.vocabularies.docSourceMaps.sources,s),a=i[o]||{};Array.isArray(a)&&(a=a[0]);let l=r[o]||{};return Array.isArray(l)&&(l=l[0]),[Object.assign(a,l)]}_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,l]=i.split(":");if(!a||!l)return i;let c=o[a];return c?`${c}${l}`:i}findSecurityScheme(i,r){let{amf:s}=this,o=this._computeDeclares(s,r),a;if(o&&(a=o.find(c=>c["@id"]===i)),a)return a=this._resolve(a),a;let l=this._computeReferences(s,r);if(Array.isArray(l)&&l.length){for(let c of l)if(this._hasType(c,d.aml.vocabularies.document.Module,r)&&(a=this[Zn](c,i,r),a))return a=this._resolve(a),a}}[Zn](i,r,s){let o=this._computeDeclares(i,s);if(!o)return;let a=o.find(l=>{let c=l;return Array.isArray(c)&&([c]=c),c["@id"]===r});return Array.isArray(a)&&([a]=a),this._resolve(a)}getByType(i,r,s){if(!i)return[];let o=[],a=this._computeDeclares(i),l=this._getAmfKey(r,s);a&&a.length&&a.forEach(p=>{this._hasType(p,l)&&o.push(p)});let c=this._computeReferences(i);if(Array.isArray(c)&&c.length){for(let p of c)if(this._hasType(p,d.aml.vocabularies.document.Module)){let u=this.getByType(p,r,s);u.length&&(o=o.concat(u))}}return o}}return e};var _a=class extends Aa(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,d.aml.vocabularies.core.name,t);r&&typeof r=="string"&&(i.name=r);let s=this._getValue(e,d.aml.vocabularies.core.description,t);s&&typeof s=="string"&&(i.description=s);let o=this._getValue(e,d.aml.vocabularies.core.version,t);o&&typeof o=="string"&&(i.version=o);let a=this._getValue(e,d.aml.vocabularies.core.termsOfService,t);a&&typeof a=="string"&&(i.termsOfService=a);let l=e[this._getAmfKey(d.aml.vocabularies.apiContract.accepts,t)];Array.isArray(l)&&l.length&&(i.accepts=this._getValueArray(e,d.aml.vocabularies.apiContract.accepts,t));let c=e[this._getAmfKey(d.aml.vocabularies.apiContract.contentType,t)];Array.isArray(c)&&c.length&&(i.contentType=this._getValueArray(e,d.aml.vocabularies.apiContract.contentType,t));let p=e[this._getAmfKey(d.aml.vocabularies.apiContract.scheme,t)];Array.isArray(p)&&p.length&&(i.schemes=this._getValueArray(e,d.aml.vocabularies.apiContract.scheme,t));let u=e[this._getAmfKey(d.aml.vocabularies.core.provider,t)];Array.isArray(u)&&([u]=u),u&&(i.provider=this.provider(u));let m=e[this._getAmfKey(d.aml.vocabularies.core.license,t)];Array.isArray(m)&&([m]=m),m&&(i.license=this.license(m));let h=e[this._getAmfKey(d.aml.vocabularies.apiContract.tag,t)];Array.isArray(h)&&h.length&&(i.tags=h.map(k=>this.tag(k)));let f=e[this._getAmfKey(d.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(d.aml.vocabularies.apiContract.endpoint,i)];Array.isArray(s)&&s.length&&(r.endPoints=s.map(l=>this.endPoint(l,i)));let o=e[this._getAmfKey(d.aml.vocabularies.apiContract.server,i)];Array.isArray(o)&&o.length&&(r.servers=o.map(l=>this.server(l,i)));let a=e[this._getAmfKey(d.aml.vocabularies.security.security,i)];return Array.isArray(a)&&a.length&&(r.security=a.map(l=>this.securityRequirement(l,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getLinkValue(e,d.aml.vocabularies.core.url,i);o&&typeof o=="string"&&(r.url=o);let a=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getLinkValue(e,d.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,d.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,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(s.description=o);let a=e[this._getAmfKey(d.aml.vocabularies.apiContract.variable,i)];Array.isArray(a)&&a.length&&(s.variables=a.map(u=>this.parameter(u,i)));let l=this._getValue(e,d.aml.vocabularies.apiContract.protocol,i),c=this._getValue(e,d.aml.vocabularies.apiContract.protocolVersion,i);l&&(s.protocol=l),c&&(s.protocolVersion=c);let p=e[this._getAmfKey(d.aml.vocabularies.security.security,i)];return Array.isArray(p)&&p.length&&(s.security=p.map(u=>this.securityRequirement(u,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.apiContract.paramName,i);o&&typeof o=="string"&&(r.paramName=o);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let l=this._getValue(e,d.aml.vocabularies.apiContract.required,i);typeof l=="boolean"&&(r.required=l);let c=this._getValue(e,d.aml.vocabularies.apiContract.allowEmptyValue,i);typeof c=="boolean"&&(r.allowEmptyValue=c);let p=this._getValue(e,d.aml.vocabularies.document.deprecated,i);typeof p=="boolean"&&(r.deprecated=p);let u=this._getValue(e,d.aml.vocabularies.apiContract.explode,i);typeof u=="boolean"&&(r.explode=u);let m=this._getValue(e,d.aml.vocabularies.apiContract.allowReserved,i);typeof m=="boolean"&&(r.allowReserved=m);let h=this._getValue(e,d.aml.vocabularies.apiContract.style,i);h&&typeof h=="string"&&(r.style=h);let f=this._getValue(e,d.aml.vocabularies.apiContract.binding,i);f&&typeof f=="string"&&(r.binding=f);let k=e[this._getAmfKey(d.aml.vocabularies.shapes.schema,i)];if(Array.isArray(k)&&k.length){let[$]=k;r.schema=this.unknownShape($,{trackedId:e["@id"]},i)}let v=e[this._getAmfKey(d.aml.vocabularies.apiContract.payload,i)];Array.isArray(v)&&v.length&&(r.payloads=v.map($=>this.payload($,i)));let E=e[this._getAmfKey(d.aml.vocabularies.apiContract.examples,i)];return Array.isArray(E)&&E.length&&(r.examples=E.map($=>this.example($,i))),r}unknownShape(e,t,i){let r=i||e["@context"],s=this.readTypes(e["@type"],r);return s.includes(d.aml.vocabularies.shapes.ScalarShape)?this.scalarShape(e,t,r):s.includes(d.w3.shacl.NodeShape)?this.nodeShape(e,t,r):s.includes(d.aml.vocabularies.shapes.UnionShape)?this.unionShape(e,t,r):s.includes(d.aml.vocabularies.shapes.FileShape)?this.fileShape(e,t,r):s.includes(d.aml.vocabularies.shapes.SchemaShape)?this.schemaShape(e,t,r):s.includes(d.aml.vocabularies.shapes.TupleShape)?this.tupleShape(e,t,r):s.includes(d.aml.vocabularies.shapes.ArrayShape)||s.includes(d.aml.vocabularies.shapes.MatrixShape)?this.arrayShape(e,t,r):s.includes(d.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,d.aml.vocabularies.document.linkTarget,i)}getLinkTarget(e,t){let i=t||e["@context"],r=this._getLinkValue(e,d.aml.vocabularies.document.linkTarget,i);if(r)return this[zs](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,d.aml.vocabularies.document.linkLabel,i);let F=this._getLinkValue(s,d.aml.vocabularies.document.linkTarget,i),P=this[zs](F,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,d.w3.shacl.name,i);a&&typeof a=="string"&&(o.name=a);let l=this._getValue(s,d.aml.vocabularies.core.displayName,i);if(l&&typeof l=="string")o.displayName=l;else{let F=this._getValue(s,d.aml.vocabularies.core.name,i);F&&typeof F=="string"&&(o.displayName=F)}let c=this._getValue(s,d.aml.vocabularies.core.description,i);c&&typeof c=="string"&&(o.description=c);let p=this._getValue(s,d.w3.shacl.defaultValueStr,i);p&&typeof p=="string"&&(o.defaultValueStr=p);let u=this._getValue(s,d.aml.vocabularies.shapes.deprecated,i);typeof u=="boolean"&&(o.deprecated=u);let m=this._getValue(s,d.aml.vocabularies.shapes.readOnly,i);typeof m=="boolean"&&(o.readOnly=m);let h=this._getValue(s,d.aml.vocabularies.shapes.writeOnly,i);typeof h=="boolean"&&(o.writeOnly=h);let f=s[this._getAmfKey(d.w3.shacl.defaultValue,i)];Array.isArray(f)&&f.length&&(o.defaultValue=this.unknownDataNode(f[0],i));let k=this._getAmfKey(d.w3.shacl.or,i),v=s[k];Array.isArray(v)&&v.length&&(o.or=v.map(F=>this.unknownShape(F,void 0,i)));let E=this._getAmfKey(d.w3.shacl.and,i),$=s[E];Array.isArray($)&&$.length&&(o.and=$.map(F=>this.unknownShape(F,void 0,i)));let j=this._getAmfKey(d.w3.shacl.xone,i),C=s[j];Array.isArray(C)&&C.length&&(o.xone=C.map(F=>this.unknownShape(F,void 0,i)));let I=s[this._getAmfKey(d.w3.shacl.in,i)];if(Array.isArray(I)&&I.length){let[F]=I,P=d.w3.rdfSchema.key,w=this._getAmfKey(P,i);Object.keys(F).forEach(O=>{if(O.startsWith(P)||O.startsWith(w)){let z=F[O];Array.isArray(z)&&([z]=z);let V=this.unknownDataNode(z,i);V&&o.values.push(V)}})}let T=this._getAmfKey(d.w3.shacl.not,i),U=s[T];return U&&(Array.isArray(U)&&([U]=U),o.not=this.unknownShape(U,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 p=this.getLinkTarget(s,r);p&&(s=p)}o.examples=[];let a=s[this._getAmfKey(d.aml.vocabularies.apiContract.examples,r)];if(Array.isArray(a)&&a.length)if(t.trackedId){let p=this.filterTrackedExamples(a,t.trackedId,r);o.examples=p.map(u=>this.example(u,r))}else{let p=this.filterNonTrackedExamples(a,r);o.examples=p.map(u=>this.example(u,r))}let l=s[this._getAmfKey(d.aml.vocabularies.core.documentation,r)];if(Array.isArray(l)&&l.length){let[p]=l;o.documentation=this.documentation(p,r)}let c=s[this._getAmfKey(d.aml.vocabularies.shapes.xmlSerialization,r)];return Array.isArray(c)&&c.length&&(o.xmlSerialization=this.xmlSerializer(c[0],r)),o}filterTrackedExamples(e,t,i){let{docSourceMaps:r}=d.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(l=>{let c=l;Array.isArray(c)&&([c]=c);let p=c[s];if(!p)return!0;Array.isArray(p)&&([p]=p);let u=p[o];if(!u)return!0;Array.isArray(u)&&([u]=u);let{value:m}=this.synthesizedField(u,i);if(!m)return!0;let h=m.split(",");return h.indexOf(a)!==-1||h.indexOf(t)!==-1})}filterNonTrackedExamples(e,t){let{docSourceMaps:i}=d.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 l=a[r];if(!l)return!0;Array.isArray(l)&&([l]=l);let c=l[s];if(!c)return!0;Array.isArray(c)&&([c]=c);let{value:p}=this.synthesizedField(c,t);return!p})}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,d.w3.shacl.pattern,r);a&&typeof a=="string"&&(o.pattern=a);let l=this._getLinkValue(s,d.w3.shacl.datatype,r);l&&typeof l=="string"&&(o.dataType=l);let c=this._getValue(s,d.aml.vocabularies.shapes.format,r);c&&typeof c=="string"&&(o.format=c);let p=this._getValue(s,d.aml.vocabularies.shapes.multipleOf,r);typeof p=="number"&&(o.multipleOf=p);let u=this._getValue(s,d.w3.shacl.minInclusive,r);typeof u=="number"&&(o.minimum=u,o.exclusiveMinimum=!1);let m=this._getValue(s,d.w3.shacl.maxInclusive,r);typeof m=="number"&&(o.maximum=m,o.exclusiveMaximum=!1);let h=this._getValue(s,d.w3.shacl.minLength,r);typeof h=="number"&&(o.minLength=h);let f=this._getValue(s,d.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,d.aml.vocabularies.shapes.discriminator,r);a&&typeof a=="string"&&(o.discriminator=a);let l=this._getValue(s,d.aml.vocabularies.shapes.discriminatorValue,r);l&&typeof l=="string"&&(o.discriminatorValue=l);let c=this._getValue(s,d.w3.shacl.closed,r);typeof c=="boolean"&&(o.closed=c),o.customShapeProperties=[],o.customShapePropertyDefinitions=[],o.dependencies=[];let p=s[this._getAmfKey(d.w3.shacl.property,r)];Array.isArray(p)&&p.length?o.properties=p.map(m=>this.propertyShape(m,r)):o.properties=[];let u=s[this._getAmfKey(d.w3.shacl.additionalPropertiesSchema,r)];if(Array.isArray(u)&&u.length===1){let[m]=u;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 p=this.getLinkTarget(r,i);p&&(r=p)}let o=this._getLinkValue(r,d.w3.shacl.path,i);o&&typeof o=="string"&&(s.path=o);let a=this._getValue(r,d.w3.shacl.minCount,i);typeof a=="number"&&(s.minCount=a);let l=this._getValue(r,d.w3.shacl.maxCount,i);typeof l=="number"&&(s.maxCount=l);let c=r[this._getAmfKey(d.aml.vocabularies.shapes.range,i)];if(Array.isArray(c)&&c.length){let[p]=c;s.range=this.unknownShape(p,void 0,i)}return s}unionShape(e,t={},i){let r=i||e["@context"],s=e[this._getAmfKey(d.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(l=>this.unknownShape(l,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,d.w3.shacl.pattern,r);a&&typeof a=="string"&&(o.pattern=a);let l=this._getValueArray(s,d.aml.vocabularies.shapes.fileType,r);Array.isArray(l)&&l.length&&(o.fileTypes=l);let c=this._getValue(s,d.w3.shacl.minLength,r);typeof c=="number"&&(o.minLength=c);let p=this._getValue(s,d.w3.shacl.maxLength,r);typeof p=="number"&&(o.maxLength=p);let u=this._getValue(s,d.w3.shacl.minInclusive,r);typeof u=="number"&&(o.minimum=u,o.exclusiveMinimum=!1);let m=this._getValue(s,d.w3.shacl.maxInclusive,r);typeof m=="number"&&(o.maximum=m,o.exclusiveMaximum=!1);let h=this._getValue(s,d.aml.vocabularies.shapes.format,r);h&&typeof h=="string"&&(o.format=h);let f=this._getValue(s,d.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 c=this.getLinkTarget(s,r);c&&(s=c)}let a=this._getValue(s,d.aml.vocabularies.core.mediaType,r);a&&typeof a=="string"&&(o.mediaType=a);let l=this._getValue(s,d.aml.vocabularies.document.raw,r);return l&&typeof l=="string"&&(o.raw=l),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,d.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 l=this.getLinkTarget(s,r);l&&(s=l)}let a=s[this._getAmfKey(d.aml.vocabularies.shapes.items,r)];if(Array.isArray(a)&&a.length){let[l]=a;o.items=this.unknownShape(l,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 c=this.getLinkTarget(s,r);c&&(s=c)}let a=s[this._getAmfKey(d.aml.vocabularies.shapes.items,r)],l=this._getAmfKey(d.w3.rdfSchema.key,r);return Array.isArray(a)&&a.length?(o.items=[],a.forEach(c=>{Array.isArray(c)&&([c]=c),Object.keys(c).filter(p=>p.startsWith(l)).forEach(p=>{let u=c[p];Array.isArray(u)&&([u]=u);let m=this.unknownShape(u,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,d.aml.vocabularies.core.url,i);s&&typeof s=="string"&&(r.url=s);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,d.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,d.aml.vocabularies.document.strict,i);typeof s=="boolean"&&(r.strict=s);let o=this._getValue(e,d.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,d.aml.vocabularies.core.displayName,i);a&&typeof a=="string"&&(r.displayName=a);let l=this._getValue(e,d.aml.vocabularies.core.description,i);l&&typeof l=="string"&&(r.description=l);let c=this._getValue(e,d.aml.vocabularies.document.raw,i);c&&typeof c=="string"&&(r.value=c);let p=this._getValue(e,d.aml.vocabularies.document.location,i);p&&typeof p=="string"&&(r.location=p);let u=e[this._getAmfKey(d.aml.vocabularies.document.structuredValue,i)];if(Array.isArray(u)&&u.length){let[m]=u;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,d.aml.vocabularies.shapes.xmlAttribute,i);typeof s=="boolean"&&(r.attribute=s);let o=this._getValue(e,d.aml.vocabularies.shapes.xmlWrapped,i);typeof o=="boolean"&&(r.wrapped=o);let a=this._getValue(e,d.aml.vocabularies.shapes.xmlName,i);a&&typeof a=="string"&&(r.name=a);let l=this._getValue(e,d.aml.vocabularies.shapes.xmlNamespace,i);l&&typeof l=="string"&&(r.namespace=l);let c=this._getValue(e,d.aml.vocabularies.shapes.xmlPrefix,i);return c&&typeof c=="string"&&(r.prefix=c),r}unknownDataNode(e,t){let i=this.readTypes(e["@type"],t);if(i.includes(d.aml.vocabularies.data.Scalar))return this.scalarNode(e,t);if(i.includes(d.aml.vocabularies.data.Object))return this.objectNode(e,t);if(i.includes(d.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,d.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,d.aml.vocabularies.data.value,i);s&&typeof s=="string"&&(r.value=s);let o=this._getLinkValue(e,d.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=d.aml.vocabularies.data.key,o=`${this._getAmfKey(s,i)}:`;return Object.keys(e).forEach(a=>{if(a.startsWith(s)||a.startsWith(o)){let l=e[a];Array.isArray(l)&&([l]=l);let c=a.replace(s,"").replace(o,""),p=this.unknownDataNode(l,t);p&&(r.properties[c]=p)}}),r}arrayNode(e,t){let i=t||e["@context"],r=this.dataNode(e,i);r.members=[];let s=this._computePropertyArray(e,d.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,d.aml.vocabularies.document.customDomainProperties,r);return Array.isArray(s)&&s.length&&s.forEach(o=>{let a=`@base:${o}`,l=e[o]||e[a];if(!l)return;Array.isArray(l)&&([l]=l);let c=this.unknownDataNode(l,r),p=this._getValue(l,d.aml.vocabularies.core.extensionName,r);if(!p||!c)return;let u={id:o,name:p,extension:c};i.push(u)}),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,d.aml.vocabularies.apiContract.path,i);s&&typeof s=="string"&&(r.path=s);let o=this._getValue(e,d.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let l=this._getValue(e,d.aml.vocabularies.core.summary,i);l&&typeof l=="string"&&(r.summary=l);let c=this[xe](e,d.aml.vocabularies.apiContract.supportedOperation,i);Array.isArray(c)&&c.length&&(r.operations=c.map(k=>this.operation(k,i)));let p=this[xe](e,d.aml.vocabularies.apiContract.parameter,i);Array.isArray(p)&&p.length&&(r.parameters=p.map(k=>this.parameter(k,i)));let u=this[xe](e,d.aml.vocabularies.apiContract.payload,i);Array.isArray(u)&&u.length&&(r.payloads=u.map(k=>this.payload(k,i)));let m=this[xe](e,d.aml.vocabularies.apiContract.server,i);Array.isArray(m)&&m.length&&(r.servers=m.map(k=>this.server(k,i)));let h=this[xe](e,d.aml.vocabularies.security.security,i);Array.isArray(h)&&h.length&&(r.security=h.map(k=>this.securityRequirement(k,i)));let f=this[xe](e,d.aml.vocabularies.document.extends,i);return Array.isArray(f)&&f.length&&(r.extends=[],f.forEach(k=>{let v=k;Array.isArray(v)&&([v]=v),this._hasType(v,d.aml.vocabularies.apiContract.ParametrizedResourceType,i)?r.extends.push(this.parametrizedResourceType(v,i)):this._hasType(v,d.aml.vocabularies.apiContract.ParametrizedTrait,i)&&r.extends.push(this.parametrizedTrait(v,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,d.aml.vocabularies.apiContract.method,i);s&&typeof s=="string"&&(r.method=s);let o=this._getValue(e,d.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let l=this._getValue(e,d.aml.vocabularies.apiContract.guiSummary,i);l&&typeof l=="string"&&(r.summary=l);let c=this._getValue(e,d.aml.vocabularies.core.deprecated,i);typeof c=="boolean"&&(r.deprecated=c);let p=this._getValue(e,d.aml.vocabularies.apiContract.operationId,i);p&&typeof p=="string"&&(r.operationId=p);let u=this._getValueArray(e,d.aml.vocabularies.apiContract.accepts,i);Array.isArray(u)&&(r.accepts=u);let m=this._getValueArray(e,d.aml.vocabularies.apiContract.scheme,i);Array.isArray(m)&&(r.schemes=m);let h=this._getValueArray(e,d.aml.vocabularies.apiContract.contentType,i);Array.isArray(h)&&(r.contentType=h);let f=e[this._getAmfKey(d.aml.vocabularies.apiContract.expects,i)];f&&(Array.isArray(f)&&([f]=f),r.request=this.request(f,i));let k=e[this._getAmfKey(d.aml.vocabularies.core.documentation,i)];k&&(Array.isArray(k)&&([k]=k),r.documentation=this.documentation(k,i));let v=e[this._getAmfKey(d.aml.vocabularies.apiContract.returns,i)];Array.isArray(v)&&(r.responses=v.map(T=>this.response(T,i)));let E=e[this._getAmfKey(d.aml.vocabularies.apiContract.callback,i)];Array.isArray(E)&&(r.callbacks=E.map(T=>this.callback(T,i)));let $=e[this._getAmfKey(d.aml.vocabularies.apiContract.server,i)];Array.isArray($)&&(r.servers=$.map(T=>this.server(T)));let j=e[this._getAmfKey(d.aml.vocabularies.security.security,i)];Array.isArray(j)&&(r.security=j.map(T=>this.securityRequirement(T,i)));let C=e[this._getAmfKey(d.aml.vocabularies.apiContract.tag,i)];Array.isArray(C)&&C.length&&(r.tags=C.map(T=>this.tag(T,i)));let I=e[this._getAmfKey(d.aml.vocabularies.document.extends,i)];return Array.isArray(I)&&I.length&&(r.extends=I.map(T=>this.parametrizedTrait(T,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=e[this._getAmfKey(d.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,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.apiContract.expression,i);o&&typeof o=="string"&&(r.expression=o);let a=e[this._getAmfKey(d.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,d.aml.vocabularies.core.description,i);s&&typeof s=="string"&&(r.description=s);let o=this._getValue(e,d.aml.vocabularies.apiContract.required,i);o&&typeof o=="boolean"&&(r.required=o);let a=e[this._getAmfKey(d.aml.vocabularies.apiContract.queryString,i)];a&&(Array.isArray(a)&&([a]=a),r.queryString=this.unknownShape(a,void 0,i));let l=this[xe](e,d.aml.vocabularies.apiContract.header,i);Array.isArray(l)&&l.length&&(r.headers=l.map(h=>this.parameter(h,i)));let c=this[xe](e,d.aml.vocabularies.apiContract.parameter,i);Array.isArray(c)&&c.length&&(r.queryParameters=c.map(h=>this.parameter(h,i)));let p=this[xe](e,d.aml.vocabularies.apiContract.uriParameter,i);Array.isArray(p)&&p.length&&(r.uriParameters=p.map(h=>this.parameter(h,i)));let u=this[xe](e,d.aml.vocabularies.apiContract.cookieParameter,i);Array.isArray(u)&&u.length&&(r.cookieParameters=u.map(h=>this.parameter(h,i)));let m=this[xe](e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,d.aml.vocabularies.apiContract.statusCode,i);a&&typeof a=="string"&&(r.statusCode=a);let l=this[xe](e,d.aml.vocabularies.apiContract.header,i);Array.isArray(l)&&l.length&&(r.headers=l.map(m=>this.parameter(m,i)));let c=this[xe](e,d.aml.vocabularies.apiContract.payload,i);Array.isArray(c)&&c.length&&(r.payloads=c.map(m=>this.payload(m,i)));let p=e[this._getAmfKey(d.aml.vocabularies.apiContract.examples,i)];Array.isArray(p)&&p.length&&(r.examples=p.map(m=>this.example(m,i)));let u=e[this._getAmfKey(d.aml.vocabularies.apiContract.link,i)];return Array.isArray(u)&&u.length&&(r.links=u.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.core.mediaType,i);o&&typeof o=="string"&&(r.mediaType=o);let a=e[this._getAmfKey(d.aml.vocabularies.shapes.schema,i)];a&&(Array.isArray(a)&&([a]=a),r.schema=this.unknownShape(a,{trackedId:r.id},i));let l=e[this._getAmfKey(d.aml.vocabularies.apiContract.examples,i)];return Array.isArray(l)&&l.length&&(r.examples=l.map(c=>this.example(c,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.core.description,i);o&&typeof o=="string"&&(r.description=o);let a=this._getValue(e,d.aml.vocabularies.apiContract.operationId,i);a&&typeof a=="string"&&(r.operationId=a);let l=e[this._getAmfKey(d.aml.vocabularies.apiContract.server,i)];l&&(Array.isArray(l)&&([l]=l),r.server=this.server(l,i));let c=e[this._getAmfKey(d.aml.vocabularies.apiContract.mapping,i)];return c&&(c&&!Array.isArray(c)&&(c=[c]),c&&(r.mapping=c.map(p=>this.iriTemplateMapping(p,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,d.aml.vocabularies.apiContract.templateVariable,i);s&&typeof s=="string"&&(r.templateVariable=s);let o=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(d.aml.vocabularies.security.scheme,i)];o&&(Array.isArray(o)&&([o]=o),r.scheme=this.securityScheme(o,i));let a=e[this._getAmfKey(d.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,d.aml.vocabularies.security.type,i);s&&typeof s=="string"&&(r.type=s);let o=this._getValue(e,d.aml.vocabularies.core.name,i);o&&typeof o=="string"&&(r.name=o);let a=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.aml.vocabularies.core.displayName,i);o&&typeof o=="string"&&(r.displayName=o);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(r.description=a);let l=this._getValue(e,d.aml.vocabularies.security.type,i);l&&typeof l=="string"&&(r.type=l);let c=e[this._getAmfKey(d.aml.vocabularies.security.settings,i)];c&&(Array.isArray(c)&&([c]=c),r.settings=this.securitySettings(c,i));let p=e[this._getAmfKey(d.aml.vocabularies.apiContract.queryString,i)];p&&(Array.isArray(p)&&([p]=p),r.queryString=this.unknownShape(p,void 0,i));let u=this[xe](e,d.aml.vocabularies.apiContract.header,i);Array.isArray(u)&&u.length&&(r.headers=u.map(f=>this.parameter(f,i)));let m=this[xe](e,d.aml.vocabularies.apiContract.parameter,i);Array.isArray(m)&&m.length&&(r.queryParameters=m.map(f=>this.parameter(f,i)));let h=this[xe](e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(d.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(d.aml.vocabularies.security.OAuth1Settings)?this.oAuth1Settings(e,i):r.includes(d.aml.vocabularies.security.OAuth2Settings)?this.oAuth2Settings(e,i):r.includes(d.aml.vocabularies.security.ApiKeySettings)?this.apiKeySettings(e,i):r.includes(d.aml.vocabularies.security.HttpSettings)?this.httpSettings(e,i):r.includes(d.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,d.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let o=this._getValue(e,d.aml.vocabularies.security.requestTokenUri,i);o&&typeof o=="string"&&(r.requestTokenUri=o);let a=this._getValue(e,d.aml.vocabularies.security.tokenCredentialsUri,i);a&&typeof a=="string"&&(r.tokenCredentialsUri=a);let l=this._getValueArray(e,d.aml.vocabularies.security.signature,i);return Array.isArray(l)&&l.length?r.signatures=l:r.signatures=[],r}oAuth2Settings(e,t){let i=t||e["@context"],r=this.settings(e,i),s=this._getValueArray(e,d.aml.vocabularies.security.authorizationGrant,i);Array.isArray(s)&&s.length?r.authorizationGrants=s:r.authorizationGrants=[];let o=e[this._getAmfKey(d.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,d.aml.vocabularies.security.authorizationUri,i);s&&typeof s=="string"&&(r.authorizationUri=s);let o=this._getValue(e,d.aml.vocabularies.security.accessTokenUri,i);o&&typeof o=="string"&&(r.accessTokenUri=o);let a=this._getValue(e,d.aml.vocabularies.security.flow,i);a&&typeof a=="string"&&(r.flow=a);let l=this._getValue(e,d.aml.vocabularies.security.refreshUri,i);l&&typeof l=="string"&&(r.refreshUri=l);let c=e[this._getAmfKey(d.aml.vocabularies.security.scope,i)];return Array.isArray(c)&&c.length&&(r.scopes=c.map(p=>this.scope(p,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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=this._getValue(e,d.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,d.aml.vocabularies.security.scheme,i);s&&typeof s=="string"&&(r.scheme=s);let o=this._getValue(e,d.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,d.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(d.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(d.aml.vocabularies.docSourceMaps.synthesizedField,i)];Array.isArray(o)&&o.length&&(s.synthesizedField=o.map(m=>this.synthesizedField(m,i)));let a=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.lexical,i)];Array.isArray(a)&&a.length&&(s.lexical=a.map(m=>this.synthesizedField(m,i)));let l=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.trackedElement,i)];Array.isArray(l)&&l.length&&(s.trackedElement=this.synthesizedField(l[0],i));let c=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.autoGeneratedName,i)];Array.isArray(c)&&c.length&&(s.autoGeneratedName=c.map(m=>this.synthesizedField(m,i)));let p=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.parsedJsonSchema,i)];Array.isArray(p)&&p.length&&(s.parsedJsonSchema=this.synthesizedField(p[0],i));let u=r[this._getAmfKey(d.aml.vocabularies.docSourceMaps.declaredElement,i)];return Array.isArray(u)&&u.length&&(s.declaredElement=this.synthesizedField(u[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,d.aml.vocabularies.docSourceMaps.element,t);typeof r=="string"&&(i.element=r);let s=this._getValue(e,d.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,d.aml.vocabularies.core.name,i);s&&typeof s=="string"&&(r.name=s);let o=e[this._getAmfKey(d.aml.vocabularies.document.variable,i)];Array.isArray(o)&&o.forEach(l=>{r.variables.push(this.variableValue(l,i))});let a=e[this._getAmfKey(d.aml.vocabularies.document.target,i)];if(Array.isArray(a)&&a.length){let[l]=a;r.target=this.abstractDeclaration(l,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,d.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(d.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,d.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,d.aml.vocabularies.document.variable,i);Array.isArray(o)&&(s.variables=o);let a=this._getValue(e,d.aml.vocabularies.core.description,i);a&&typeof a=="string"&&(s.description=a);let l=e[this._getAmfKey(d.aml.vocabularies.document.dataNode,i)];if(Array.isArray(l)){let[c]=l;s.dataNode=this.unknownDataNode(c,i)}return s}endPointWithOperationsListItem(e,t){let i=this._getValue(e,d.aml.vocabularies.apiContract.path,t),r={id:e["@id"],path:i,operations:[]},s=this[xe](e,d.aml.vocabularies.apiContract.supportedOperation,t);Array.isArray(s)&&s.length&&(r.operations=s.map(a=>this.operationListItem(a,t)));let o=this._getValue(e,d.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,d.aml.vocabularies.apiContract.method,t);r&&typeof r=="string"&&(i.method=r);let s=this._getValue(e,d.aml.vocabularies.core.name,t);return s&&typeof s=="string"&&(i.name=s),i}};var mi=class n{mime;opts;generator;constructor(e,t={}){this.mime=e,this.opts=Object.freeze({...t}),e.includes("json")?this.generator=new pr(t):e.includes("xml")&&(this.generator=new ur(t))}static asExample(e,t,i){return new n(t,i).toExample(e)}static asSchema(e,t,i){return new n(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:[d.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 Ci=Object.freeze({processApiLink:"amfprocessapilink",processBuffer:"amfprocessbuffer",processApiFile:"amfprocessapifile",selectApiMainFile:"amfselectapimainfile"});var dp=Object.freeze({processApiLink:async(n,e,t,i,r=globalThis)=>{let s=new CustomEvent(Ci.processApiLink,{bubbles:!0,composed:!0,cancelable:!0,detail:{url:n,mainFile:e,md5:t,packaging:i}});return r.dispatchEvent(s),s.detail.result},processBuffer:async(n,e,t=globalThis)=>{let i=new CustomEvent(Ci.processBuffer,{bubbles:!0,composed:!0,cancelable:!0,detail:{buffer:n,opts:e}});return t.dispatchEvent(i),i.detail.result},processApiFile:async(n,e=globalThis)=>{let t=new CustomEvent(Ci.processApiFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{file:n}});return e.dispatchEvent(t),t.detail.result},selectApiMainFile:async(n,e=globalThis)=>{let t=new CustomEvent(Ci.selectApiMainFile,{bubbles:!0,composed:!0,cancelable:!0,detail:{candidates:n}});return e.dispatchEvent(t),t.detail.result}});var Ea=["string","number","boolean","date","datetime","time","binary","json"],mr;(function(n){n.string="string",n.number="number",n.boolean="boolean",n.date="date",n.datetime="datetime",n.time="time",n.file="binary",n.json="json"})(mr||(mr={}));var el=["required","multiple","primary","index","unique","search","readOnly","writeOnly","deprecated"],tl=["required","multiple"],il=["float","double","int32","int64"];function Vs(n,e){return n==="number"?e?.format==="int32"||e?.format==="int64"?d.w3.xmlSchema.integer:d.w3.xmlSchema.number:n==="boolean"?d.aml.vocabularies.shapes.boolean:n==="date"?d.w3.xmlSchema.date:n==="datetime"?d.w3.xmlSchema.dateTime:n==="time"?d.aml.vocabularies.shapes.dateTimeOnly:d.w3.xmlSchema.string}var hi=Symbol("noValue"),hr=class{increment=0;static noValue=hi;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):hi}generateString(e){switch(e){case"random":return Q(8);case"uuid-v4":return crypto.randomUUID();default:return hi}}generateNumber(e){return e==="incremental"?`${this.increment++}`:hi}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 hi}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 hi}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"),l=`${t.getSeconds()}`.padStart(2,"0");return`${i}-${r}-${s}T${o}:${a}:${l}`}return hi}};var xa="anyOf",pp="allOf",up="oneOf",mp="not",Oa="string",rl="binary",ii=class{#e;get valueGenerator(){return this.#e||(this.#e=new hr),this.#e}entity(e,t=new Set){if(t.has(e.key))return this.createRecursiveShape(e);t.add(e.key);let i=Ge.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=Ge.propertyShape(i);return r.path=`${d.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=Ge.propertyShape(r);return s.path=`${d.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||xa)===mp){let o=Ge.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=Ge.scalarShape(e.key);return t.id=`link-${e.key}`,t.dataType=Vs(Oa),t}createUnionShape(e,t){let i=Ge.unionShape(e.key);this.updateBaseProperties(e,i),i.anyOf=[];let r=e.schema&&e.schema.unionType||xa;return r===xa?i.anyOf=t:r===pp?i.and=t:r===up?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===rl?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 l=this.valueGenerator.generate(a,e.type);if(l!==hr.noValue){let c=vt.scalar(l,o);t.defaultValue=c.toJSON()}}else{let l=vt.scalar(a,r);t.defaultValue=l.toJSON()}}Array.isArray(i.enum)&&(t.values=i.enum.map(o=>vt.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=Ge.arrayShape(e.key),{type:s}=e;if(s===rl?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=Ge.scalarShape(e.key);return this.updateBaseProperties(e,r),this.setScalarCommonProperties(r,e,i),r.dataType||(r.dataType=Vs(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:Q(),customDomainProperties:[],strict:!0,types:[...sr.IAmfExampleTypes],structuredValue:vt.scalar(r,t).toJSON()};i.push(s)}return i}createArrayExamples(e,t){let i={id:Q(),customDomainProperties:[],strict:!0,types:[...sr.IAmfExampleTypes]},r=new vt("array");for(let s of e){let o=vt.scalar(s,t);r.addMember(o)}return i.structuredValue=r.toJSON(),[i]}createFileShape(e,t){let i=Ge.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===Oa?e.minLength=r.minimum:e.minimum=r.minimum),typeof r.maximum=="number"&&(s===Oa?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=d.w3.xmlSchema.double;break;case"float":e.format=d.w3.xmlSchema.float;break;case"int32":e.format=d.w3.xmlSchema.integer;break;case"int64":e.format=d.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 l="";t.type==="number"?l=0:t.type==="boolean"&&(l=!1);let c=("dataType"in e?e.dataType:void 0)||Vs(t.type,i);e.examples=this.createExamples([String(l)],c)}}updateBaseProperties(e,t){t.name=e.info.name,t.displayName=e.info.displayName,t.description=e.info.description,(e.kind===he||e.kind===R)&&(t.deprecated=e.deprecated)}createRecursiveShape(e){return Ge.recursiveShape(e.key,e.key)}refactorShapeToArray(e,t){let i=Ge.arrayShape(e);return i.items=t,i}};var ri=class n extends tt{kind;info;required;multiple;primary;unique;index;search;readOnly;writeOnly;deprecated;tags=[];semantics=[];type="string";jsonSchema;jsonIndex;schema;bindings=[];lineage;static createSchema(e={}){let{key:t=Q(),multiple:i,required:r,type:s=mr.string,index:o,search:a,primary:l,unique:c,readOnly:p,writeOnly:u,tags:m,semantics:h,deprecated:f,schema:k,bindings:v,jsonSchema:E,jsonIndex:$,lineage:j}=e;if(typeof s=="string"&&!Ea.includes(s))throw new Error(`Invalid data property type ${s}`);let C=pe.fromJSON(e.info,{name:"new_property"}).toJSON(),I={kind:he,key:t,info:C,type:s};return E&&(I.jsonSchema=structuredClone(E)),$&&(I.jsonIndex=structuredClone($)),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 l=="boolean"&&(I.primary=l),typeof c=="boolean"&&(I.unique=c),typeof p=="boolean"&&(I.readOnly=p),typeof u=="boolean"&&(I.writeOnly=u),typeof f=="boolean"&&(I.deprecated=f),Array.isArray(m)&&(I.tags=[...m]),Array.isArray(h)&&(I.semantics=[...h]),k&&(I.schema=structuredClone(k)),Array.isArray(v)?I.bindings=v.map(T=>structuredClone(T)):I.bindings=[],j&&(I.lineage=structuredClone(j)),I}parent;constructor(e,t,i={}){let r=n.createSchema(i);super(e,r.key),this.parent=t,this.kind=he,this.info=new pe(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.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!==he)}toJSON(){let e={kind:this.kind,key:this.key,info:this.info.toJSON(),type:this.type||mr.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.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:Ea.includes(e)}static isValidAttribute(e){return typeof e!="string"?!1:el.includes(e)}static isValidFormat(e){return e===void 0?!0:typeof e!="string"?!1:!!il.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 g(`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 ii().property(this)}toExample(e,t={}){let i=this.toApiShape();return i.range?new mi(e,{renderExamples:t.renderExamples??!0,renderMocked:t.renderMocked??!0,renderOptional:t.renderOptional??!0,selectedUnions:t.selectedUnions}).generate(i):void 0}addSemantic(e){this.root.ensureWritable();let t=dt[e.id];if(!ps(t))throw new Error(`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 Error(`Cannot duplicate property ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(c=>c.key===this.key);if(t===-1)throw new Error(`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,l=e.fields[a];return e.fields.splice(a,1),e.fields.splice(t+1,0,l),o}setLineage(e,t){this.lineage={id:t,key:e.key,kind:e.kind},e.namespace!==this.root.key&&(this.lineage.domain=e.namespace)}};var si=class extends g{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 Ue(n,e){if(!n.hasNode(e))return;let t=n.node(e);if(t){if(t.kind===de){n.removeNode(e);return}for(let i of n.children(e))Ue(n,i);for(let i of n.outEdges(e)){let r=n.edge(i);r&&(r.type==="association"||r.type==="property")&&Ue(n,i.w)}n.removeNode(e)}}var Ti=class n extends tt{kind;info;required;multiple;schema;bindings;parent;targets;semantics=[];onDelete;readOnly;fields;static createSchema(e={}){let{key:t=Q(),semantics:i=[]}=e,r=pe.fromJSON(e.info,{name:"new_association"}).toJSON(),s={kind:de,key:t,info:r};return 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=n.createSchema(i);super(e,r.key),this.parent=t,this.kind=de,this.info=new pe(r.info),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)}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 ri(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(){for(let{key:e}of this.fields){let t=this.root.graph.node(e);!t||t.kind!==he||(yield t)}}removeProperty(e){this.root.ensureWritable();let t=this.fields.findIndex(r=>r.key===e&&r.type==="property");if(!this.root.graph.hasNode(e))throw new si(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new si(`Trying to remove the ${e} property, but it doesn't belong to this association`);Ue(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(){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(){return this.schema||(this.schema={}),this.schema}static isValidAttribute(e){return typeof e!="string"?!1:tl.includes(e)}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 g(`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){this.root.ensureWritable();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)}removeTarget(e){this.root.ensureWritable();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)}*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 ii().associationProperty(this)}checkPreconditions(e){let t=dt[e];if(!(!t||!us(t)||!t.preconditions||t.preconditions.length===0)){for(let i of t.preconditions)if(i.kind==="associationMultiple"){if(this.multiple!==i.multiple)throw new g(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 g(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(p=>r.hasSemantic(p)):r.hasSemantic(a.parent))?s.some(p=>Array.isArray(a.target)?a.target.some(u=>p.hasSemantic(u)):p.hasSemantic(a.target)):!1))throw new g(i.unmetMessage||`Association entity pairing precondition check failed for semantic ${e}.`,{status:400})}}}getReciprocalAssociations(e){let t=[],i=this.root,r=this.getParentInstance()?.key??"";for(let s of i.listEntities())for(let o of s.listAssociations())if(!(o.key===this.key&&s.key===r)){for(let a of o.semantics)if(a.link&&a.link.key===this.key&&(!e||a.id===e)){t.push(o);break}}return t}toggleOptionalSemanticProperty(e,t,i){this.root.ensureWritable();let r=dt[e];if(!r||!us(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(c=>c.value.info?.name===t);if(!o)throw new Error(`Property "${t}" is not defined in semantic blueprint ${e}.`);let l=Array.from(this.listProperties()).find(c=>c.info.name===t||c.lineage?.id===e&&c.info.name===t);if(i){if(l)return l;let c={...o.value,lineage:{key:this.key,kind:de,domain:this.root.key,id:e}};return this.addProperty(c)}else{l&&l.remove();return}}addSemantic(e){this.root.ensureWritable();let t=dt[e.id];if(!us(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:de,domain:this.root.key,id:e.id}};this.addProperty(a)}})}removeSemantic(e){this.root.ensureWritable();let t=this.semantics.findIndex(s=>s.id===e);t>=0&&this.semantics.splice(t,1);let i=Array.from(this.listProperties()).filter(s=>s.lineage?.id===e);for(let s of i)s.remove();let r=this.getReciprocalAssociations(e);for(let s of r)s.removeSemantic(e),s.semantics.length===0&&s.remove()}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 Error(`Cannot duplicate association ${this.key} as it has no parent entity.`);let t=e.fields.findIndex(c=>c.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 c of this.listProperties()){let p=c.toJSON();delete p.key,o.addProperty(p)}for(let c of this.targets)o.addTarget(c.key,c.domain);let a=e.fields.length-1,l=e.fields[a];return e.fields.splice(a,1),e.fields.splice(t+1,0,l),o}};var fi=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 sl=n=>{let e=n.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 ol from"dompurify";var Pa;function hp(){return typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"}if(hp()){let{JSDOM:n}=await import("jsdom"),{window:e}=new n("<!DOCTYPE html>");Pa=ol(e)}else Pa=ol;var al=Pa;function fp(n){return al.sanitize(n)}function nl(n,e="untitled_column"){let t=fp(n);return t=sl(t),t=t.replace(/[\s-]+/g,"_"),t=t.replace(/[^a-z0-9_]/g,""),t=t.replace(/^_+|_+$/g,""),t||e}function ll(n,e,t="untitled_table"){let i=nl(n,t);return`${nl(e.slice(0,8))}_${i}`}function cl(n){let{entityName:e,assocName:t,targetEntityName:i,pkName:r,isMultiple:s,isOrgResources:o,useTargetTableInColumnName:a}=n,l;return o&&s?l=`${e}_${r}`:a&&i?l=`${e}_${t}_${i}_${r}`:l=`${e}_${t}_${r}`,yp(l)}function gp(n,e=0){let t=3735928559^e,i=1103547991^e;for(let r=0,s;r<n.length;r++)s=n.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 yp(n){if(n.length<=63)return n;let e=gp(n).toString(16).padStart(8,"0").substring(0,8);return`${n.substring(0,54)}_${e}`}var Di=class n extends tt{kind;#e;#t;#i;#r;info;tags;semantics=[];fields;deprecated;static createSchema(e={}){let{key:t=Q(),tags:i,semantics:r,fields:s,deprecated:o}=e,a=pe.fromJSON(e.info,{name:"new_entity"}).toJSON(),l={kind:R,key:t,info:a};return Array.isArray(i)&&(l.tags=[...i]),Array.isArray(r)&&(l.semantics=[...r]),Array.isArray(s)&&(l.fields=[...s]),typeof o=="boolean"&&(l.deprecated=o),l}constructor(e,t){let i=n.createSchema(t);super(e,i.key),this.kind=R,this.info=new pe(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 g(`Entity ${this.key} has no exposed name defined`,{code:"E_MISSING_EXPOSED_NAME",status:500});return e}getDatabaseTableName(){return ll(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 ri(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 si(`Trying to remove the ${e} property, but it doesn't exist`);if(this.root.graph.node(e).getParentInstance()!==this)throw new si(`Trying to remove the ${e} property, but it doesn't belong to this entity`);Ue(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!==he||(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 fi([{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 fi([{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 fi([{field:"parents",message:s,rule:"circular"}],{message:s})}if(r.outEdges(this.key,i).next().value){let s=`Parent ${e} already exists`;throw new fi([{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:R});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 l=`${a.domain}:${a.key}`;if(!t.hasNode(l))throw new Error(`Foreign entity ${l} not found`)}else if(!t.hasNode(a.key))throw new Error(`Target entity ${a.key} not found`)}let o=new Ti(this.root,this.key,i);if(t.setNode(o.key,o),t.setEdge(this.key,o.key,{type:"association"}),s)for(let a of r)o.addTarget(a.key,a.domain);return this.fields.push({type:"association",key:o.key}),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()}Ue(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!==de||(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===de||t.kind===he)&&(yield t)}}hasFields(){return this.fields.length>0}removeField(e){this.fields=this.fields.filter(t=>t.key!==e)}toApiShape(){return new ii().entity(this)}toExample(e,t={}){let i=this.toApiShape();return new mi(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=dt[e.id];if(!Za(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.semantics.some(l=>l.id===y.OrganizationMembers||l.id===y.ProjectMembers))continue;let r=t.getParentInstance();if(!r)continue;let s=r.primaryKey();if(!s)continue;let o=t.hasSemantic(y.OrganizationResource)||t.hasSemantic(y.ProjectResource);yield{name:cl({entityName:r.getExposedName(),assocName:t.getExposedName(),pkName:s.getExposedName(),isMultiple:!0,isOrgResources:o}),primaryKey:s,sourceEntity:r,association:t}}}};var Mi=class extends g{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 We=class extends g{static code="E_ATTACH";static status=500;static message="Error attaching the object.";static help="Make sure you are attaching the right object."};var Et=class extends g{static code="E_DETACH";static status=500;static message="Error detaching the object.";static help="Make sure you are detaching the right object."};var oi=class n extends tt{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=Q(),fields:i,deprecated:r}=e,s=pe.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=n.createSchema(t);super(e,i.key),this.kind=Oe,this.info=new pe(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 Di(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 Mi(`Trying to remove the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==R)throw new Mi(`Trying to remove the ${e} entity, but it is not an entity`);if(t.getParentInstance()!==this)throw new Mi(`Trying to remove the ${e} entity, but it is not a child of this model`);Ue(this.root.graph,e),this.removeField(e)}attachEntity(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new We(`Trying to attach the ${e} entity, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==R)throw new We(`Trying to attach the ${e} entity, but it is not a entity`);if(t.domain.key!==this.root.key)throw new We(`Trying to attach the ${e} entity, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new We(`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 We(`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 Et(`Trying to detach the ${e} entity, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==R)throw new Et(`Trying to detach the ${e} entity, but it is not an entity`);if(i.getParentInstance()!==this)throw new Et(`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!==R||(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 gi=class extends g{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 fr=class extends g{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 Li=class n extends tt{kind;info;fields;deprecated;static createSchema(e={}){let{key:t=Q(),fields:i,deprecated:r}=e,s=pe.fromJSON(e.info,{name:"New namespace"}).toJSON(),o={kind:Re,key:t,info:s};return Array.isArray(i)&&(o.fields=[...i]),typeof r=="boolean"&&(o.deprecated=r),o}constructor(e,t){let i=n.createSchema(t);super(e,i.key),this.kind=Re,this.info=new pe(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 n(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 gi(`Trying to remove the ${e} namespace, but it doesn't exist`);let t=this.root.graph.node(e);if(!t||t.kind!==Re)throw new gi(`Trying to remove the ${e} namespace, but it is not a namespace`);return Ue(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!==Re)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 We(`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 gi(`Trying to detach the ${e} namespace, but it doesn't exist`);let i=this.root.graph.node(e);if(!i||i.kind!==Re)throw new gi(`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!==Re||(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 oi(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 fr(`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 fr(`Trying to remove the ${e} model, but it is not a model`);return Ue(this.root.graph,e),this.removeField(e),this}attachModel(e){if(this.root.ensureWritable(),!this.root.graph.hasNode(e))throw new We(`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 We(`Trying to attach the ${e} model, but it is not a model`);if(t.domain.key!==this.root.key)throw new We(`Trying to attach the ${e} model, but it is not in the same domain`);let i=t.getParentInstance();if(i===this)throw new We(`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 Et(`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 Et(`Trying to detach the ${e} model, but it is not a model`);if(i.getParentInstance()!==this)throw new Et(`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===Re||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 Ui(n,e,t){return n+""+e+""+(t||"\0")}function Ia(n,e,t){let i={v:n,w:e};return t&&(i.name=t),i}var Fs=class n{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 n({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)],l=[];for(;a.length>0;){let c=!1;for(let u of a)t.hasNode(u)&&(l.push(u),c=!0);if(c)break;let p=[];for(let u of a)for(let m of this.parents(u))p.push(m);a=p}l.length===0&&l.push("\0"),s.set(o,l)}for(let[o,a]of s){this.removeParent(o);for(let l of a)t.addParent(o,l)}}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=Ia(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=Ui(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 u=Ia(t.w,t.v,t.name);r?this._setEdge({loop:1},u,i):this._setEdge({loop:1},u)}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 l=r?s:this.defaultEdgeLabelFn(t.v,t.w,t.name);this.edgeLabelsValue.set(o,l),this.edgeObjectsValue.set(o,t);let c=this.predecessorsValue.get(t.w);if(c){let u=(c.get(t.v)||0)+1;c.set(t.v,u)}let p=this.successorsValue.get(t.v);if(p){let u=(p.get(t.w)||0)+1;p.set(t.w,u)}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 u=Ia(t.w,t.v,t.name);r?this._setEdge({loop:1},u,i):typeof l=="object"&&l!==null?this._setEdge({loop:1},u,l):this._setEdge({loop:1},u)}}edge(e,t,i){let r;return typeof e=="object"?r=Ui(e.v,e.w,e.name):r=Ui(e,t,i),this.edgeLabelsValue.get(r)}hasEdge(e,t,i){let r;return typeof e=="object"?r=Ui(e.v,e.w,e.name):r=Ui(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=Ui(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 c=(a.get(o.v)||0)-1;c<=0?a.delete(o.v):a.set(o.v,c)}let l=this.successorsValue.get(o.v);if(l){let c=(l.get(o.w)||0)-1;c<=0?l.delete(o.w):l.set(o.w,c)}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 bp(n,e){let t=[];for(let i of n.nodes()){let r=n.node(i);if(!r||r.domain.key!==e)continue;let s=[...n.parents(i)],o={v:i};o.value=r.toJSON(),s.length&&(o.parents=s),t.push(o)}return t}function kp(n,e){let t=[];for(let i of n.edges()){let r=n.edge(i);if(!r)continue;let s=n.node(i.v),o=n.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 vp(n,e){let t=[],i=new Set;for(let r of n.nodes()){let s=n.node(r);s&&s.domain.key===e&&i.add(r)}for(let r of i){let s=n.node(r);if(s){if(s.kind===he||s.kind===de){let a=[...n.inEdges(r)].filter(l=>{let c=n.node(l.v);return c&&c.domain.key===e});if(a.length===0){let l=s.kind===he?"Property":"Association";t.push(`${l} "${s.info.name}" (${r}) has no parent entity edge. This will cause deserialization to fail.`)}else if(a.length>1){let l=s.kind===he?"Property":"Association",c=a.map(p=>p.v).join(", ");t.push(`${l} "${s.info.name}" (${r}) has multiple parent edges: ${c}. This may cause deserialization issues.`)}else{let l=a[0],c=n.node(l.v);if(!c||c.kind!==R&&c.kind!==de){let p=s.kind===he?"Property":"Association";t.push(`${p} "${s.info.name}" (${r}) has a parent that is not an entity or association. Parent: ${c?.kind||"unknown"} (${l.v})`)}}}if(s.kind===R&&([...n.parents(r)].some(l=>{let c=n.node(l);return c&&c.kind===Oe})||t.push(`Entity "${s.info.name}" (${r}) has no model parent. Entities must belong to a model.`)),s.kind===Oe){let o=[...n.parents(r)],a=o.some(l=>{let c=n.node(l);return c&&c.kind===Re});if(o.length>0&&!a){let l=o.map(c=>`${n.node(c)?.kind||"unknown"} (${c})`).join(", ");t.push(`Model "${s.info.name}" (${r}) has invalid parent types: ${l}. Models can only belong to namespaces or be at root level.`)}}}}for(let r of i){let s=n.node(r);if(s&&s.kind===de){let o=s,l=[...n.outEdges(r)].filter(c=>{let p=n.edge(c);return p&&p.type==="association"});l.length;for(let c of l){let p=n.node(c.w);p?p.kind!==R&&t.push(`Association "${o.info.name}" (${r}) references non-entity target: ${p.kind} (${c.w})`):t.push(`Association "${o.info.name}" (${r}) references non-existent target: ${c.w}`)}}}if(t.length>0)throw new Error(`Graph consistency validation failed for domain "${e}":
52
52
  `+t.map(r=>` - ${r}`).join(`
53
- `))}function sl(n,e){return pp(n,e),{options:{directed:n.isDirected(),multigraph:n.isMultigraph(),compound:n.isCompound()},nodes:cp(n,e),edges:dp(n,e)}}function al(n,e){for(let t of n.nodes()){let i=n.node(t);i&&i.domain.key===e&&n.removeNode(t)}}function So(n,e,t){let i=new Set,r=new Set;for(let a of e.nodes()){let o=e.node(a);if(!o)continue;let l=`${t}:${a}`;n.setNode(l,o),i.add(l)}for(let a of e.edges()){let o=e.edge(a);if(!o)continue;let l=`${t}:${a.v}`,c=`${t}:${a.w}`;n.setEdge(l,c,{foreign:!0,domain:t,...o}),r.add(`${l}|${c}`)}let s=new Set;for(let a of e.nodes()){let o=`${t}:${a}`;for(let l of e.parents(a)){let c=`${t}:${l}`,p=n.node(o),u=n.node(c);p.kind===j&&u.kind===j?s.has(o)?n.addParent(o,c):(s.add(o),n.setParent(o,c)):n.setParent(o,c)}}return{nodes:i,edges:r}}function rl(n,e){for(let t of e)if(t.w===n)return t.v}function up(n,e,t,i,r){if(!e){let a={type:"malformed_entry",severity:"error",message:"Unable to restore data domain graph. Malformed node entry"};if(r.push(a),i==="strict")throw new Error(a.message);return}let s=e;if(!s.kind){let a={type:"malformed_entry",severity:"error",message:"Unable to restore data domain graph. Node entry missing kind property",affectedKey:s.key};if(r.push(a),i==="strict")throw new Error(a.message);return}try{if(s.kind===Ie)return new Ti(n,s);if(s.kind===Ee)return new ri(n,s);if(s.kind===j)return new Ri(n,s);if(s.kind===he){let o=s,l=rl(o.key,t);if(!l){let c={type:"missing_edge",severity:"error",message:`Property "${o.info?.name||o.key}" has no parent entity edge`,affectedKey:o.key,resolution:i==="lenient"?"Property will be skipped":void 0};if(r.push(c),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new ti(n,l,o)}if(s.kind===de){let o=s,l=rl(o.key,t);if(!l){let c={type:"missing_edge",severity:"error",message:`Association "${o.info?.name||o.key}" has no parent entity edge`,affectedKey:o.key,resolution:i==="lenient"?"Association will be skipped":void 0};if(r.push(c),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new ji(n,l,o)}let a={type:"unknown_kind",severity:"error",message:`Unknown node kind: ${s.kind}`,affectedKey:s.key};if(r.push(a),i==="strict")throw new Error(`Unable to restore data domain graph. Unknown node kind ${s.kind}`);return}catch(a){let o={type:"malformed_entry",severity:"error",message:`Failed to create node: ${a instanceof Error?a.message:String(a)}`,affectedKey:s.key};if(r.push(o),i==="strict")throw a;return}}function ol(n,e={}){let{json:t,dependencies:i,mode:r="strict"}=e,s=new Us({compound:!0,multigraph:!0,directed:!0}),a=[],o=new Set,l=new Set;if(i)for(let p of i)try{let u=So(s,p.graph,p.key);u.edges.size&&(l=new Set([...l,...u.edges])),u.nodes.size&&(o=new Set([...o,...u.nodes])),n.dependencies.set(p.key,p)}catch(u){let m=`Failed to merge dependency "${p.key}": ${u instanceof Error?u.message:String(u)}`;if(r==="strict")throw new Error(m,{cause:u});let h={type:"missing_dependency",severity:"error",message:m,affectedKey:p.key,resolution:"Dependency will be skipped"};a.push(h)}if(!t)return{graph:s,issues:a,success:!0};if(Array.isArray(t.nodes)){let p=new Map;for(let u of t.nodes){let m=up(n,u.value,t.edges,r,a);m&&(s.setNode(u.v,m),u.parents&&p.set(u.v,u.parents))}for(let[u,m]of p){if(!s.hasNode(u)){let h={type:"missing_node",severity:"warning",message:`Cannot set parents for missing node: ${u}`,affectedKey:u,resolution:"Parent relationship will be skipped"};a.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 "${u}"`,affectedKey:u,context:{parentKey:h},resolution:"Parent relationship will be skipped"};a.push(f);continue}try{s.setParent(u,h)}catch(f){let w={type:"invalid_parent",severity:"warning",message:`Failed to set parent "${h}" for child "${u}": ${f instanceof Error?f.message:String(f)}`,affectedKey:u,context:{parentKey:h},resolution:"Parent relationship will be skipped"};a.push(w)}}}}if(Array.isArray(t.edges))for(let p of t.edges){if(!p.value){let u="Edge entry missing value";if(r==="strict")throw new Error(u);let m={type:"malformed_entry",severity:"error",message:u,context:{edge:p}};a.push(m);continue}if(p.value.foreign&&!o.has(p.w)){let u={type:"missing_node",severity:"warning",message:`Missing foreign node: ${p.w}`,affectedKey:p.w,resolution:"Edge will be skipped"};a.push(u);continue}if(o.has(p.v)||o.has(p.w)){if(!s.hasNode(p.v)||!s.hasNode(p.w)){let u={type:"missing_node",severity:"warning",message:`Missing foreign node for edge: ${p.v} -> ${p.w}`,context:{sourceNode:p.v,targetNode:p.w},resolution:"Edge will be skipped"};a.push(u);continue}}else{if(!s.hasNode(p.v)){let u={type:"missing_node",severity:"warning",message:`Source node not found for edge: ${p.v}`,affectedKey:p.v,resolution:"Edge will be skipped"};a.push(u);continue}if(!s.hasNode(p.w)){let u={type:"missing_node",severity:"warning",message:`Target node not found for edge: ${p.w}`,affectedKey:p.w,resolution:"Edge will be skipped"};a.push(u);continue}}try{s.setEdge({v:p.v,w:p.w,name:p.name},p.value)}catch(u){let h={type:"malformed_entry",severity:"warning",message:`Failed to create edge ${p.v} -> ${p.w}: ${u instanceof Error?u.message:String(u)}`,context:{sourceNode:p.v,targetNode:p.w},resolution:"Edge will be skipped"};a.push(h)}}for(let p of s.nodes()){let u=s.node(p);if(u){if(u.kind===he){let m=u,h=m.parent?s.node(m.parent):void 0;h&&Array.isArray(h.fields)&&(h.fields.some(v=>v.key===m.key&&v.type==="property")||h.fields.push({type:"property",key:m.key}))}else if(u.kind===de){let m=u,h=m.parent?s.node(m.parent):void 0;h&&Array.isArray(h.fields)&&(h.fields.some(v=>v.key===m.key&&v.type==="association")||h.fields.push({type:"association",key:m.key}))}}}let c=a.some(p=>p.severity==="error");return{graph:s,issues:a,success:!c}}var Mi=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 Qe=class n extends Mi{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=Q(),fields:i,lifecycle:r="draft",previousVersion:s}=e,a=pe.fromJSON(e.info,{name:"Unnamed domain"}).toJSON(),o={kind:Re,key:t,info:a,lifecycle:r};return s&&(o.previousVersion=s),e.dependencyList&&(o.dependencyList=structuredClone(e.dependencyList)),e.graph&&(o.graph=e.graph),Array.isArray(i)&&(o.fields=[...i]),o}constructor(e,t=[],i){let r=n.createSchema(e),s=[];for(let l of t)if(l instanceof n)l.readOnly?s.push(l):(console.warn(`Domain ${l.key} is not read only, cloning it. This may have performance implications.`),s.push(l.clone({readOnly:!0})));else if(typeof l=="object"&&l.kind===Re&&l.key){let c=new n(l,void 0,{readOnly:!0});s.push(c)}else throw new Error(`Invalid foreign domain dependency: ${l}`);super(r.dependencyList,s),this.kind=r.kind,this.key=r.key,this.info=new pe(r.info),this.readOnly=i?.readOnly||!1,this.lifecycle=r.lifecycle||"draft",this.previousVersion=r.previousVersion;let a=i?.mode||"strict",o=ol(this,{json:r.graph,dependencies:s,mode:a});this.graph=o.graph,o.issues.length>0&&a==="lenient"&&(this.issues=o.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 n(t,i,r)}toJSON(){let e={info:this.info.toJSON(),kind:this.kind,key:this.key,graph:sl(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===Ie||t.kind===Ee)&&(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!==Ie)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 Ti(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!==Ie)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?(Le(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!==Ie||(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===Ie&&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===Ie)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 a=this.findNamespace(t);if(a&&a.domain.key!==this.key)throw new Error("Cannot move a namespace to a foreign domain");if(!a)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 ri(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!==Ee)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?(Le(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 a of s.listModels()){let o=t===this.key?a.key:`${t}:${a.key}`,l=this.graph.node(o);l&&(yield l)}return}if(!r)for(let{key:s,type:a}of this.fields){if(a!=="model")continue;let o=this.graph.node(s);o&&o.kind===Ee&&(yield o)}if(i||r)for(let[s,a]of this.dependencies)for(let o of a.listModels()){let l=`${s}:${o.key}`,c=this.graph.node(l);c&&(yield c)}}*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===Ee&&i.domain.key===this.key&&(yield i)}}findModel(e,t){let i=this.graph.node(this.buildReferenceKey(e,t));if(i&&i.kind===Ee)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 a=t?this.graph.children(t):this.graph.nodes();for(let o of a){let l=this.graph.node(o);if(l&&l.kind===j){let c=l.domain.key===this.key;if(i){l.domain.key===i&&(yield l);continue}s?c||(yield l):r?yield l:c&&(yield l)}}}*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===j)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),a=this.findModel(i);if(!r||!s||!a)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(a.domain.key!==this.key)throw new Error("Cannot move an entity to a foreign domain");a.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!==de)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===de)return i}getIncomingAssociations(e){let t=[];for(let i of this.graph.inEdges(e)){let r=this.graph.node(i.v);r&&r.kind===de&&t.push(r)}return t}findAssociationBetween(e,t){let i=this.graph.node(e);if(!i||i.kind!==j)return;let r=i;for(let s of r.listAssociations())for(let a of s.targets)if(this.buildReferenceKey(a.key,a.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 a of i.withInheritedAssociations())for(let o of a.targets)if(this.buildReferenceKey(o.key,o.domain)===s){yield a;break}}resolveOwnershipPath(e){let t=this.findEntity(e);if(!t)return null;if(t.hasSemantic(y.User))return[];for(let s of t.listAssociations())if(s.hasSemantic(y.ResourceOwnerIdentifier))return[s];let i=[{key:e,path:[]}],r=new Set([e]);for(;i.length>0;){let s=i.shift();if(!s)continue;let a=this.findEntity(s.key);if(!a)continue;let o=[...a.listAssociations()].filter(u=>u.hasSemantic(y.CreatedBy)||u.hasSemantic(y.UpdatedBy)||u.hasSemantic(y.DeletedBy)?!1:u.hasSemantic(y.RelationalResourceOwner)||u.hasSemantic(y.ResourceOwnerIdentifier)?!0:u.listTargets().some(m=>m.hasSemantic(y.User))),c=this.getIncomingAssociations(s.key).filter(u=>{if(u.hasSemantic(y.CreatedBy)||u.hasSemantic(y.UpdatedBy)||u.hasSemantic(y.DeletedBy))return!1;let m=u.getParentInstance();return m?m.hasSemantic(y.User)||u.schema?.embedded===!0:!1}),p=[...o,...c];for(let u of p){let m=u.getParentInstance();if(!m)continue;let h=[...u.listTargets()];if(h.length!==0)for(let f of h){let v=s.key===m.key?f.key:m.key;if(r.has(v))continue;let w=this.findEntity(v);if(!w)continue;let E=[...s.path,u];if(w.hasSemantic(y.User)||u.hasSemantic(y.ResourceOwnerIdentifier))return E;r.add(v),i.push({key:v,path:E})}}}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!==he)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===he)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}),So(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),al(this.graph,t.key)}removeDomainElement(e,t){switch(t){case Ie:this.removeNamespace(e);break;case Ee:this.removeModel(e);break;case j:this.removeEntity(e);break;case he:this.removeProperty(e);break;case de: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,a=[],o=!t&&(!i||i.length===0),l=m=>!i||i.length===0?!0:i.includes(m),c=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)},p=m=>{if(!t)return[];let h=[],{info:f}=m;return c(f.name)&&h.push("name"),c(f.displayName)&&h.push("displayName"),c(f.description)&&h.push("description"),h},u=m=>m.includes(":");for(let m of this.graph.nodes()){let h=this.graph.node(m);if(!h||!h.info)continue;let f=u(m);if(f&&!r||!l(h.kind))continue;if(o){a.push({node:h,matchedFields:[],key:m,isForeign:f});continue}let v=p(h);(!t||v.length>0)&&a.push({node:h,matchedFields:v,key:m,isForeign:f})}return a}};var zs=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","COMMIT","ROLLBACK","SAVEPOINT","BEGIN","END","CASE","WHEN","THEN","ELSE","END CASE","EXCEPTION","RAISE","RETURN","FUNCTION","PROCEDURE"]);function Vs(n){let e=[],t=n.info.getLabel(),i=n.getParentInstance();if(!i)return e;let r;if(i.kind===j)r=i.key;else{let o=i.getParentInstance();if(!o)return e;r=o.key}let s=n.kind===he?"property":"association";if(!n.info.name){let o=`The "${t}" ${s} has no name.`,l=`The ${s} must have a name.`;return e.push({field:"name",rule:"required",message:o,help:l,severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),e}let a=n.info.name;if(a.length<2){let o=`The "${t}" ${s} name is too short.`;e.push({field:"name",rule:"length",message:o,help:"The name must be at least 2 characters long.",severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(a.length>59){let o=`The "${t}" ${s} name is too long.`;e.push({field:"name",rule:"length",message:o,help:"The name must be at most 59 characters long.",severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){let o=`The "${t}" ${s} name is invalid.`;e.push({field:"name",rule:"format",message:o,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:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(/^[A-Z]/.test(a)){let o=`The "${t}" ${s} name is not in snake case.`;e.push({field:"name",rule:"snake_case",message:o,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(zs.has(a.toUpperCase())){let o=`The "${t}" ${s} name is a reserved keyword.`;e.push({field:"name",rule:"reserved",message:o,help:"The name should not be a reserved keyword.",severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}return e}var Fs=class{domain;constructor(e){this.domain=e}validate(e){let t=[],i;if(typeof e=="string"?i=this.domain.findAssociation(e):i=e,!i){let o=`The "${e}" association does not exist.`;return t.push({field:"*",rule:"exists",message:o,help:"The association must be defined in the domain.",key:e,kind:de,severity:"error",parentKind:j}),t}let r=this.validateName(i);t.push(...r);let s=this.validateTargets(i);t.push(...s);let a=this.validateSemantics(i);return t.push(...a),t}validateName(e){return Vs(e)}validateTargets(e){let t=[],i=e.info.getLabel(),r=e.getParentInstance();if(!e.targets.length){let s=`The "${i}" association has no target.`;return t.push({field:"targets",rule:"required",message:s,help:"An association must have at least one target.",severity:"error",key:e.key,kind:e.kind,parent:r.key,parentKind:j}),t}for(let s of e.targets)if(!this.domain.findEntity(s.key,s.domain)){let o=`The "${i}" association has an invalid target "${s.key}".`;t.push({field:"targets",rule:"exists",message:o,help:"The target must be defined in the domain.",severity:"error",key:e.key,kind:e.kind,parent:r.key,parentKind:j})}return t}validateSemantics(e){let t=[],i=e.info.getLabel(),r=e.getParentInstance();if(e.hasSemantic(y.RelationalResourceOwner))for(let s of e.targets){let a=this.domain.findEntity(s.key,s.domain);a&&this.domain.resolveOwnershipPath(a.key)===null&&t.push({field:"semantics",rule:"relational_owner_path_valid",message:`The target entity "${a.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:j})}return t}};var Ks=class{domain;constructor(e){this.domain=e}validate(e){let t=[],i;if(typeof e=="string"?i=this.domain.findEntity(e):i=e,!i){let c=`The "${e}" entity does not exist.`;return t.push({field:"*",rule:"exists",message:c,help:"The entity must be defined in the domain.",key:e,kind:j,severity:"error",parentKind:j}),t}let r=this.validatePrimaryKey(i);t.push(...r);let s=this.minimumRequiredProperties(i);t.push(...s);let a=this.validateName(i);t.push(...a);let o=this.uniqueName(i);t.push(...o);let l=this.validateUserSemantics(i);return t.push(...l),t}validatePrimaryKey(e){let t=[];if(!e.primaryKey()){let r=`The "${e.info.getLabel()}" entity has no identifier.`;t.push({field:"properties",rule:"primary_key",message:r,help:"An entity that can exists by itself must have identifier defined.",severity:"error",key:e.key,kind:e.kind,parentKind:j})}return t}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){let t=[],i=this.hasPropertiesInherited(e),r=this.hasAssociationsInherited(e);if(!i&&!r){let s=`The "${e.info.getLabel()}" entity has no properties. It will be ignored.`;t.push({field:"properties",rule:"required",message:s,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:j})}return t}validateName(e){let t=[],i=e.info.getLabel();if(!e.info.name){let s=`The "${i}" entity has no name.`;return t.push({field:"name",rule:"required",message:s,help:"An entity must have a name.",severity:"error",key:e.key,kind:e.kind,parentKind:j}),t}let r=e.info.name;if(r.length<2){let s=`The "${i}" entity name is too short.`;t.push({field:"name",rule:"length",message:s,help:"The name must be at least 2 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:j})}if(r.length>31){let s=`The "${i}" entity name is too long.`;t.push({field:"name",rule:"length",message:s,help:"The name must be at most 31 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:j})}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)){let s=`The "${i}" entity name is invalid.`;t.push({field:"name",rule:"format",message:s,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:j})}if(/^[A-Z]/.test(r)){let s=`The "${i}" entity name is not in snake case.`;t.push({field:"name",rule:"snake_case",message:s,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:e.key,kind:e.kind,parentKind:j})}if(zs.has(r.toUpperCase())){let s=`The "${i}" entity name is a reserved keyword.`;t.push({field:"name",rule:"reserved",message:s,help:"The name should not be a reserved keyword.",severity:"error",key:e.key,kind:e.kind,parentKind:j})}return t}uniqueName(e){let t=[],i=e.info.name?.toLowerCase();if(!i)return t;for(let r of this.domain.listEntities())if(r.info.name?.toLowerCase()===i&&r.key!==e.key){let s=`The "${i}" entity name is already used in the data domain.`;t.push({field:"name",rule:"unique",message:s,help:"The name must be unique. This includes references to other data domains.",severity:"error",key:r.key,kind:r.kind,parentKind:j})}for(let r of this.domain.listEntities({foreignOnly:!0}))if(r.info.name?.toLowerCase()===i&&r.key!==e.key){let s=`The "${i}" entity name is already used in the foreign data domain.`;t.push({field:"name",rule:"unique",message:s,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:j})}return t}validateUserSemantics(e){let t=[],i=!1,r=!1;for(let s of e.withInheritedProperties())s.hasSemantic(y.Username)&&(i=!0),s.hasSemantic(y.Password)&&(r=!0);if((i||r)&&!e.hasSemantic(y.User)){let s=`The "${e.info.getLabel()}" entity has Username or Password properties but does not have the User taxonomy.`;t.push({field:"semantics",rule:"user_taxonomy_required",message:s,help:"Entities containing authentication credentials like usernames or passwords must be tagged with the User taxonomy.",severity:"error",key:e.key,kind:e.kind,parentKind:j})}if(r&&!i){let s=`The "${e.info.getLabel()}" entity has Password credentials but lacks Username semantics.`;t.push({field:"semantics",rule:"username_required_for_password",message:s,help:"An entity with Password credentials must also define a Username property for authentication.",severity:"error",key:e.key,kind:e.kind,parentKind:j})}return t}};function Et(n,e){let t=n;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 qs=class{domain;constructor(e){this.domain=e}validate(e){let t=[],i;if(typeof e=="string"?i=this.domain.findProperty(e):i=e,!i){let l=`The "${e}" property does not exist.`;return t.push({field:"*",rule:"exists",message:l,help:"The property must be defined in the domain.",key:e,kind:he,severity:"error",parentKind:j}),t}let r=this.validateName(i);t.push(...r);let s=this.validatePrimaryKeyDefault(i);t.push(...s);let a=this.validateJsonIndex(i);t.push(...a);let o=this.validateSchema(i);return t.push(...o),t}validateName(e){return Vs(e)}validatePrimaryKeyDefault(e){let t=[];if(e.primary){let i=e.getParentInstance();if(!i)return t;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.push({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.`;t.push({field:"schema.defaultValue",rule:"primary_key_no_default",message:s,help:'Without a default generator (e.g., the "random" function), the client application must generate and supply primary key values manually.',severity:"warning",key:e.key,kind:e.kind,parentKind:i.kind})}}return t}validateJsonIndex(e){let t=[],i=e.jsonIndex;if(!i)return t;let r=e.getParentInstance();if(!r)return t;if(e.type!=="json")return t.push({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}),t;if(i.paths&&e.jsonSchema)for(let s of i.paths){if(!s.path){t.push({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 a=s.path.split(".");Et(e.jsonSchema,a)||t.push({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})}return t}validateSchema(e){let t=[],i=e.schema;if(!i)return t;let r=e.getParentInstance();if(!r)return t;if(!["number","string","date","datetime","time"].includes(e.type)&&(i.minimum!==void 0||i.maximum!==void 0)){let o=i.minimum!==void 0?"schema.minimum":"schema.maximum",l=e.info.getLabel();return t.push({field:o,rule:"schema_boundary_unsupported_type",message:`The property "${l}" 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}),t}let a=!1;if(i.minimum!==void 0){let o=this.validateBoundaryValue(e,"minimum",i.minimum,r.kind);o&&(a=!0,t.push(o))}if(i.maximum!==void 0){let o=this.validateBoundaryValue(e,"maximum",i.maximum,r.kind);o&&(a=!0,t.push(o))}if(!a&&i.minimum!==void 0&&i.maximum!==void 0){let o=this.validateBoundaryRange(e,r.kind);o&&t.push(o)}return t}validateBoundaryRange(e,t){let{schema:i,type:r}=e;if(!i||i.minimum===void 0||i.maximum===void 0)return;let{minimum:s,maximum:a,exclusiveMinimum:o,exclusiveMaximum:l}=i,c=e.info.getLabel();if(r==="number"||r==="string"){if(typeof s!="number"||typeof a!="number")return;if(s>a)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum value (${s}) 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};if(s===a&&(o||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} 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(r==="date"){if(typeof s!="string"||typeof a!="string"||!this.isValidIsoDate(s)||!this.isValidIsoDate(a))return;if(s>a)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum date (${s}) 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};if(s===a&&(o||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} 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(r==="datetime"){if(typeof s!="string"||typeof a!="string"||!this.isValidIsoDateTime(s)||!this.isValidIsoDateTime(a))return;let p=Date.parse(s),u=Date.parse(a);if(p>u)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum datetime (${s}) 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};if(p===u&&(o||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} 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(r==="time"){if(typeof s!="string"||typeof a!="string"||!this.isValidIsoTime(s)||!this.isValidIsoTime(a))return;let p=this.isoTimeToSeconds(s),u=this.isoTimeToSeconds(a);if(p>u)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum time (${s}) 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};if(p===u&&(o||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} 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){let{type:s}=e,a=e.info.getLabel(),o=t==="minimum"?"schema_minimum_type":"schema_maximum_type",l=`schema.${t}`;if(s==="number"){if(typeof i!="number")return{field:l,rule:o,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}}else if(s==="string"){if(typeof i!="number"||!Number.isInteger(i)||i<0)return{field:l,rule:o,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}}else if(s==="date"){if(!this.isValidIsoDate(i))return{field:l,rule:o,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}}else if(s==="datetime"){if(!this.isValidIsoDateTime(i))return{field:l,rule:o,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}}else if(s==="time"&&!this.isValidIsoTime(i))return{field:l,rule:o,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}}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,a=i*3600+r*60+s;if(t[4]!==void 0&&t[5]!==void 0){let o=e.includes("+")?1:-1,l=(Number(t[4])*3600+Number(t[5])*60)*o;a-=l}return a}};var Js=class{domain;constructor(e){this.domain=e}validate(){let e=[],t=this.validateUserEntity();e.push(...t);let i=this.validateTimestampSemantics();e.push(...i);let r=this.validateSoftDeleteSemantics();e.push(...r);let s=this.validatePropertySemanticsDataTypes();e.push(...s);let a=this.validateCurrencySemantics();e.push(...a);let o=this.validateGeospatialEndpoints();e.push(...o);let l=this.validateOrganizationSemantics();e.push(...l);let c=this.validateProjectSemantics();e.push(...c);let p=this.validateAssociationSemanticsPreconditions();return e.push(...p),e}validateUserEntity(){let e=[],t=0;for(let i of this.domain.listEntities())if(i.hasSemantic(y.User)){t++;let r=!1,s=!1,a=!1;for(let o of i.withInheritedProperties())if(o.hasSemantic(y.Username)&&(r=!0),o.hasSemantic(y.Password)&&(s=!0),o.hasSemantic(y.UserRole)&&(a=!0),r&&s&&a)break;r||e.push({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:j,parentKind:j}),s||e.push({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:j,parentKind:j}),a||e.push({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:j,parentKind:j})}return t===0?e.push({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:j,parentKind:j}):t>1&&e.push({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:j,parentKind:j}),e}validateTimestampSemantics(){let e=[];for(let t of this.domain.listEntities()){let i=!1,r=!1;for(let s of t.withInheritedProperties())s.hasSemantic(y.CreatedTimestamp)&&(i=!0),s.hasSemantic(y.UpdatedTimestamp)&&(r=!0);i||e.push({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:j}),r||e.push({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:j})}return e}validateSoftDeleteSemantics(){let e=[];for(let t of this.domain.listEntities()){let i=!1;for(let r of t.withInheritedProperties())if(r.hasSemantic(y.DeletedTimestamp)||r.hasSemantic(y.DeletedFlag)){i=!0;break}i||e.push({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:j})}return e}validatePropertySemanticsDataTypes(){let e=[];for(let t of this.domain.listEntities())for(let i of t.withInheritedProperties())for(let r of i.semantics){let s=dt[r.id];ls(s)&&s.applicableDataTypes&&(s.applicableDataTypes.includes(i.type)||e.push({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:j}))}return e}validateCurrencySemantics(){let e=[];for(let t of this.domain.listEntities())for(let i of t.withInheritedProperties()){let r=i.getSemantic(y.Currency);if(r){let s=r.config;i.type==="number"&&s?.allowedCurrencies&&s.allowedCurrencies.length>1&&e.push({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:t.key,parentKind:j})}}return e}validateGeospatialEndpoints(){let e=[];for(let t of this.domain.listEntities()){let i=new Map;for(let r of t.withInheritedProperties()){let s=r.getSemantic(y.GeospatialCoordinates);if(s){let a=s.config??{},o=!!a.enableDistanceQueries,l=!!a.enableBoundingBoxQueries,c=!!a.enablePolygonQueries,p=!!a.enableGeoClustering;if(o||l||c||p){let u=(a.apiEndpointPrefix||"/nearby").trim().toLowerCase();i.has(u)||i.set(u,[]),i.get(u)?.push(r.info.getLabel())}}}for(let[r,s]of i.entries())s.length>1&&e.push({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:j})}return e}validateOrganizationSemantics(){let e=[],t=Array.from(this.domain.listEntities()).filter(c=>c.hasSemantic(y.Organization));if(t.length===0)return e;t.length>1&&e.push({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:j,parentKind:j});let i=t[0],r=Array.from(this.domain.listEntities()).find(c=>c.hasSemantic(y.User));if(!r)return e.push({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:j,parentKind:j}),e;let s=Array.from(i.withInheritedAssociations()).find(c=>c.hasSemantic(y.OrganizationMembers)),a=Array.from(r.withInheritedAssociations()).find(c=>c.hasSemantic(y.OrganizationMembers));!s&&!a&&e.push({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:j,parentKind:j}),s&&(s.targets.length===1&&s.targets[0].key===r.key||e.push({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:j})),a&&(a.targets.length===1&&a.targets[0].key===i.key||e.push({field:"semantics",rule:"organization_members_user_target_mismatch",message:`The association "${a.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:a.key,kind:a.kind,parent:r.key,parentKind:j}));let o=[s,a].filter(Boolean);o.length>0&&e.push(...this.validateBiDirectionalSemanticLinks(y.OrganizationMembers,"organization_members",o));let l=o.find(c=>!c.getSemantic(y.OrganizationMembers)?.link);if(l){e.push(...this.validateAssociationPropertyCollisions("organization_members",l));let c=l.getParentInstance(),p=Array.from(l.listProperties()).filter(u=>u.hasSemantic(y.OrganizationRole)||u.hasSemantic(y.AssociationRole));if(p.length===0)e.push({field:"semantics",rule:"organization_role_missing",message:`Association "${l.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${c?.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:l.key,kind:l.kind,parent:c?.key,parentKind:j});else if(p.length>1)e.push({field:"semantics",rule:"organization_role_multiple",message:`Association "${l.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${c?.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:l.key,kind:l.kind,parent:c?.key,parentKind:j});else{let u=p[0],m=u.schema?.enum;(!m||!Array.isArray(m)||m.length===0)&&e.push({field:"semantics",rule:"organization_role_enum_missing",message:`The organization role property "${u.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 OrganizationRole property to set valid roles.",severity:"warning",key:u.key,kind:u.kind,parent:l.key,parentKind:de})}}return e}validateProjectSemantics(){let e=[],t=Array.from(this.domain.listEntities()).filter(s=>s.hasSemantic(y.Project));if(t.length===0)return e;t.length>1&&e.push({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:j,parentKind:j});let i=Array.from(this.domain.listEntities()).find(s=>s.hasSemantic(y.User)),r=i?Array.from(i.withInheritedAssociations()).filter(s=>s.hasSemantic(y.ProjectMembers)):[];for(let s of r)s.targets.length===1&&t.some(o=>o.key===s.targets[0].key)||e.push({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:j});for(let s of t){let a=Array.from(s.withInheritedAssociations()).find(p=>p.hasSemantic(y.ProjectMembers)),o=r.find(p=>p.targets.some(u=>u.key===s.key));a&&(i&&a.targets.length===1&&a.targets[0].key===i?.key||e.push({field:"semantics",rule:"project_members_target_mismatch",message:`The association "${a.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:a.key,kind:a.kind,parent:s.key,parentKind:j}));let l=[a,o].filter(Boolean),c=l.find(p=>!p.getSemantic(y.ProjectMembers)?.link);if(c){e.push(...this.validateAssociationPropertyCollisions("project_members",c));let p=c.getParentInstance(),u=Array.from(c.listProperties()).filter(m=>m.hasSemantic(y.ProjectRole)||m.hasSemantic(y.AssociationRole));if(u.length===0)e.push({field:"semantics",rule:"project_role_missing",message:`Association "${c.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${p?.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:c.key,kind:c.kind,parent:p?.key,parentKind:j});else if(u.length>1)e.push({field:"semantics",rule:"project_role_multiple",message:`Association "${c.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${p?.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:c.key,kind:c.kind,parent:p?.key,parentKind:j});else{let m=u[0],h=m.schema?.enum;(!h||!Array.isArray(h)||h.length===0)&&e.push({field:"semantics",rule:"project_role_enum_missing",message:`The project role property "${m.info.getLabel()}" on association "${c.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:c.key,parentKind:de})}}l.length>0&&e.push(...this.validateBiDirectionalSemanticLinks(y.ProjectMembers,"project_members",l))}return e}validateAssociationPropertyCollisions(e,t){let i=[],r=t.getParentInstance();if(!r)return i;let s=Array.from(t.listTargets()),a=[r,...s];for(let o of t.listProperties()){let l=o.info.name;for(let c of a)Array.from(c.withInheritedProperties()).find(u=>u.info.name===l)&&i.push({field:"properties",rule:`${e}_property_collision`,message:`Property "${l}" on association "${t.info.getLabel()}" collides with a property of the same name on entity "${c.info.getLabel()}".`,help:`Rename the property "${l}" on the association to avoid conflicts when joining tables in the API (e.g., use a prefix like "${e.split("_")[0]}_${l}").`,severity:"error",key:o.key,kind:o.kind,parent:t.key,parentKind:de})}return i}validateBiDirectionalSemanticLinks(e,t,i){let r=[],s=[],a=[];for(let o of i){let l=o.getSemantic(e);if(l)if(l.link){a.push(o),l.config&&Object.keys(l.config).length>0&&r.push({field:"semantics",rule:"semantic_link_config_forbidden",message:`The association "${o.info.getLabel()}" has a semantic link set for "${e}", 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:j});let c=this.domain.findAssociation(l.link.key,l.link.domain);if(!c)r.push({field:"semantics",rule:"semantic_link_target_not_found",message:`The association "${o.info.getLabel()}" has a semantic link targeting "${l.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:j});else{let p=c.getSemantic(e);p?p.link&&r.push({field:"semantics",rule:"semantic_link_target_is_link",message:`The association "${o.info.getLabel()}" links to "${c.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:j}):r.push({field:"semantics",rule:"semantic_link_target_invalid",message:`The association "${o.info.getLabel()}" links to "${c.info.getLabel()}", but the target association does not have the "${e}" semantic.`,help:`Ensure the target association has the "${e}" semantic applied.`,severity:"error",key:o.key,kind:o.kind,parent:o.getParentInstance()?.key,parentKind:j})}}else s.push(o)}if(i.length>1){if(s.length===0)r.push({field:"semantics",rule:"semantic_link_primary_missing",message:`All associations with the "${e}" 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:a[0].key,kind:a[0].kind,parent:a[0].getParentInstance()?.key,parentKind:j});else if(s.length>1)for(let o=1;o<s.length;o++){let l=s[o];r.push({field:"semantics",rule:`${t}_link_required`,message:`Multiple associations have the "${e}" semantic, but "${l.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:l.key,kind:l.kind,parent:l.getParentInstance()?.key,parentKind:j})}}return r}validateAssociationSemanticsPreconditions(){let e=[];for(let t of this.domain.listEntities())for(let i of t.listAssociations())for(let r of i.semantics)try{i.checkPreconditions(r.id)}catch(s){let a=s instanceof Error?s.message:String(s);e.push({field:"semantics",rule:"association_semantic_precondition_unmet",message:a,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:j})}return e}};var Li=class{domain;report=[];#e=0;#t=0;#i=0;#r=!1;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.domain=e}validate(){this.#r=!1,this.report=[];let e=new Ks(this.domain),t=new qs(this.domain),i=new Fs(this.domain),r=new Js(this.domain),s=!1;for(let o of this.domain.listEntities()){if(o.domain.key!==this.domain.key)continue;s=!0;let l=e.validate(o);this.report.push(...l);for(let c of o.properties){if(c.domain.key!==this.domain.key)continue;let p=t.validate(c);this.report.push(...p)}for(let c of o.associations){if(c.domain.key!==this.domain.key)continue;let p=i.validate(c);this.report.push(...p)}}if(!s)return this.report;let a=r.validate();return this.report.push(...a),this.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 _o=[],Ao=[],nl={},ur={},mr={};function ll(n){return typeof n=="string"?new RegExp("^"+n+"$","i"):n}function Bs(n,e){return n===e?e:n===n.toLowerCase()?e.toLowerCase():n===n.toUpperCase()?e.toUpperCase():n[0]===n[0].toUpperCase()?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():e.toLowerCase()}function mp(n,e){return n.replace(/\$(\d{1,2})/g,function(t,i){return e[i]||""})}function hp(n,e){return n.replace(e[0],function(t,i){let r=mp(e[1],arguments);return Bs(t===""?n[i-1]:t,r)})}function cl(n,e,t){if(!n.length||Object.hasOwn(nl,n))return e;let i=t.length;for(;i--;){let r=t[i];if(r[0].test(e))return hp(e,r)}return e}function dl(n,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?Bs(i,r):Object.prototype.hasOwnProperty.call(n,r)?Bs(i,n[r]):cl(r,i,t)}}function pl(n,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?!0:Object.prototype.hasOwnProperty.call(n,r)?!1:cl(r,r,t)===r}}var Te=function(n,e,t){let i=e===1?Te.singular(n):Te.plural(n);return(t?e+" ":"")+i};Te.plural=dl(mr,ur,_o);Te.isPlural=pl(mr,ur,_o);Te.singular=dl(ur,mr,Ao);Te.isSingular=pl(ur,mr,Ao);Te.addPluralRule=function(n,e){_o.push([ll(n),e])};Te.addSingularRule=function(n,e){Ao.push([ll(n),e])};Te.addUncountableRule=function(n){if(typeof n=="string"){nl[n.toLowerCase()]=!0;return}Te.addPluralRule(n,"$0"),Te.addSingularRule(n,"$0")};Te.addIrregularRule=function(n,e){e=e.toLowerCase(),n=n.toLowerCase(),mr[n]=e,ur[e]=n};[["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(n){Te.addIrregularRule(n[0],n[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(n){Te.addPluralRule(n[0],n[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(n){Te.addSingularRule(n[0],n[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(Te.addUncountableRule);var Gs=Te;function xt(n,e){let t=n.domain||e;return t?`${t}:${n.key}`:n.key}function hr(n){if(!n)throw new g("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=n.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 g(`Cannot generate a valid parameter name from "${n}".`,{code:"E_INVALID_PARAM_NAME",help:"The entity name must contain alphanumeric characters to generate a path parameter."});let s=i.map((a,o)=>{let l=a.toLowerCase();return o===0?l:l.charAt(0).toUpperCase()+l.slice(1)}).join("");return/^[0-9]/.test(s)&&(s="_"+s),`${s}Id`}function si(n){let e=n.trim(),t=e.startsWith("/")?e:`/${e}`;return t==="/"?"/":t.replace(/\/+$/,"")}function Eo(n,e){let t=n.endsWith("/")?n.slice(0,-1):n,i=e.startsWith("/")?e:`/${e}`;return`${t}${i}`}var _;(function(n){n.PRE_FETCH="pre-fetch",n.FETCH="fetch",n.POST_FETCH="post-fetch"})(_||(_={}));var ge=class{type;parent;isIdentityConstraining=!1;isBroadIdentityRule=!1;#e;get metadata(){if(!this.#e)throw new Error("Metadata not set for access rule "+this.type);return this.#e}constructor(e,t,i={}){this.parent=e,this.type=i.type??"",this.#e={...t,...i.metadata}}toJSON(){let e={type:this.type};return this.#e&&(e.metadata=this.#e),e}};var fr=class n{description;key;rate;interval;burst;constructor(e={}){this.description=e.description,this.key=n.isRateLimitRuleKey(e.key)?structuredClone(e.key):void 0,this.rate=typeof e.rate=="number"?e.rate:void 0,this.interval=n.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),n.isRateLimitRuleKey(this.key)&&(e.key=structuredClone(this.key)),typeof this.rate=="number"&&(e.rate=this.rate),n.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 Tt=class{rules;constructor(e={}){this.rules=e.rules?.map(t=>new fr(t))||[]}toJSON(){return{rules:this.rules.map(e=>e.toJSON())}}};var Hs=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,{list:_.PRE_FETCH,create:_.PRE_FETCH,search:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.PRE_FETCH},t),this.type="allowAuthenticated"}};var Ws=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,{list:_.PRE_FETCH,create:_.PRE_FETCH,search:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.PRE_FETCH},t),this.type="allowPublic"}};var Xs=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;domains;requireVerified;constructor(e,t={}){super(e,{list:_.PRE_FETCH,create:_.PRE_FETCH,search:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.PRE_FETCH},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 Ys=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;target;constructor(e,t={}){super(e,{list:_.FETCH,search:_.FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.FETCH},t),this.type="matchResourceOwner",this.association=t.association?{...t.association}:void 0;let i="association";t.target==="user-entity"?i="user-entity":t.target==="association"&&(i="association"),this.target=i}toJSON(){let e={...super.toJSON(),target:this.target};return this.association&&(e.association={...this.association}),e}};var Zs=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;parameters;constructor(e,t={}){super(e,{list:_.PRE_FETCH,search:_.PRE_FETCH,create:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.PRE_FETCH},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 gi=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;attribute;operator;value;values;constructor(e,t={}){super(e,{list:_.FETCH,search:_.FETCH,read:_.POST_FETCH,update:_.POST_FETCH,delete:_.POST_FETCH,link:_.POST_FETCH,unlink:_.POST_FETCH,restore:_.FETCH},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"?n.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?n.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isScalarOperator(e.operator):!1}static assertArray(e){if(!n.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!n.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return n.isArrayOperator(this.operator)}get isScalar(){return n.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 Qs=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;allowedStatuses;deniedStatuses;constructor(e,t={}){super(e,{list:_.FETCH,search:_.FETCH,read:_.POST_FETCH,update:_.POST_FETCH,delete:_.POST_FETCH,link:_.POST_FETCH,unlink:_.POST_FETCH,restore:_.FETCH},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 yi=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;property;operator;value;values;constructor(e,t={}){super(e,{list:_.PRE_FETCH,create:_.PRE_FETCH,search:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.PRE_FETCH},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"?n.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?n.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isScalarOperator(e.operator):!1}static assertArray(e){if(!n.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!n.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return n.isArrayOperator(this.operator)}get isScalar(){return n.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 ea=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;mode;allowed;denied;minimumRole;maximumRole;roleMatch;constructor(e,t={}){super(e,{list:_.PRE_FETCH,create:_.PRE_FETCH,search:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.PRE_FETCH},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 bi=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;isIdentityConstraining=!0;isBroadIdentityRule=!1;roles;constructor(e,t={}){super(e,{list:_.FETCH,search:_.FETCH,create:_.PRE_FETCH,read:_.POST_FETCH,update:_.POST_FETCH,delete:_.POST_FETCH,link:_.POST_FETCH,unlink:_.POST_FETCH,restore:_.FETCH},t),this.roles=Array.isArray(t.roles)?[...t.roles]:typeof t.roles=="string"?[t.roles]:[]}toJSON(){return{...super.toJSON(),roles:[...this.roles]}}};var ta=class n extends bi{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchOrganizationRole"}};var ia=class n extends bi{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchProjectRole"}};var ra=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;allowedRoles;constructor(e,t={}){super(e,{list:_.FETCH,search:_.FETCH,create:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.FETCH},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 sa=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,{list:_.FETCH,search:_.FETCH,create:_.PRE_FETCH,read:_.PRE_FETCH,update:_.PRE_FETCH,delete:_.PRE_FETCH,link:_.PRE_FETCH,unlink:_.PRE_FETCH,restore:_.FETCH},t),this.type="relationalResourceOwner"}toJSON(){return{...super.toJSON()}}};function ul(n,e){switch(e.type){case"allowAuthenticated":return new Hs(n,e);case"allowPublic":return new Ws(n,e);case"matchEmailDomain":return new Xs(n,e);case"matchResourceOwner":return new Ys(n,e);case"relationalResourceOwner":return new sa(n,e);case"matchPathParameter":return new Zs(n,e);case"matchResourceAttribute":return new gi(n,e);case"lifecycleStatus":return new Qs(n,e);case"matchUserProperty":return new yi(n,e);case"matchUserRole":return new ea(n,e);case"matchOrganizationRole":return new ta(n,e);case"matchProjectRole":return new ia(n,e);case"matchAssociation":return new ra(n,e);default:throw new g("Unknown access rule kind",{code:"E_UNKNOWN_ACCESS_RULE_KIND",status:422})}}var Dt=class{key;label;rules;parent;constructor(e,t={}){this.parent=e,this.key=t.key||Q(),t.label!==void 0&&(this.label=t.label),this.rules=Array.isArray(t.rules)?t.rules.map(i=>ul(this.parent,i)):[]}toJSON(){let e={key:this.key,rules:this.rules.map(t=>t.toJSON())};return this.label!==void 0&&this.label!==""&&(e.label=this.label),e}};var Pe=class{kind;accessScenarios;overrideParentScenarios;rateLimiting;projection;parent;constructor(e,t={}){this.parent=e,this.kind=t.kind||"",this.overrideParentScenarios=t.overrideParentScenarios??!1,this.accessScenarios=t.accessScenarios?t.accessScenarios.map(i=>new Dt(this,i)):[],this.rateLimiting=t.rateLimiting?new Tt(t.rateLimiting):void 0,t.projection&&(this.projection=structuredClone(t.projection))}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 gr=class extends Pe{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 ai=class extends Pe{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 Mt=class extends Pe{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 ki=class extends Pe{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 Lt=class extends Pe{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 vi=class extends Pe{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 yr=class extends Pe{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 br=class extends Pe{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 wi=class extends Pe{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 xo(n,e){switch(e.kind){case"list":return new Mt(n,e);case"read":return new ki(n,e);case"create":return new gr(n,e);case"update":return new vi(n,e);case"delete":return new ai(n,e);case"search":return new Lt(n,e);case"link":return new yr(n,e);case"unlink":return new br(n,e);case"restore":return new wi(n,e);default:throw new g("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}function ml(n,e){switch(e){case"list":return new Mt(n);case"read":return new ki(n);case"create":return new gr(n);case"update":return new vi(n);case"delete":return new ai(n);case"search":return new Lt(n);case"link":return new yr(n);case"unlink":return new br(n);case"restore":return new wi(n);default:throw new g("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}var kr=class n{kind;key;entity;hasCollection;collectionPath;resourcePath;isRoot;parent;actions;accessScenarios;rateLimiting;paginationContract;truncated;api;static createSchema(e={}){let{key:t=Q(),entity:i={key:""},collectionPath:r,resourcePath:s="/",hasCollection:a=!0,isRoot:o,parent:l,actions:c=[],accessScenarios:p,rateLimiting:u,truncated:m,paginationContract:h}=e,f={kind:ni,key:t,entity:{...i},hasCollection:a,resourcePath:s,actions:c.map(v=>({...v}))};return r!==void 0&&(f.collectionPath=r),o!==void 0&&(f.isRoot=o),l!==void 0&&(f.parent={key:l.key,association:{...l.association}}),Array.isArray(p)&&(f.accessScenarios=p.map(v=>({...v}))),u!==void 0&&(f.rateLimiting={...u}),m!==void 0&&(f.truncated=m),h!==void 0&&(f.paginationContract=structuredClone(h)),f}constructor(e,t){this.api=e;let i=n.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=>xo(this,r)):[],this.accessScenarios=i.accessScenarios?i.accessScenarios.map(r=>new Dt(this,r)):[],i.rateLimiting&&(this.rateLimiting=new Tt(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,association:{...this.parent.association}}),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 g("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=si(e).split("/").filter(Boolean);if(i.length!==1)throw new g(`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 g(`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 l=this.resourcePath.split("/").filter(Boolean)[1];l&&/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(l)&&(s=l)}if(!s){let o=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!o||!o.info.name)throw new g("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=`{${hr(o.info.name)}}`}let a=`${r}/${s}`;this.#i(a),this.collectionPath=r,this.resourcePath=a}setResourcePath(e){let t=si(e),i=t.split("/").filter(Boolean);if(this.hasCollection){if(!this.collectionPath)throw new g("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 g(`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 g(`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,a]=i;if(s!==r[0])throw new g(`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(a))throw new g(`The second segment must be a parameter in braces, e.g. {id}. Received: "${a}"`,{code:"E_PARAMETER_INVALID",help:"Use the braces to surround the parameter name, e.g., {productId}."});this.resourcePath!==t&&(this.#i(`/${s}/${a}`),this.resourcePath=`/${s}/${a}`);return}if(i.length!==1)throw new g(`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 g(`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 g(`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=si(this.resourcePath),t=this.parent?.key;for(;t;){let i=this.api.exposes.get(t);if(!i)break;let r=si(i.resourcePath);e=Eo(r,e),t=i.parent?.key}return e}getAbsoluteCollectionPath(){if(!this.hasCollection||!this.collectionPath)return;let e=si(this.collectionPath),t=this.parent?.key;for(;t;){let i=this.api.exposes.get(t);if(!i)break;let r=si(i.resourcePath);e=Eo(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 g(`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."});let t=xo(this,e);return this.actions.push(t),t}addActionFromKind(e){if(this.actions.some(i=>i.kind===e))throw new g(`Action of kind "${e}" already exists for this exposure`,{code:"E_ACTION_USED",help:"There's no need to add an API action again."});let t=ml(this,e);return this.actions.push(t),t}createPaginationContract(){let e=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!e)throw new g(`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=si(e);return i.find(s=>{if(s.key===e||s.entity.key===e)return!0;let a=this.api.domain?.findEntity(s.entity.key,s.entity.domain);if(a&&a.info.name===e)return!0;if(s.hasCollection&&s.collectionPath){if(s.collectionPath===e||s.collectionPath===r)return!0;let l=s.getAbsoluteCollectionPath();if(l&&(l===e||l===r))return!0}if(s.resourcePath===e||s.resourcePath===r)return!0;let o=s.getAbsoluteResourcePath();return!!(o&&(o===e||o===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 g("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 g(`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 g(`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 a=i.findEntity(e.key,e.domain);if(!a)throw new g(`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 o=i.findAssociation(t.key,t.domain);if(!o)throw new g(`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 l=s.key,c=a.key,p=o.getParentInstance()?.key,u=p===l||s.listAllParents("up").some(V=>V.key===p),m=o.targets.some(V=>V.key===c||a.listAllParents("up").some(O=>O.key===V.key));if(!u||!m)throw new g(`Association "${t.key}" does not connect parent "${s.info.getLabel()||l}" to "${a.info.getLabel()||c}".`,{code:"E_ASSOCIATION_NOT_FOUND",help:"Ensure there is a defined association in the data domain connecting these entities."});let h=xt(e,i.key),f=xt(t,i.key);for(let V of this.api.exposes.values())if(V.parent?.key===r.key&&xt(V.entity,i.key)===h&&xt(V.parent.association,i.key)===f)throw new g(`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 v=o.getExposedName(),w=!!o.multiple,E=w?Gs(v.toLocaleLowerCase()):v.toLocaleLowerCase(),I=hr(a.info.name||""),R=w?`/${E}`:void 0,C=w?`/${E}/{${I}}`:`/${E}`;if(w&&R){let V=new Set;for(let P of this.api.exposes.values())P.parent?.key===r.key&&P.hasCollection&&P.collectionPath&&V.add(P.collectionPath);let O=1,k=R;for(;V.has(R);)R=`${k}-${O}`,C=`${R}/{${I}}`,O++}let N=o.namespace&&this.api.domain?.key&&o.namespace!==this.api.domain.key,T={kind:ni,key:Q(),entity:{...e},actions:[],isRoot:!1,collectionPath:R,resourcePath:"",hasCollection:w,parent:{key:r.key,association:{key:o.key,...N?{domain:o.namespace}:{}}}},L=new n(this.api,T);return L.setResourcePath(C),this.api.exposes.set(L.key,L),this.api.notifyChange(),L}};var vr=(n={})=>{let e={...aa,...n};return n.metadata&&(e.metadata={...n.metadata}),{id:y.Currency,config:e}},aa={storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1,validateCurrencyCode:!0},LO={USD_DECIMAL:vr({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),USD_CENTS:vr({storageFormat:"integer_cents",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),MULTI_CURRENCY:vr({storageFormat:"complex_object",allowedCurrencies:["USD","EUR","GBP","JPY","CAD"],decimalPlaces:2,allowNegative:!1}),WITH_NEGATIVES:vr({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!0}),HIGH_PRECISION:vr({storageFormat:"decimal",defaultCurrency:"BTC",decimalPlaces:8,allowNegative:!1})};var oa={requireVerification:!0,allowSubaddressing:!0,allowInternational:!0};var hl={requireCountryCode:!0,format:"international",allowExtension:!1,requireVerification:!1,verificationMethod:"sms"};var Po=["allowAuthenticated","allowPublic","matchEmailDomain","matchResourceOwner","relationalResourceOwner","matchPathParameter","matchResourceAttribute","lifecycleStatus","matchUserProperty","matchAssociation","matchProjectRole"],fp={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"],matchResourceOwner:["exposure","action"],relationalResourceOwner:["exposure","action"],matchResourceAttribute:["exposure","action"],matchAssociation:["exposure","action"],matchPathParameter:["exposure","action"],lifecycleStatus:["exposure","action"]};function fl(n,e){let t;switch(n){case"RBAC":t=[...Po,"matchUserRole"];break;case"OrganizationRBAC":t=[...Po,"matchOrganizationRole"];break;case"EnterpriseRBAC":t=[...Po,"matchUserRole","matchOrganizationRole"];break;default:t=[];break}return e?t.filter(i=>fp[i]?.includes(e)):t}function Pt(n,e){if(e){let t=n.findEntity(e.key,e.domain);return t&&t.hasSemantic(y.User)?t:void 0}for(let t of n.listEntities({includeForeign:!0}))if(t.hasSemantic(y.User))return t}function Ut(n,e){let t=e||Pt(n),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(y.UserRole)?(i.roleProperty=r,i.hasRole=!0):r.hasSemantic(y.Username)?(i.usernameProperty=r,i.hasUsername=!0):r.hasSemantic(y.Password)&&(i.passwordProperty=r,i.hasPassword=!0);return i}function Ui(n){let e,t;for(let o of n.listEntities())if(!e&&o.hasSemantic(y.Organization)&&(e=o),!t&&o.hasSemantic(y.User)&&(t=o),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=na(i,y.OrganizationMembers,y.OrganizationRole),a=s;return!a&&e&&(a=Array.from(e.withInheritedProperties()).find(o=>o.hasSemantic(y.OrganizationRole))),!a&&t&&(a=Array.from(t.withInheritedProperties()).find(o=>o.hasSemantic(y.OrganizationRole))),{hasOrganization:!!e,hasMembersAssociation:!!r,hasOrganizationRole:!!a,orgEntity:e,membersAssoc:r,roleProperty:a}}function Oo(n){let e,t;for(let o of n.listEntities())if(!e&&o.hasSemantic(y.Project)&&(e=o),!t&&o.hasSemantic(y.User)&&(t=o),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=na(i,y.ProjectMembers,y.ProjectRole),a=s;return!a&&e&&(a=Array.from(e.withInheritedProperties()).find(o=>o.hasSemantic(y.ProjectRole))),!a&&t&&(a=Array.from(t.withInheritedProperties()).find(o=>o.hasSemantic(y.ProjectRole))),{hasProject:!!e,hasMembersAssociation:!!r,hasProjectRole:!!a,projectEntity:e,membersAssoc:r,roleProperty:a}}function na(n,e,t){let i,r;for(let s of n){let a=[];for(let o of s.listAssociations())a.push(o);for(let o of s.listAllParents("up"))for(let l of o.listAssociations())a.some(c=>c.key===l.key)||a.push(l);for(let o of a)if(o.hasSemantic(e)){let l=o.getSemantic(e);if(!l?.link&&!i&&(i=o),!l?.link)for(let c of o.properties)!r&&c.hasSemantic(t)&&(r=c)}}return{membersAssoc:i,roleProperty:r}}function gp(n){let e=n.type,i=n.readWebBinding()?.format,r=n.multiple,s;if(e==="string"){let a=n.schema?.maximum,o=typeof a=="number"?a:void 0;if(n.schema?.defaultValue?.type==="function"&&n.schema.defaultValue.value==="random"){let l=n.schema.defaultValue.config;if(l){let c=0,p=!1;l.isFixed?l.length&&(c=l.length,p=!0):o&&(c=o,p=!0),p&&(l.prefix&&(c+=l.prefix.length),l.suffix&&(c+=l.suffix.length),(!o||c>o)&&(o=c))}}s=o?`VARCHAR(${o})`:"TEXT"}else if(e==="number"){let a=n.schema?.defaultValue?.type==="function"&&n.schema.defaultValue.value==="incremental";i==="int32"?s="INTEGER":i==="int64"?s="BIGINT":i==="float"||i==="double"?s="DOUBLE PRECISION":a?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 gl(n){let e=n.getExposedName();if(!e)throw new g("Property missing a name definition.",{code:"E_PROPERTY_NAME_MISSING",status:500});let t=null;if(n.schema?.defaultValue){let u=n.schema.defaultValue.type,m=String(n.schema.defaultValue.value);if(u==="function"){let h=n.type;if(h==="string"){if(m==="uuid-v4"&&n.primary)throw new g("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 g(`Function '${m}' is not supported for string properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else if(h==="number"){if(m!=="incremental")throw new g(`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 g(`Function '${m}' is not supported for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else throw new g(`Functions are not supported as default values for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}t={type:u,value:m}}let i=!!n.primary,r=!n.required&&!i,s=!!n.unique;!t&&n.hasSemantic(y.DeletedFlag)&&(t={type:"literal",value:"false"});let a=n.getSemantic(y.Currency);if(a){let u=a.config??{},m=u.storageFormat||aa.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=u.decimalPlaces??aa.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:u.defaultCurrency||"USD"}}]}}let o=[{name:e,dataType:gp(n),isNullable:r,isPrimary:i,isUnique:s,defaultRule:t}],l=!1,c=n.getSemantic(y.Email);c&&(l=!!(c.config??oa).requireVerification);let p=n.getSemantic(y.Phone);return p&&(l=(p.config??hl).requireVerification===!0),l&&o.push({name:`_${e}_verified`,dataType:"BOOLEAN",isNullable:!1,isPrimary:!1,isUnique:!1,defaultRule:{type:"literal",value:"false"}},{name:`_${e}_token`,dataType:"VARCHAR(255)",isNullable:!0,isPrimary:!1,isUnique:!1,defaultRule:null},{name:`_${e}_expires_at`,dataType:"TIMESTAMPTZ",isNullable:!0,isPrimary:!1,isUnique:!1,defaultRule:null}),o}function yp(n){let e=n.toUpperCase().split("(")[0];return e==="CHARACTER VARYING"&&(e="VARCHAR"),e==="CHARACTER"&&(e="CHAR"),e}function bp(n,e){let t=e.toUpperCase(),i=yp(n.dataType),r=t.split("(")[0];if(i===r){if(i==="VARCHAR"){let a=n.dataType.match(/\((\d+)\)/),o=a?Number.parseInt(a[1],10):null,l=t.match(/\((\d+)\)/),c=l?Number.parseInt(l[1],10):null;return!!(!c||o&&c>=o)}return!0}return{INTEGER:["BIGINT","NUMERIC","VARCHAR","TEXT"],BIGINT:["NUMERIC","VARCHAR","TEXT"],DATE:["TIMESTAMPTZ"],BOOLEAN:["VARCHAR","TEXT"]}[i]?.includes(r)||!1}function kp(n,e,t,i,r){if(!e.actions)return;let s=e.entity.key,a=t.get(s),o=i.findEntity(s);if(!a)return;let l=Array.from(a.withInheritedProperties()),c=new Set(l.map(m=>m.key)),p=Array.from(a.withInheritedAssociations()),u=new Set(p.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("."),v=f[0];if(u.has(v)){let w=p.find(E=>E.key===v);f.length>1&&(!w||w.schema?.embedded!==!0)&&r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:`Projected association '${h.key}' is invalid because association '${v}' is not embedded.`})}else{let w=!1,E=`Projected association '${h.key}' no longer exists on entity '${a.info.getLabel()}'.`;if(o){let I=Array.from(o.withInheritedAssociations()).find(R=>R.key===v);if(I){let R;try{R=I.getExposedName()}catch{}if(R){let C=p.find(N=>{try{return N.getExposedName()===R}catch{return!1}});C&&(f.length>1&&C.schema?.embedded!==!0?E=`Projected association '${h.key}' is invalid because remapped association '${C.key}' is not embedded.`:w=!0)}}}w||r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:E})}}else{let f=h.key.split("."),v=f[0];if(c.has(v)){let w=l.find(E=>E.key===v);f.length>1&&(!w||w.type!=="json"?r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid because root property '${v}' is not of type 'json'.`}):w.jsonSchema&&(Et(w.jsonSchema,f.slice(1))||r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid according to the JSON Schema of '${v}'.`})))}else{let w=!1;if(o){let E=Array.from(o.withInheritedProperties()).find(I=>I.key===v);if(E){let I;try{I=E.getExposedName()}catch{}if(I){let R=l.find(C=>{try{return C.getExposedName()===I}catch{return!1}});R&&(f.length===1||R.type==="json")&&(w=!0,f.length>1&&R.jsonSchema&&(Et(R.jsonSchema,f.slice(1))||(w=!1)))}}}w||r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' no longer exists on entity '${a.info.getLabel()}'.`})}}}function vp(n,e,t,i,r){if(!e.paginationContract)return;let s=e.paginationContract,a=e.entity.key,o=t.get(a);if(!o)return;let l=Array.from(o.withInheritedProperties()),c=new Set(l.map(m=>m.key)),p=i.findEntity(a),u=(m,h)=>{if(!(!m||!Array.isArray(m)))for(let f of m){let v=f.split("."),w=v[0];if(c.has(w)){let E=l.find(I=>I.key===w);v.length>1&&(!E||E.type!=="json"?r.paginationFieldsWithMismatches.push({exposureKey:n,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid because root property '${w}' is not of type 'json'.`}):E.jsonSchema&&(Et(E.jsonSchema,v.slice(1))||r.paginationFieldsWithMismatches.push({exposureKey:n,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid according to the JSON Schema of '${w}'.`})))}else{let E=!1;if(p){let I=Array.from(p.withInheritedProperties()).find(R=>R.key===w);if(I){let R;try{R=I.getExposedName()}catch{}if(R){let C=l.find(N=>{try{return N.getExposedName()===R}catch{return!1}});C&&(v.length===1||C.type==="json")&&(E=!0,v.length>1&&C.jsonSchema&&(Et(C.jsonSchema,v.slice(1))||(E=!1)))}}}E||r.paginationFieldsWithMismatches.push({exposureKey:n,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' no longer exists on entity '${o.info.getLabel()}'.`})}}};u(s.filterableFields,"filterable"),u(s.sortableFields,"sortable"),u(s.searchableFields,"searchable")}function yl(n,e){let t=n.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 O of t.listEntities())r.set(O.key,O);let s=new Map;for(let O of e.listEntities())s.set(O.key,O);let a=new Set;for(let[O,k]of n.exposes.entries()){let P=r.has(k.entity.key),U=s.get(k.entity.key);if(!U){let z=r.get(k.entity.key)?.info.getLabel()||k.entity.key;i.exposedEntitiesToRemove.push({key:O,entityKey:k.entity.key,name:k.entity.key,reason:`Entity ${z} no longer exists in the domain.`}),a.add(O);continue}if(P){let z=r.get(k.entity.key),B=new Map;for(let ae of z.withInheritedProperties())try{let ie=ae.getExposedName();ie&&B.set(ie,ae)}catch{}let Y=new Map;for(let ae of U.withInheritedProperties())try{let ie=ae.getExposedName();ie&&Y.set(ie,ae)}catch{}for(let[ae,ie]of B.entries()){let Ne=Y.get(ae);if(!Ne)continue;let ke=gl(ie),le=gl(Ne);for(let oe of ke){let be=le.find(ot=>ot.name===oe.name);if(!be)continue;if(oe.isPrimary&&!be.isPrimary){i.canProceed=!1;let ot=z.info.getLabel(),nt=`Cannot remove Primary Key constraint from column '${oe.name}' in entity '${ot}'.`;i.breakingChanges.push({type:"primary_key_removed",entityKey:z.key,propertyKey:ie.key,reason:nt})}if(!bp(oe,be.dataType)){i.canProceed=!1;let ot=z.info.getLabel(),nt=`Cannot safely cast column '${oe.name}' in entity '${ot}' from ${oe.dataType} to ${be.dataType}.`;i.breakingChanges.push({type:"type_change_unsafe",entityKey:z.key,propertyKey:ie.key,reason:nt})}let $e=oe.isNullable&&!be.isNullable,Ue=!!be.defaultRule;if($e&&!Ue){i.canProceed=!1;let ot=z.info.getLabel(),nt=`Cannot make column '${oe.name}' in entity '${ot}' required without providing a default value to backfill existing records.`;i.breakingChanges.push({type:"column_not_null_missing_default",entityKey:z.key,propertyKey:ie.key,reason:nt})}}}}}let o=!0;for(;o;){o=!1;for(let[O,k]of n.exposes.entries())if(!a.has(O)){if(k.isRoot===!1&&!k.parent){let P=r.get(k.entity.key)?.info.getLabel()||k.entity.key;i.subEndpointsToRemove.push({key:O,parentKey:"",associationKey:"",name:k.entity.key,reason:`Sub-endpoint for entity ${P} is missing a parent reference.`}),a.add(O),o=!0;continue}if(k.parent){let P=n.exposes.get(k.parent.key);if(!P){i.subEndpointsToRemove.push({key:O,parentKey:k.parent.key,associationKey:k.parent.association?.key??"unknown",name:k.entity.key,reason:`Parent exposure "${k.parent.key}" does not exist in the API model.`}),a.add(O),o=!0;continue}let U=r.get(P.entity.key),z=U?.info.getLabel()||P.entity.key;if(a.has(k.parent.key)){i.subEndpointsToRemove.push({key:O,parentKey:k.parent.key,associationKey:k.parent.association?.key??"unknown",name:k.entity.key,reason:`Parent exposure for entity ${z} is scheduled for removal.`}),a.add(O),o=!0;continue}let B=s.get(P.entity.key);if(!B){i.subEndpointsToRemove.push({key:O,parentKey:k.parent.key,associationKey:k.parent.association?.key??"unknown",name:k.entity.key,reason:`Parent entity ${z} is scheduled for removal.`}),a.add(O),o=!0;continue}if(!k.parent.association||!k.parent.association.key){let De=r.get(k.entity.key)?.info.getLabel()||k.entity.key;i.subEndpointsToRemove.push({key:O,parentKey:k.parent.key,associationKey:"unknown",name:k.entity.key,reason:`Sub-endpoint for entity ${De} does not define a parent association.`}),a.add(O),o=!0;continue}let Y=k.parent.association.key,ae=k.parent.association.domain,ie=e.findAssociation(Y,ae)??Array.from(B.withInheritedAssociations()).find(De=>De.key===Y),Ne=t.findAssociation(Y,ae)??(U?Array.from(U.withInheritedAssociations()).find(De=>De.key===Y):void 0),ke=ie?.info.getLabel()||Ne?.info.getLabel()||Y;if(!ie){i.subEndpointsToRemove.push({key:O,parentKey:k.parent.key,associationKey:Y,name:k.entity.key,reason:`Parent association ${ke} is missing in the new domain.`}),a.add(O),o=!0;continue}let le=s.get(k.entity.key),oe=B.key,be=k.entity.key,$e=ie.getParentInstance()?.key,Ue=$e===oe||B.listAllParents("up").some(De=>De.key===$e),ot=$e===be||le&&le.listAllParents("up").some(De=>De.key===$e),nt=ie.targets.some(De=>De.key===be||le&&le.listAllParents("up").some(Fi=>Fi.key===De.key)),Tl=ie.targets.some(De=>De.key===oe||B.listAllParents("up").some(Fi=>Fi.key===De.key));if(!(Ue&&nt||ot&&Tl)){let Fi=(r.get(k.entity.key)||le)?.info.getLabel()||k.entity.key;i.subEndpointsToRemove.push({key:O,parentKey:k.parent.key,associationKey:Y,name:k.entity.key,reason:`Target entity ${Fi} is no longer a valid target for the parent association ${ke}.`}),a.add(O),o=!0;continue}}}}let l,c;if(n.user&&(l=r.get(n.user.key),c=s.get(n.user.key),!c)){i.canProceed=!1;let k=`User entity '${l?.info.getLabel()||n.user.key}' no longer exists in the new domain version.`;i.breakingChanges.push({type:"user_entity_missing",entityKey:n.user.key,propertyKey:"",reason:k})}if(n.user&&c&&l){let O=Array.from(l.withInheritedProperties()),k=Array.from(c.withInheritedProperties());if(n.session?.properties)for(let P of n.session.properties){let U=O.find(Y=>Y.key===P.key);if(!U){i.sessionPropertiesToRemove.push(P.key);continue}let z;try{z=U.getExposedName()}catch{}if(!z){i.sessionPropertiesToRemove.push(P.key);continue}let B=k.find(Y=>{try{return Y.getExposedName()===z}catch{return!1}});B?B.key!==U.key&&i.userModelRemapping.push({oldPropertyKey:U.key,newPropertyKey:B.key,exposedName:z,reason:`Property ${U.info.getLabel(U.key)} has been renamed to ${B.info.getLabel(B.key)}.`}):i.sessionPropertiesToRemove.push(P.key)}}let p=Ut(e,c),u=Ui(e),m=Oo(e),h=p.roleProperty??(c?Array.from(c.withInheritedProperties()).find(O=>O.hasSemantic(y.UserRole)):void 0),f=u.roleProperty,v=m.roleProperty,w=h?.schema?.enum,E=f?.schema?.enum,I=v?.schema?.enum,R=(O,k)=>{if(O.type==="matchOrganizationRole"){let P=O;if(!f)i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:k,reason:"No organization role property configured in the new domain model."});else if(E&&Array.isArray(E)&&P.roles)for(let U of P.roles)E.includes(U)||i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:k,reason:`Organization role '${U}' is no longer a valid role in the new domain model.`})}else if(O.type==="matchProjectRole"){let P=O;if(!v)i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:k,reason:"No project role property configured in the new domain model."});else if(I&&Array.isArray(I)&&P.roles)for(let U of P.roles)I.includes(U)||i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:k,reason:`Project role '${U}' is no longer a valid role in the new domain model.`})}},C=(O,k)=>{if(O.type==="matchUserRole"){let P=O;if(!h){i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:k,reason:"No role field configured on the new user model."});return}if(!w||!Array.isArray(w))return;let U=P.mode;if(U==="allowlist")for(let z of P.allowed??[])w.includes(z)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:k,reason:`Role '${z}' in the allowed list is no longer a valid role in the new user model.`});else if(U==="denylist")for(let z of P.denied??[])w.includes(z)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:k,reason:`Role '${z}' in the denied list is no longer a valid role in the new user model.`});else U==="minRole"?P.minimumRole&&!w.includes(P.minimumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:k,reason:`minimumRole '${P.minimumRole}' is no longer a valid role in the new user model.`}):U==="maxRole"&&P.maximumRole&&!w.includes(P.maximumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:k,reason:`maximumRole '${P.maximumRole}' is no longer a valid role in the new user model.`})}},N=(O,k,P)=>{if(O.type==="matchResourceAttribute"){let U=O;if(!P)return;let z=s.get(P);if(!z)return;let B=Array.from(z.withInheritedProperties());if(!B.some(ae=>ae.key===U.attribute)){let ae=r.get(P),ie=U.attribute,Ne=!1;if(ae){let ke=Array.from(ae.withInheritedProperties()).find(le=>le.key===U.attribute);if(ke){ie=ke.info.getLabel(ke.key);let le;try{le=ke.getExposedName()}catch{}le&&B.find(be=>{try{return be.getExposedName()===le}catch{return!1}})&&(Ne=!0)}}if(!Ne){let ke=z.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceAttribute",location:k,reason:`Property attribute '${ie}' no longer exists on entity '${ke}'.`})}}}},T=(O,k,P)=>{if(O.type==="matchResourceOwner"){let U=O;if(U.target==="user-entity"){n.user&&!c&&i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:k,reason:"User entity is missing in the new domain."});return}if(!P)return;let z=s.get(P);if(!z)return;if(U.association&&U.association.key){let B=U.association.key,Y=U.association.domain,ae=e.findAssociation(B,Y),ie=Array.from(z.withInheritedAssociations());if(!(ae?ie.some(ke=>ke.key===ae.key):ie.some(ke=>ke.key===B))){let ke=r.get(P),le=B,oe=!1;if(ke){let $e=Array.from(ke.withInheritedAssociations()).find(Ue=>Ue.key===B);if($e){le=$e.info.getLabel($e.key);let Ue;try{Ue=$e.getExposedName()}catch{}Ue&&ie.find(nt=>{try{return nt.getExposedName()===Ue}catch{return!1}})&&(oe=!0)}}if(!oe){let be=z.info.getLabel();e.resolveOwnershipPath(P)!==null?i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:k,reason:`Direct ownership association '${le}' no longer exists on entity '${be}'. The resolved ownership path will be used instead.`}):i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:k,reason:`Ownership association '${le}' no longer exists on entity '${be}' and no transitively resolved ownership path is available.`})}}}else if(!(e.resolveOwnershipPath(P)!==null)){let Y=z.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:k,reason:`No ownership association specified and no transitively resolved ownership path exists for entity '${Y}'.`})}}},L=(O,k)=>{if(O.type==="matchUserProperty"){let P=O;if(n.user&&!c){i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:k,reason:"User entity is missing in the new domain."});return}c&&P.property&&(Array.from(c.withInheritedProperties()).some(B=>B.key===P.property)||i.userModelRemapping.some(Y=>Y.oldPropertyKey===P.property)||i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:k,reason:`User property '${P.property}' no longer exists on the User entity.`}))}},V=(O,k,P)=>{if(O.type==="matchAssociation"){let z=O.association;if(!z||!z.key){i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:k,reason:"No target association specified for match association access rule."});return}let B=z.key,Y=z.domain;if(!e.findAssociation(B,Y)){let ie=P?s.get(P):void 0,Ne=ie?Array.from(ie.withInheritedAssociations()):[];if(!Ne.some(le=>le.key===B)){let le=P?r.get(P):void 0,oe=!1;if(le){let $e=Array.from(le.withInheritedAssociations()).find(Ue=>Ue.key===B);if($e){let Ue;try{Ue=$e.getExposedName()}catch{}Ue&&Ne.find(nt=>{try{return nt.getExposedName()===Ue}catch{return!1}})&&(oe=!0)}}if(!oe){let be=ie?.info.getLabel()||le?.info.getLabel()||P||"Entity";i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:k,reason:`Target association '${B}' no longer exists in domain or on entity '${be}'.`})}}}}};if(n.accessScenarios)for(let O of n.accessScenarios)for(let k of O.rules)C(k,{type:"api",key:n.key}),R(k,{type:"api",key:n.key}),L(k,{type:"api",key:n.key});for(let[O,k]of n.exposes.entries())if(!a.has(O)){if(k.accessScenarios)for(let P of k.accessScenarios)for(let U of P.rules)C(U,{type:"exposure",key:O}),R(U,{type:"exposure",key:O}),N(U,{type:"exposure",key:O},k.entity.key),T(U,{type:"exposure",key:O},k.entity.key),L(U,{type:"exposure",key:O}),V(U,{type:"exposure",key:O},k.entity.key);if(k.actions){for(let P of k.actions)if(P.accessScenarios)for(let U of P.accessScenarios)for(let z of U.rules)C(z,{type:"action",key:`${O}:${P.kind}`}),R(z,{type:"action",key:`${O}:${P.kind}`}),N(z,{type:"action",key:`${O}:${P.kind}`},k.entity.key),T(z,{type:"action",key:`${O}:${P.kind}`},k.entity.key),L(z,{type:"action",key:`${O}:${P.kind}`}),V(z,{type:"action",key:`${O}:${P.kind}`},k.entity.key)}kp(O,k,s,t,i),vp(O,k,s,t,i)}return i}function bl(n,e,t){if(!t.canProceed)throw new g("Cannot apply domain update because it contains breaking changes. Details in the report.",{code:"E_CANNOT_PROCEED_WITH_UPGRADE",status:400});let i=n.domain;n.dependencies.clear(),n.dependencies.set(e.key,e),n.dependencyList=[{key:e.key,version:e.info.version}];let r=[...t.exposedEntitiesToRemove,...t.subEndpointsToRemove];for(let I of r)n.exposes.delete(I.key);if(n.user&&n.session){let I=new Set(t.sessionPropertiesToRemove),R=new Map;for(let C of t.userModelRemapping)R.set(C.oldPropertyKey,C.newPropertyKey);if(n.session.properties){let C=[];for(let N of n.session.properties){if(I.has(N.key))continue;let T=R.get(N.key);T?C.push({...N,key:T}):C.push(N)}n.session.properties=C}}let s=new Map;for(let I of e.listEntities())s.set(I.key,I);let a=n.user?s.get(n.user.key):void 0,o=Ut(e,a),l=Ui(e),c=Oo(e),p=o.roleProperty??(a?Array.from(a.withInheritedProperties()).find(I=>I.hasSemantic(y.UserRole)):void 0),u=l.roleProperty,m=c.roleProperty,h=p?.schema?.enum,f=u?.schema?.enum,v=m?.schema?.enum,w=(I,R,C,N,T)=>{if(I.type===R){let L=I;if(!C)return!0;if(N&&Array.isArray(N)&&L.roles&&L.roles.length>0){let V=L.roles.filter(O=>N.includes(O));if(V.length===0)return!0;L.roles=V}return T.push(I),!0}return!1},E=(I,R)=>{let C=[];for(let N of I)if(N.type==="matchUserRole"){let T=N;if(!p)continue;if(h&&Array.isArray(h)){let L=T.mode;if(L==="allowlist"){let V=T.allowed??[];if(V.length>0){let O=V.filter(k=>h.includes(k));if(O.length===0)continue;T.allowed=O}}else if(L==="denylist"){let V=T.denied??[];V.length>0&&(T.denied=V.filter(O=>h.includes(O)))}else if(L==="minRole"){if(T.minimumRole&&!h.includes(T.minimumRole))continue}else if(L==="maxRole"&&T.maximumRole&&!h.includes(T.maximumRole))continue}C.push(N)}else{if(w(N,"matchOrganizationRole",u,f,C))continue;if(w(N,"matchProjectRole",m,v,C))continue;if(N.type==="matchResourceAttribute"&&R){let T=N,L=s.get(R);if(!L)continue;let V=Array.from(L.withInheritedProperties());if(V.some(k=>k.key===T.attribute))C.push(N);else{let k,P=i?.findEntity(R);if(P){let z=Array.from(P.withInheritedProperties()).find(B=>B.key===T.attribute);if(z){let B;try{B=z.getExposedName()}catch{}B&&(k=V.find(Y=>{try{return Y.getExposedName()===B}catch{return!1}}))}}if(k)T.attribute=k.key,C.push(N);else continue}}else if(N.type==="matchResourceOwner"&&R){let T=N;if(T.target==="user-entity")C.push(N);else if(T.association&&T.association.key){let L=s.get(R);if(!L)continue;let V=Array.from(L.withInheritedAssociations()),O=T.association.key;if(V.some(P=>P.key===O))C.push(N);else{let P,U=i?.findEntity(R);if(U){let B=Array.from(U.withInheritedAssociations()).find(Y=>Y.key===O);if(B){let Y;try{Y=B.getExposedName()}catch{}if(Y){let ae=V.find(ie=>{try{return ie.getExposedName()===Y}catch{return!1}});ae&&(P=ae.key)}}}P?(T.association.key=P,C.push(N)):(T.association=void 0,C.push(N))}}else C.push(N)}else if(N.type==="matchUserProperty"){let T=N;if(n.user){let L=s.get(n.user.key);if(L&&T.property)if(Array.from(L.withInheritedProperties()).some(k=>k.key===T.property))C.push(N);else{let k=t.userModelRemapping.find(P=>P.oldPropertyKey===T.property);k?(T.property=k.newPropertyKey,C.push(N)):(T.property="",C.push(N))}else C.push(N)}else C.push(N)}else if(N.type==="matchAssociation"){let T=N;if(T.association&&T.association.key){let L=R?s.get(R):void 0;if(L&&R){let V=Array.from(L.withInheritedAssociations());if(!V.some(k=>k.key===T.association.key)){let k=i?.findEntity(R);if(k){let U=Array.from(k.withInheritedAssociations()).find(z=>z.key===T.association.key);if(U){let z;try{z=U.getExposedName()}catch{}if(z){let B=V.find(Y=>{try{return Y.getExposedName()===z}catch{return!1}});B&&(T.association.key=B.key)}}}}}}C.push(N)}else C.push(N)}return C};if(n.accessScenarios)for(let I of n.accessScenarios)I.rules=E(I.rules);for(let I of n.exposes.values()){let R=I.entity.key,C=s.get(R),N=i?.findEntity(R),T=k=>k,L=k=>k,V=!1,O=!1;if(C){let k=Array.from(C.withInheritedProperties()),P=new Set(k.map(B=>B.key)),U=Array.from(C.withInheritedAssociations()),z=new Set(U.map(B=>B.key));T=B=>{let Y=B.split("."),ae=Y[0],ie=ae,Ne=!1;if(P.has(ae))Ne=!0;else if(N){let le=Array.from(N.withInheritedProperties()).find(oe=>oe.key===ae);if(le){let oe;try{oe=le.getExposedName()}catch{}if(oe){let be=k.find($e=>{try{return $e.getExposedName()===oe}catch{return!1}});be&&(ie=be.key,Ne=!0)}}}Y[0]=ie;let ke=Y.join(".");return Ne||(V=!0),ke},L=B=>{let Y=B.split("."),ae=Y[0],ie=ae,Ne=!1;if(z.has(ae))Ne=!0;else if(N){let le=Array.from(N.withInheritedAssociations()).find(oe=>oe.key===ae);if(le){let oe;try{oe=le.getExposedName()}catch{}if(oe){let be=U.find($e=>{try{return $e.getExposedName()===oe}catch{return!1}});be&&(ie=be.key,Ne=!0)}}}Y[0]=ie;let ke=Y.join(".");return Ne||(O=!0),ke}}if(I.accessScenarios)for(let k of I.accessScenarios)k.rules=E(k.rules,R);if(I.actions)for(let k of I.actions){if(k.accessScenarios)for(let P of k.accessScenarios)P.rules=E(P.rules,R);k.projection&&Array.isArray(k.projection.fields)&&(k.projection.fields=k.projection.fields.map(P=>{if(P.type==="association"){O=!1;let U=L(P.key),B=t.actionProjectionsWithMismatches.some(Y=>Y.exposureKey===I.key&&Y.actionKind===k.kind&&Y.fieldType==="association"&&Y.fieldKey===P.key)||O?!0:P.invalid;return{...P,key:U,invalid:B}}else{V=!1;let U=T(P.key),B=t.actionProjectionsWithMismatches.some(Y=>Y.exposureKey===I.key&&Y.actionKind===k.kind&&Y.fieldType==="property"&&Y.fieldKey===P.key)||V?!0:P.invalid;return{...P,key:U,invalid:B}}}))}if(I.paginationContract&&C){let k=I.paginationContract;k.filterableFields&&(k.filterableFields=k.filterableFields.map(T)),k.sortableFields&&(k.sortableFields=k.sortableFields.map(T)),k.searchableFields&&(k.searchableFields=k.searchableFields.map(T))}}n.notifyChange()}var la=class n extends Mi{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=Q(),exposes:i=[],pagination:r}=e,s=pe.fromJSON(e.info,{name:"Unnamed API"}).toJSON(),a={kind:Fe,key:t,info:s,exposes:i,pagination:r?structuredClone(r):{kind:"cursor"}};return e.user&&(a.user=structuredClone(e.user)),e.dependencyList&&(a.dependencyList=structuredClone(e.dependencyList)),e.authentication&&(a.authentication=structuredClone(e.authentication)),e.authorization&&(a.authorization=structuredClone(e.authorization)),e.session&&(a.session=structuredClone(e.session)),Array.isArray(e.accessScenarios)&&(a.accessScenarios=structuredClone(e.accessScenarios)),e.rateLimiting&&(a.rateLimiting=structuredClone(e.rateLimiting)),e.termsOfService&&(a.termsOfService=e.termsOfService),e.contact&&(a.contact=structuredClone(e.contact)),e.license&&(a.license=structuredClone(e.license)),a}constructor(e,t){let i=n.createSchema(e),r=[];if(t instanceof Qe)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===Re)r.push(new Qe(t,void 0,{readOnly:!0}));else if(t)throw new g("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 g(`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 pe(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 kr(this,s)])):this.exposes=new Map,Array.isArray(i.accessScenarios)?this.accessScenarios=i.accessScenarios.map(s=>new Dt(this,s)):this.accessScenarios=[],i.rateLimiting&&(this.rateLimiting=new Tt(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 g("No domain attached to API model",{code:"E_NO_DOMAIN",help:"Attach a data domain to the API model before exposing entities."});let r=xt(e,this.domain?.key),{parentId:s,association:a}=t;if(s&&!a)throw new g("Association not specified for nested entity",{code:"E_NO_ASSOCIATION",help:"Provide an association when exposing a nested entity."});if(!s&&a)throw new g("Association specified for non nested entity",{code:"E_NO_PARENT",help:"Provide a parent when exposing a nested entity."});if(s&&a){let m=this.exposes.get(s);if(!m)throw new g(`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,a)}for(let m of this.exposes.values())if(m.isRoot&&xt(m.entity,this.domain?.key)===r)throw new g(`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 o=i.findEntity(e.key,e.domain);if(!o)throw new g(`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:l,resourcePath:c}=this.generateUniqueRootPaths(o.info.name||""),p={kind:ni,key:Q(),entity:{...e},actions:[],isRoot:!0,collectionPath:l,resourcePath:c,hasCollection:!0},u=new kr(this,p);return this.exposes.set(u.key,u),this.notifyChange(),u}generateUniqueRootPaths(e){let t=Gs(e.toLocaleLowerCase()),i=hr(e),r=`/${t}`,s=`/${t}/{${i}}`,a=1,o=r;for(;this.findCollectionPathCollision(r);)r=`${o}-${a}`,s=`${r}/{${i}}`,a++;return{collectionPath:r,resourcePath:s}}removeExposedEntity(e){if(!this.exposes.has(e))throw new g(`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 g("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(y.User)){this.user={key:t.key};break}this.notifyChange()}findExposedByEntity(e){let t=xt(e,this.domain?.key);for(let i of this.exposes.values())if(xt(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 yl(this,e)}applyDomainUpdate(e,t){bl(this,e,t),this.notifyChange()}};function kl(n,e,t,i,r,s,a,o,l,c){let p=[],u=o.domain;if(!u)return p;let m=Pt(u,o.user),h=Array.from(u.listEntities({includeForeign:!0})).find(f=>f.hasSemantic(i));if(m||p.push({code:S("RULE","MISSING_USER_MODEL"),message:`The API specifies a "Match ${t.toLowerCase()} 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:c}),h||p.push({code:S("RULE",`MISSING_${t.toUpperCase()}_MODEL`),message:`The API specifies a "Match ${t.toLowerCase()} role access" rule, but no ${t} entity is configured.`,suggestion:`Annotate an entity in the domain with the ${t} semantic.`,severity:"error",context:c}),h){let f=u.findEntity(l.entity.key,l.entity.domain),v=[h,m].filter(Boolean),{membersAssoc:w,roleProperty:E}=na(v,r,a),I=E;if(I||(I=Array.from(h.withInheritedProperties()).find(R=>R.hasSemantic(a))||(m?Array.from(m.withInheritedProperties()).find(R=>R.hasSemantic(a)):void 0)),f&&!(f.key===h.key))if(f.hasSemantic(y.User))w||p.push({code:S("RULE",`${t.toUpperCase()}_NOT_LINKED`),message:`[${f.info.getLabel()}]: The access rule is set to "Match ${t.toLowerCase()} role access", but the resource is not linked to the ${t} entity.`,suggestion:`Establish an association between the ${t} entity and this resource entity.`,severity:"error",context:c});else{let C=Array.from(h.withInheritedAssociations()).filter(L=>L.targets.some(V=>V.key===f.key)),N=Array.from(f.withInheritedAssociations()).filter(L=>L.targets.some(V=>V.key===h.key));if(!(C.find(L=>L.hasSemantic(s))||N.find(L=>L.hasSemantic(s)))){let L=C[0]||N[0];if(L){let V=L.info.displayName||(L.info.name&&L.info.name!=="new_association"?L.info.name:L.key);p.push({code:S("RULE",`MISSING_${t.toUpperCase()}_RESOURCE_SEMANTIC`),message:`[${f.info.getLabel()}]: Association "${V}" links ${t} to "${f.info.getLabel()}", but is missing the ${t}Resource semantic annotation.`,suggestion:`Add the ${t}Resource semantic to the association so the runtime can resolve inherited ${t.toLowerCase()} access.`,severity:"error",context:c})}else p.push({code:S("RULE",`${t.toUpperCase()}_NOT_LINKED`),message:`[${f.info.getLabel()}]: The access rule is set to "Match ${t.toLowerCase()} role access", but the resource is not linked to the ${t} entity.`,suggestion:`Establish an association between the ${t} entity and this resource entity.`,severity:"error",context:c})}}if(e&&e.length>0&&I){let R=I.schema?.enum;if(R&&Array.isArray(R))for(let C of e)R.includes(C)||p.push({code:S("RULE",`INVALID_${t.toUpperCase()}_ROLE`),message:`${t} role "${C}" is not defined in the ${t} role enum list.`,suggestion:`Select a valid role from: [${R.join(", ")}].`,severity:"warning",context:c})}}return p}function S(n,e){return`${n}_${e}`}function vl(n){let e=[],t={apiModelKey:n.key,kind:Fe,key:n.key};return n.kind!==Fe&&e.push({code:S("API","INVALID_KIND"),message:"The API model type is incorrect.",suggestion:'Set the model type to "ApiModel".',severity:"error",context:{...t,property:"kind"}}),(!n.key||typeof n.key!="string"||n.key.trim()==="")&&e.push({code:S("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:{...t,property:"key"}}),(!n.info||!n.info.name||n.info.name.trim()==="")&&e.push({code:S("API","MISSING_NAME"),message:"The API model has no defined name.",suggestion:"Provide a descriptive name for your API.",severity:"error",context:{...t,property:"info.name"}}),(!n.info||!n.info.description||n.info.description.trim()==="")&&e.push({code:S("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:{...t,property:"info.description"}}),e}function wl(n){let e=[],t={apiModelKey:n.key,kind:Fe,key:n.key},i=n.domain;return i?((!i.info||!i.info.version)&&e.push({code:S("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:t}),e):(e.push({code:S("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:t}),e)}function Sl(n){let e=[],t={apiModelKey:n.key,kind:Fe,key:n.key},i=n.domain?Pt(n.domain,n.user):void 0;if(!n.authentication)e.push({code:S("API","MISSING_AUTHENTICATION"),message:"The API is missing authentication settings.",suggestion:"Go to the security settings and configure how users authenticate.",severity:"error",context:{...t,property:"authentication"}});else if(n.authentication.strategy==="UsernamePassword"&&i){let r;for(let a of i.properties)if(a.hasSemantic(y.Password)){r=a;break}r||e.push({code:S("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:{...t,property:"user"}});let s;for(let a of i.properties)if(a.hasSemantic(y.Username)){s=a;break}s||e.push({code:S("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:{...t,property:"user"}})}if(!n.authorization)e.push({code:S("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:{...t,property:"authorization"}});else{let r=n.authorization.strategy;if(r==="RBAC"){if(n.domain){let s=Ut(n.domain,i);i&&!s.hasRole&&e.push({code:S("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:{...t,property:"user"}})}}else if(r==="OrganizationRBAC"){if(n.domain){let s=Ui(n.domain);s.hasOrganization||e.push({code:S("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:{...t,property:"authorization"}}),s.hasMembersAssociation||e.push({code:S("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:{...t,property:"authorization"}}),s.hasOrganizationRole||e.push({code:S("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:{...t,property:"authorization"}})}}else if(r==="EnterpriseRBAC"&&n.domain){let s=Ut(n.domain,i);i&&!s.hasRole&&e.push({code:S("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:{...t,property:"user"}});let a=Ui(n.domain);a.hasOrganization||e.push({code:S("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:{...t,property:"authorization"}}),a.hasMembersAssociation||e.push({code:S("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:{...t,property:"authorization"}}),a.hasOrganizationRole||e.push({code:S("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:{...t,property:"authorization"}})}}if(!n.session)e.push({code:S("API","MISSING_SESSION"),message:"The API is missing session configuration.",suggestion:"Configure how user sessions will be handled.",severity:"error",context:{...t,property:"session"}});else{if(n.session.secret||e.push({code:S("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:{...t,property:"session.secret"}}),!n.session.properties||n.session.properties.length===0)e.push({code:S("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:{...t,property:"session.properties"}});else if(n.authorization&&(n.authorization.strategy==="RBAC"||n.authorization.strategy==="EnterpriseRBAC")&&n.domain){let a=Ut(n.domain,i);a.roleProperty&&!n.session.properties.find(o=>o.key===a.roleProperty?.key)&&e.push({code:S("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:{...t,property:"session.properties"}})}let{cookie:r,jwt:s}=n.session;(!r||!r.enabled)&&(!s||!s.enabled)&&e.push({code:S("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:{...t,property:"session"}})}if(n.user?n.domain&&!n.domain.findEntity(n.user.key,n.user.domain)&&e.push({code:S("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:{...t,property:"user"}}):e.push({code:S("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:{...t,property:"user"}}),n.accessScenarios&&n.accessScenarios.length>0)for(let r of n.accessScenarios)for(let s of r.rules)e.push(...No(s,"api",void 0,n));return e}function _l(n){let e=[],t={apiModelKey:n.key,kind:Fe,key:n.key},i=/^https?:\/\//i,r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return n.contact?(n.contact.email&&!r.test(n.contact.email)&&e.push({code:S("API","INVALID_CONTACT_EMAIL"),message:"The contact email address looks invalid.",suggestion:"Please double check the email address formatting.",severity:"error",context:{...t,property:"contact.email"}}),n.contact.url&&!i.test(n.contact.url)&&e.push({code:S("API","INVALID_CONTACT_URL"),message:"The contact link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...t,property:"contact.url"}})):e.push({code:S("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:{...t,property:"contact"}}),n.license?n.license.url&&!i.test(n.license.url)&&e.push({code:S("API","INVALID_LICENSE_URL"),message:"The license link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...t,property:"license.url"}}):e.push({code:S("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:{...t,property:"license"}}),n.termsOfService||e.push({code:S("API","MISSING_TOS"),message:"Terms of Service help legal compliance.",suggestion:"Add a link to the terms of your API service.",severity:"info",context:{...t,property:"termsOfService"}}),e}function Al(n){let e=[],t={apiModelKey:n.key,kind:Fe,key:n.key},i=!1;for(let r of n.exposes.values())if(r.actions.some(s=>Mt.isListAction(s)||Lt.isSearchAction(s))){i=!0;break}return i&&(!n.pagination||!n.pagination.kind?e.push({code:S("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:{...t,property:"pagination"}}):(n.pagination.defaultLimit===void 0&&e.push({code:S("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:{...t,property:"pagination.defaultLimit"}}),n.pagination.maxLimit===void 0&&e.push({code:S("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:{...t,property:"pagination.maxLimit"}}))),e}function wp(n,e,t){let i=[],r={apiModelKey:t.key,kind:"Action",key:n.kind,parentExposedEntityKey:e.key};if(ai.isDeleteAction(n)&&(n.strategy?n.strategy==="hard"&&i.push({code:S("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:{...r,property:"strategy"}}):i.push({code:S("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:{...r,property:"strategy"}})),vi.isUpdateAction(n)&&(!n.allowedMethods||n.allowedMethods.length===0)&&i.push({code:S("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:{...r,property:"allowedMethods"}}),wi.isRestoreAction(n)){let c=e.actions.find(ai.isDeleteAction);(!c||c.strategy!=="soft")&&i.push({code:S("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:{...r,property:"kind"}})}if(n.getAllRateLimiters().some(c=>c.rules.length)||i.push({code:S("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:r}),n.accessScenarios)for(let c of n.accessScenarios)for(let p of c.rules)i.push(...No(p,"action",e,t,n));n.overrideParentScenarios&&n.accessScenarios.length===0&&i.push({code:S("ACTION","OVERRIDE_BUT_NO_SCENARIOS"),message:`Action "${n.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:{...r,property:"overrideParentScenarios"}});let o=n.getAllScenarios();for(let c of o)c.rules.some(u=>u.isIdentityConstraining)||i.push({code:S("ACTION","SCENARIO_MISSING_IDENTITY_RULE"),message:`Scenario "${c.label||c.key}" on action "${n.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:{...r,property:"accessScenarios"}});let l=null;for(let c of o){let p=c.rules.filter(u=>u.isIdentityConstraining);if(p.length>0){if(p.every(m=>m.isBroadIdentityRule))l||(l=c);else if(l){i.push({code:S("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:{...r,property:"accessScenarios"}});break}}}if(n.projection&&(Mt.isListAction(n)||Lt.isSearchAction(n)||ki.isReadAction(n)||i.push({code:S("ACTION","INVALID_PROJECTION_SEVERITY"),message:`Projections are only supported for read actions (List, Search, Read). The action "${n.kind}" does not support projections.`,suggestion:"Remove projection configuration from this write action.",severity:"warning",context:{...r,property:"projection"}}),n.projection.type!=="include"&&n.projection.type!=="exclude"&&i.push({code:S("ACTION","INVALID_PROJECTION_TYPE"),message:'Projection type must be either "include" or "exclude".',suggestion:"Select a valid projection type.",severity:"error",context:{...r,property:"projection"}}),Array.isArray(n.projection.fields))){let p=e.entity?t.domain?.findEntity(e.entity.key,e.entity.domain):void 0;if(p){let u=Array.from(p.withInheritedProperties()),m=new Set(u.map(f=>f.key)),h=new Set(Array.from(p.withInheritedAssociations()).map(f=>f.key));n.projection.fields.forEach((f,v)=>{if(f.invalid===!0){i.push({code:S("ACTION","INVALID_PROJECTION_FIELD"),message:`The projected field "${f.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:{...r,property:`projection.fields[${v}]`}});return}if(f.type==="association"){let w=f.key.split("."),E=w[0];if(!h.has(E))i.push({code:S("ACTION","INVALID_PROJECTION_ASSOCIATION"),message:`The projected association "${f.key}" does not exist on this entity.`,suggestion:"Select a valid association or remove it.",severity:"error",context:{...r,property:`projection.fields[${v}]`}});else{let I=Array.from(p.withInheritedAssociations()).find(R=>R.key===E);w.length>1&&(!I||I.schema?.embedded!==!0)&&i.push({code:S("ACTION","INVALID_PROJECTION_ASSOCIATION_EMBEDDED"),message:`The projected association "${f.key}" is invalid because association "${E}" is not embedded.`,suggestion:"Ensure the association is marked as embedded to use dot-notation.",severity:"error",context:{...r,property:`projection.fields[${v}]`}})}}else{let w=f.key.split("."),E=w[0];if(!m.has(E))i.push({code:S("ACTION","INVALID_PROJECTION_PROPERTY"),message:`The projected property "${f.key}" does not exist on this entity.`,suggestion:"Select a valid property or remove it.",severity:"error",context:{...r,property:`projection.fields[${v}]`}});else{let I=u.find(R=>R.key===E);w.length>1&&(!I||I.type!=="json"?i.push({code:S("ACTION","INVALID_PROJECTION_JSON_ROOT"),message:`The projected property "${f.key}" is invalid because root property "${E}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...r,property:`projection.fields[${v}]`}}):I.jsonSchema&&(Et(I.jsonSchema,w.slice(1))||i.push({code:S("ACTION","INVALID_PROJECTION_JSON_PATH"),message:`The projected property "${f.key}" is invalid according to the JSON Schema of "${E}".`,suggestion:"Configure a valid JSON Schema path or update the projection path.",severity:"error",context:{...r,property:`projection.fields[${v}]`}})))}}})}}return i}function El(n,e){let t=[],i={apiModelKey:e.key,kind:ni,key:n.key},r=n.entity?e.domain?.findEntity(n.entity.key,n.entity.domain):void 0,s=r?.info.getLabel()||r?.key||"unknown";!n.entity||!n.entity.key?t.push({code:S("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:{...i,property:"entity"}}):r||t.push({code:S("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:{...i,property:"entity"}});let a=r?.hasSemantic(y.User);if(n.isRoot&&r&&!a&&e.domain&&e.domain.resolveOwnershipPath(r.key)===null&&t.push({code:S("EXPOSURE","MISSING_OWNER_PATH"),message:`[${s}]: 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:i}),!n.isRoot&&e.domain)if(!n.parent)t.push({code:S("EXPOSURE","MISSING_PARENT_REF"),message:`[${s}]: 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:{...i,property:"parent"}});else{let l=e.exposes.get(n.parent.key);if(!l)t.push({code:S("EXPOSURE","INVALID_PARENT_EXPOSURE"),message:`[${s}]: The parent exposed entity "${n.parent.key}" does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...i,property:"parent.key"}});else{let c=e.domain.findEntity(l.entity.key,l.entity.domain),p=n.parent.association.key,u=e.domain.findAssociation(p,n.parent.association.domain);if(!u)t.push({code:S("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${s}]: The parent association "${p}" 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:{...i,property:"parent.association"}});else{let m=c?.key,h=r?.key,f=u.getParentInstance()?.key===m,v=u.getParentInstance()?.key===h,w=u.targets.some(R=>R.key===m),E=u.targets.some(R=>R.key===h);f&&E||v&&w||t.push({code:S("EXPOSURE","INVALID_PARENT_ASSOCIATION"),message:`[${s}]: The parent association "${p}" does not connect the parent entity "${c?.info.name||m}" with the child entity "${r?.info.name||h}".`,suggestion:"Use an association that directly connects the parent and child data entities.",severity:"error",context:{...i,property:"parent.association"}})}}}if(n.hasCollection){if(!n.collectionPath)t.push({code:S("EXPOSURE","MISSING_COLLECTION_PATH"),message:`[${s}]: 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:{...i,property:"collectionPath"}});else{let l=n.collectionPath.split("/").filter(Boolean);(l.length!==1||!n.collectionPath.startsWith("/"))&&t.push({code:S("EXPOSURE","INVALID_COLLECTION_PATH"),message:`[${s}]: The collection URL should start with "/" and have no extra slashes.`,suggestion:`Ensure the path looks like exactly "/${l[0]||"subresource"}".`,severity:"error",context:{...i,property:"collectionPath"}})}n.resourcePath?n.collectionPath&&(new RegExp(`^${n.collectionPath}/\\{[a-zA-Z0-9_]+\\}$`).test(n.resourcePath)||t.push({code:S("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${s}]: The single item route should match exactly your collection path plus one identifier variable.`,suggestion:`Make sure the item path is formatted exactly like "${n.collectionPath}/{id}".`,severity:"error",context:{...i,property:"resourcePath"}})):t.push({code:S("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${s}]: You need an identifier to locate single items.`,suggestion:'Specify the identification parameter format, like "{id}".',severity:"error",context:{...i,property:"resourcePath"}})}else n.resourcePath?(n.resourcePath.split("/").filter(Boolean).length!==1||!n.resourcePath.startsWith("/"))&&t.push({code:S("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${s}]: The URL route ${n.resourcePath} must only contain one exact part or level.`,suggestion:"Simplify the endpoint URL to a single segment.",severity:"error",context:{...i,property:"resourcePath"}}):t.push({code:S("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${s}]: Exposed entity representing a single item must declare their URL route.`,suggestion:'Set the URL path (such as "/profile").',severity:"error",context:{...i,property:"resourcePath"}});n.isRoot&&(n.collectionPath&&e.findCollectionPathCollision(n.collectionPath,n.key)&&t.push({code:S("EXPOSURE","ROOT_COLLECTION_COLLISION"),message:`[${s}]: The route "${n.collectionPath}" is already used by another view.`,suggestion:"Give this resource a different path to avoid conflicts.",severity:"error",context:{...i,property:"collectionPath"}}),n.resourcePath&&e.findResourcePathCollision(n.resourcePath,n.key)&&t.push({code:S("EXPOSURE","ROOT_RESOURCE_COLLISION"),message:`[${s}]: The route "${n.resourcePath}" is already used by another one.`,suggestion:"Give this single-item resource a different path to avoid conflicts.",severity:"error",context:{...i,property:"resourcePath"}}));let o=n.getAbsoluteResourcePath();if(o){let l=[...o.matchAll(/\{([^}]+)\}/g)].map(p=>p[1]);if(new Set(l).size!==l.length){let u=l.filter((m,h)=>l.indexOf(m)!==h)[0];t.push({code:S("EXPOSURE","DUPLICATE_PATH_PARAMETER"),message:`[${s}]: The path parameter "{${u}}" 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:{...i,property:"resourcePath"}})}}if(!n.actions||n.actions.length===0)t.push({code:S("EXPOSURE","MISSING_ACTIONS"),message:`[${s}]: This exposed entity does not let users do anything.`,suggestion:"Enable at least one operation like Create, Read, or Update.",severity:"error",context:{...i,property:"actions"}});else{let l=!1,c=!1,p=!1,u=!1;for(let m of n.actions)t.push(...wp(m,n,e)),Lt.isSearchAction(m)&&(l=!0),Mt.isListAction(m)&&(c=!0),(m.kind==="link"||m.kind==="unlink")&&(p=!0),(m.kind==="create"||m.kind==="delete")&&(u=!0),m.getAllScenarios().length===0&&t.push({code:S("ACTION","MISSING_ACCESS_RULES"),message:`[${s}]: The ${m.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:{...i,kind:"Action",key:m.kind,parentExposedEntityKey:n.key}});if(p&&u&&t.push({code:S("EXPOSURE","MUTUALLY_EXCLUSIVE_ACTIONS"),message:`[${s}]: 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:{...i,property:"actions"}}),c||l){let m=n.paginationContract;if(!m)t.push({code:S("EXPOSURE","MISSING_PAGINATION_CONTRACT"),message:`[${s}]: The List or Search action needs a pagination contract.`,suggestion:"Add a pagination contract to the exposed entity.",severity:"error",context:i});else{if(c&&((!m.filterableFields||m.filterableFields.length===0)&&t.push({code:S("EXPOSURE","LIST_MISSING_FILTERS"),message:`[${s}]: Listing all elements without filters could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow filtering.",severity:"warning",context:i}),(!m.sortableFields||m.sortableFields.length===0)&&t.push({code:S("EXPOSURE","LIST_MISSING_SORTING"),message:`[${s}]: Listing all elements without sorting could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow sorting.",severity:"warning",context:i})),l){let h=[];Array.isArray(m.searchableFields)&&h.push(...m.searchableFields),Array.isArray(m.filterableFields)&&h.push(...m.filterableFields),h.length||t.push({code:S("EXPOSURE","SEARCH_MISSING_FIELDS"),message:`[${s}]: 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:i})}if(r){let h=Array.from(r.withInheritedProperties()),f=new Set(h.map(w=>w.key)),v=(w,E,I,R)=>{if(w&&Array.isArray(w))for(let C of w){let N=C.split("."),T=N[0];if(!f.has(T))t.push({code:S("EXPOSURE",I),message:`[${s}]: The ${R} field "${C}" does not exist on this entity.`,suggestion:`Select a valid property on the entity for ${R}.`,severity:"error",context:{...i,property:`paginationContract.${E}Fields`}});else{let L=h.find(V=>V.key===T);N.length>1&&(!L||L.type!=="json"?t.push({code:S("EXPOSURE",I),message:`[${s}]: The ${R} field "${C}" is invalid because root property "${T}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...i,property:`paginationContract.${E}Fields`}}):L.jsonSchema&&(Et(L.jsonSchema,N.slice(1))||t.push({code:S("EXPOSURE",I),message:`[${s}]: The ${R} field "${C}" is invalid according to the JSON Schema of "${T}".`,suggestion:"Configure a valid JSON Schema path or update the field path.",severity:"error",context:{...i,property:`paginationContract.${E}Fields`}})))}}};v(m.filterableFields,"filterable","INVALID_FILTER_FIELD","filterable"),v(m.sortableFields,"sortable","INVALID_SORT_FIELD","sortable"),v(m.searchableFields,"searchable","INVALID_SEARCH_FIELD","searchable")}}}}if(n.accessScenarios)for(let l of n.accessScenarios)for(let c of l.rules)t.push(...No(c,"exposure",n,e));return t}function No(n,e,t,i,r){let s=[],a={apiModelKey:i.key,kind:"AccessRule",key:n.type,...t?{parentExposedEntityKey:t.key}:{}};if(!n.allowedLevels.includes(e)){if(e==="api")s.push({code:S("RULE","INVALID_LEVEL"),message:`[${i.info.getLabel()}]: The "${n.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 o=e==="exposure"?"an exposed entity":"an action",l=n.allowedLevels.join(", ");s.push({code:S("RULE","INVALID_LEVEL"),message:`[${t?.entity?.key??t?.key}]: The "${n.type}" access rule cannot be used at the ${e} level because it is only allowed at: [${l}].`,suggestion:`Move this access rule to ${l.includes("api")?"the API level":o==="an exposed entity"?"an action":"an exposed entity"}.`,severity:"error",context:a})}return s}if(i.authorization?.strategy&&(fl(i.authorization.strategy,e).includes(n.type)||s.push({code:S("RULE","INCOMPATIBLE_RULE_FOR_STRATEGY"),message:`The "${n.type}" access rule is not compatible with the ${i.authorization.strategy} authorization strategy.`,suggestion:"Switch to a strategy that supports this rule.",severity:"error",context:a})),n.type==="matchUserRole"){let o=n,l=i.domain,c=["allowlist","denylist","minRole","maxRole"];if((!o.mode||!c.includes(o.mode))&&s.push({code:S("RULE","MATCH_USER_ROLE_INVALID_MODE"),message:`The "matchUserRole" access rule has an invalid or missing mode "${o.mode??""}". Valid modes are: allowlist, denylist, minRole, maxRole.`,suggestion:"Set the mode to one of: allowlist, denylist, minRole, or maxRole.",severity:"error",context:a}),o.roleMatch!==void 0&&o.roleMatch!=="any"&&o.roleMatch!=="all"&&s.push({code:S("RULE","MATCH_USER_ROLE_INVALID_ROLE_MATCH"),message:`The "matchUserRole" access rule has an invalid roleMatch "${o.roleMatch}". Valid values are: any, all.`,suggestion:'Set roleMatch to either "any" or "all", or omit it to use the default.',severity:"error",context:a}),o.mode==="allowlist")o.allowed?o.allowed.length===0&&s.push({code:S("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:a}):s.push({code:S("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:a});else if(o.mode==="denylist")o.denied?o.denied.length===0&&s.push({code:S("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:a}):s.push({code:S("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:a});else if(o.mode==="minRole"||o.mode==="maxRole"){let p=o.mode==="minRole",u=p?"minimumRole":"maximumRole",m=p?o.minimumRole:o.maximumRole,h=p?"minimum":"maximum";if(!m)s.push({code:S("RULE",p?"MATCH_USER_ROLE_MIN_ROLE_MISSING":"MATCH_USER_ROLE_MAX_ROLE_MISSING"),message:`The "matchUserRole" access rule is in ${o.mode} mode, but "${u}" is not specified.`,suggestion:`Specify the ${h} required role name in the "${u}" field.`,severity:"error",context:a});else if(l){let f=Pt(l,i.user);if(f){let v=Ut(l,f),w=v.roleProperty?.schema?.enum;Array.isArray(w)&&!w.includes(m)&&s.push({code:S("RULE",p?"MATCH_USER_ROLE_MIN_ROLE_NOT_IN_ENUM":"MATCH_USER_ROLE_MAX_ROLE_NOT_IN_ENUM"),message:`The "${u}" value "${m}" does not exist in the UserRole enum. Valid roles are: ${w.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:a}),o.mode==="maxRole"&&v.roleProperty?.multiple&&o.roleMatch!=="all"&&s.push({code:S("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:a})}}}if(l&&(o.mode==="allowlist"||o.mode==="denylist")){let p=Pt(l,i.user);if(p){let m=Ut(l,p).roleProperty?.schema?.enum;if(Array.isArray(m)){let h=o.mode==="allowlist"?o.allowed??[]:o.denied??[],f=o.mode==="allowlist"?"allowed":"denied";for(let v of h)m.includes(v)||s.push({code:S("RULE","MATCH_USER_ROLE_INVALID_ROLE_VALUE"),message:`The role "${v}" in the "${f}" list does not exist in the UserRole enum.`,suggestion:`Remove "${v}" or correct it to a valid UserRole enum value: ${m.join(", ")}.`,severity:"warning",context:a})}}}}else if(n.type==="matchEmailDomain"){let o=n,l=i.domain;if(l){let c=Pt(l,i.user);if(!c)s.push({code:S("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:a});else{let p=Array.from(c.withInheritedProperties()).find(u=>u.hasSemantic(y.Email));p?o.requireVerified!==!1&&((p.getSemantic(y.Email)?.config?.requireVerification??oa.requireVerification??!0)||s.push({code:S("RULE","EMAIL_VERIFICATION_MISMATCH"),message:`The "Match email domain" access rule requires verified email addresses (requireVerified: true), but the Email data semantic on property "${p.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:a})):s.push({code:S("RULE","MISSING_EMAIL_SEMANTIC"),message:`The access rule is set to "Match email domain", but the User entity "${c.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:a})}}(!o.domains||o.domains.length===0)&&s.push({code:S("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:a})}else if(n.type==="matchUserProperty"){let o=n,l=i.domain;if(l){let u=Pt(l,i.user);if(!u)s.push({code:S("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:a});else if(o.property){let m=Array.from(u.withInheritedProperties());if(!m.some(f=>f.key===o.property))s.push({code:S("RULE","INVALID_USER_PROPERTY"),message:`The user property "${o.property}" does not exist on the User entity "${u.info.getLabel()}".`,suggestion:"Select a valid property on the User entity.",severity:"error",context:a});else if(i.session?.properties&&!i.session.properties.some(v=>v.key===o.property)){let w=m.find(E=>E.key===o.property)?.info.getLabel()??o.property;s.push({code:S("RULE","USER_PROPERTY_NOT_IN_SESSION"),message:`The user property "${w}" 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:a})}}else s.push({code:S("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:a})}let c=yi.isArrayOperator(o.operator),p=yi.isScalarOperator(o.operator);!c&&!p?s.push({code:S("RULE","INVALID_USER_PROPERTY_OPERATOR"),message:`The operator "${o.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:a}):c?Array.isArray(o.values)?o.values.length===0&&s.push({code:S("RULE","MATCH_USER_PROPERTY_EMPTY_ARRAY"),message:`The "${o.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:a}):s.push({code:S("RULE","MATCH_USER_PROPERTY_ARRAY_REQUIRED"),message:`The "${o.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:a}):Array.isArray(o.value)&&s.push({code:S("RULE","MATCH_USER_PROPERTY_SCALAR_REQUIRED"),message:`The "${o.operator}" operator does not accept array 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:a})}if(!t)return s;if(n.type==="relationalResourceOwner"){let o=i.domain;if(!o)return s;let l=t.entity.key,c=o.findEntity(l),p=c?c.info.getLabel():t.key;if(t.isRoot||!t.parent)return s.push({code:S("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}),s;let u=t.parent.key,m=!1,h=new Set([t.key]);for(;u&&!h.has(u);){h.add(u);let f=i.exposes.get(u);if(!f)break;let v=o.findEntity(f.entity.key,f.entity.domain);if(v){if(v.hasSemantic(y.User)){m=!0;break}let w=!1;for(let E of v.withInheritedAssociations())if(E.hasSemantic(y.ResourceOwnerIdentifier)){w=!0;break}if(w){m=!0;break}}u=f.parent?.key}m||s.push({code:S("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})}else if(n.type==="matchResourceOwner"){let o=n,l=i.domain;if(!l)return s;let c=t.entity.key,p=l.findEntity(c);if(!p)return s;if(o.target==="user-entity")p.hasSemantic(y.User)||s.push({code:S("RULE","INVALID_USER_ENTITY_TARGET"),message:`[${p.info.getLabel()}]: 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});else if(o.association&&o.association.key){let u=o.association.key,m=o.association.domain,h=l.findAssociation(u,m),f=Array.from(p.withInheritedAssociations());(h?f.some(w=>w.key===h.key):f.some(w=>w.key===u))||s.push({code:S("RULE","INVALID_OWNERSHIP_ASSOCIATION"),message:`[${p.info.getLabel()}]: The ownership association "${u}" does not exist on this entity.`,suggestion:"Select a valid association, or clear the field to use transitively resolved ownership.",severity:"error",context:a})}else l.resolveOwnershipPath(c)===null&&s.push({code:S("RULE","MISSING_OWNERSHIP_PATH"),message:`[${p.info.getLabel()}]: The access rule is set to "Match resource owner", but no direct association or transitive ownership path to the User entity exists.`,suggestion:"Annotate an association with the ResourceOwnerIdentifier or RelationalResourceOwner semantic.",severity:"error",context:a})}else if(n.type==="matchResourceAttribute"){let o=n,l=i.domain;if(!l)return s;let c=l.findEntity(t.entity.key,t.entity.domain);if(!c)return s;o.attribute?Array.from(c.withInheritedProperties()).some(f=>f.key===o.attribute)||s.push({code:S("RULE","INVALID_RESOURCE_ATTRIBUTE"),message:`[${c.info.getLabel()}]: The resource attribute property "${o.attribute}" does not exist.`,suggestion:"Select a valid property on the entity.",severity:"error",context:a}):s.push({code:S("RULE","MISSING_RESOURCE_ATTRIBUTE"),message:`[${c.info.getLabel()}]: 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:a});let p=gi.isArrayOperator(o.operator),u=gi.isScalarOperator(o.operator);!p&&!u?s.push({code:S("RULE","INVALID_RESOURCE_ATTRIBUTE_OPERATOR"),message:`[${c.info.getLabel()}]: The operator "${o.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:a}):p?Array.isArray(o.values)?o.values.length===0&&s.push({code:S("RULE","MATCH_RESOURCE_ATTRIBUTE_EMPTY_ARRAY"),message:`[${c.info.getLabel()}]: The "${o.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:a}):s.push({code:S("RULE","MATCH_RESOURCE_ATTRIBUTE_ARRAY_REQUIRED"),message:`[${c.info.getLabel()}]: The "${o.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:a}):Array.isArray(o.value)&&s.push({code:S("RULE","MATCH_RESOURCE_ATTRIBUTE_SCALAR_REQUIRED"),message:`[${c.info.getLabel()}]: The "${o.operator}" operator does not accept array 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:a})}else if(n.type==="matchOrganizationRole"){let o=n;s.push(...kl("matchOrganizationRole",o.roles,"Organization",y.Organization,y.OrganizationMembers,y.OrganizationResource,y.OrganizationRole,i,t,a))}else if(n.type==="matchProjectRole"){let o=n;s.push(...kl("matchProjectRole",o.roles,"Project",y.Project,y.ProjectMembers,y.ProjectResource,y.ProjectRole,i,t,a))}else if(n.type==="matchAssociation"){let o=n,l=i.domain;if(l)if(Pt(l,i.user)||s.push({code:S("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:a}),!o.association||!o.association.key)s.push({code:S("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:a});else{let p=o.association.key,u=o.association.domain,m=l.findAssociation(p,u),h=t.entity.key,f=l.findEntity(h),v=f?Array.from(f.withInheritedAssociations()).find(w=>w.key===p):void 0;if(!m&&!v){let w=f?f.info.getLabel():h;s.push({code:S("RULE","INVALID_ASSOCIATION_TARGET"),message:`[${w}]: The target association "${p}" does not exist in the domain.`,suggestion:"Select a valid association configured in the data domain.",severity:"error",context:a})}}}else if(n.type==="matchPathParameter"){let o=n;if(!o.parameters||o.parameters.length===0)s.push({code:S("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});else{let l;if(e==="action"&&r)if(["list","create","search","link"].includes(r.kind)){let m=t.getAbsoluteCollectionPath()??"";l=new Set([...m.matchAll(/\{([^}]+)\}/g)].map(h=>h[1]))}else{let m=t.getAbsoluteResourcePath();l=new Set([...m.matchAll(/\{([^}]+)\}/g)].map(h=>h[1]))}else l=new Set(t.getPathParameters({absolute:!0}));let c=i.domain,p=c?Pt(c,i.user):void 0,u=new Set;if(i.session?.properties)for(let m of i.session.properties)m.key&&u.add(m.key);if(p)for(let m of p.withInheritedProperties())u.add(m.key);for(let m of o.parameters){if(!m.pathParameter||m.pathParameter.trim()==="")s.push({code:S("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(!l.has(m.pathParameter)){let h=t.entity?c?.findEntity(t.entity.key,t.entity.domain)?.info.getLabel()??t.entity.key:t.key,f=l.size>0?`[${Array.from(l).join(", ")}]`:"none";s.push({code:S("RULE","MATCH_PATH_PARAMETER_MISSING_ROUTE_PARAM"),message:`[${h}]: Path parameter "${m.pathParameter}" declared in "Match path parameter" rule was not found in the route hierarchy.`,suggestion:`Ensure the route path includes "{${m.pathParameter}}" or select from available parameters: ${f}.`,severity:"error",context:a})}!m.sessionProperty||m.sessionProperty.trim()===""?s.push({code:S("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}):u.size>0&&!u.has(m.sessionProperty)&&s.push({code:S("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${m.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:`Select a valid session property from: [${Array.from(u).join(", ")}].`,severity:"error",context:a})}}}return s}var ca=class{model;report=[];#e=0;#t=0;#i=0;#r=!1;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(){if(this.#r=!1,this.report=[],this.report.push(...vl(this.model)),this.report.push(...wl(this.model)),this.report.push(...Sl(this.model)),this.report.push(...Al(this.model)),this.report.push(..._l(this.model)),!this.model.exposes||this.model.exposes.size===0)this.report.push({code:"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:Fe,key:this.model.key,property:"exposes"}});else for(let e of this.model.exposes.values())this.report.push(...El(e,this.model));return this.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 pa=class extends Oe{constructor(t,i,r){super(i,r);this.file=t}file;async execute(){b.debug("[validate] Executing schema validation...");try{this.validateArguments();let t=await this.loadSchema();this.validateSchemaStructure(t);let i=t.kind,r=[];i===Re?r=await this.validateDataDomain(t):i===Fe?r=await this.validateApiModel(t):(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Unsupported schema kind "${i}". Supported kinds: "${Re}", "${Fe}".`}),process.exit(1)),this.reportResults(r,i)}catch(t){let i=F(t);this.formatter.error(i),process.exit(1)}}get isRemoteValidationWithoutOrg(){return!!(this.options.fid&&!this.options.org&&!A.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 b.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.");b.debug(`[validate] Fetching remote schema file ID '${this.options.fid}' from organization '${t}'...`);let i=G(),{media:r}=await i.files.readMedia(t,this.options.fid,{token:i.token});return b.debug("[validate] Remote schema loaded successfully."),r}async loadLocalSchema(){let t;if(this.shouldReadFromStdin)b.debug("[validate] Reading schema from STDIN..."),t=await this.readStdin();else if(this.file){let i=xl.resolve(this.file);b.debug(`[validate] Reading local schema file from path: ${i}`),da.existsSync(i)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${i}`}),process.exit(1)),t=da.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 b.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){b.debug("[validate:domain] Validating schema as Data Domain...");let i=[];if(this.options.fid){let o=G(),l=t.dependencyList||[];l.length>0&&(b.debug(`[validate:domain] Listing ${l.length} dependency data domains from catalog...`),i=(await o.dataCatalog.listDependencies(l,{token:o.token})).data||[])}let r=new Qe(t,i,{readOnly:!0}),a=new Li(r).validate();return b.debug(`[validate:domain] Domain validation rules executed. Issues found: ${a.length}`),a}async validateApiModel(t){b.debug("[validate:api] Validating schema as API Model...");let i;if(this.options.fid){let o=G(),l=t.dependencyList||[];if(l.length>0){b.debug(`[validate:api] Listing ${l.length} dependency data domains from catalog...`);let p=(await o.dataCatalog.listDependencies(l,{token:o.token})).data||[];p.length>0&&(i=new Qe(p[0],p,{readOnly:!0}))}}else if(this.options.domain){let o=xl.resolve(this.options.domain);b.debug(`[validate:api] Loading domain dependency from local path: ${o}`),da.existsSync(o)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${o}`}),process.exit(1));let l;try{l=JSON.parse(da.readFileSync(o,"utf8"))}catch(c){let p=c instanceof Error?c.message:String(c);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${p}`}),process.exit(1)}i=new Qe(l,[],{readOnly:!0})}let r=new la(t,i),a=new ca(r).validate();return b.debug(`[validate:api] API Model validation rules executed. Issues found: ${a.length}`),a}reportResults(t,i){b.debug(`[validate] Reporting results. Found ${t.length} validation issue(s).`);let r=t.some(s=>s.severity==="error");if(A.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 a=t.filter(c=>c.severity==="error").length,o=t.filter(c=>c.severity==="warning").length,l=t.filter(c=>c.severity==="info").length;console.log(""),a>0?console.error(ee.red(`\u2716 Validation failed: ${a} error(s), ${o} warning(s), ${l} info(s).`)):console.log(ee.yellow(`\u26A0 Validation passed with warnings: ${o} warning(s), ${l} info(s).`))}r&&process.exit(1)}formatIssues(t,i){return t.map(r=>{let s=r.severity||"info",a=r.message||"",o,l,c;if(i===Re){let p=r;o=p.rule||"unknown",l=p.help||"",c=p.key?`${p.kind||"unknown"}: ${p.key}`:p.field||""}else{let p=r;o=p.code||"unknown",l=p.suggestion||"";let u=p.context||{};c=`${u.kind||"unknown"}: ${u.key||""}${u.property?"."+u.property:""}`}return{severity:s,code:o,message:a,suggestion:l,context:c}})}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 Pl(n){n.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 Z({format:A.resolved.format});b.debug("[validate] Starting validation process..."),await new pa(e,t,i).execute()})}var ua=class extends Oe{async execute(){b.debug("[runtime:update] Executing runtime user update...");try{let e=G();Ei(e,this.formatter);let t=this.resolveOrgId("Organization ID is not specified.","Use --org <oid> or configure a default organization.");b.debug(`[runtime:update] Using organization ID: ${t}`),b.debug("[runtime:update] Parsing properties...");let i=this.parseProperties(this.options.property),r={};for(let[a,o]of Object.entries(i)){let l=["token","password","secret","key"].some(c=>a.toLowerCase().includes(c));r[a]=l?"**********":o}b.debug(`[runtime:update] Parsed properties: ${JSON.stringify(r)}`),b.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});b.debug("[runtime:update] Runtime user updated successfully."),this.formatter.success(`User '${this.options.userId}' updated successfully!`,s)}catch(e){let t=F(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(),a=r.slice(1).join("=").trim();a==="true"?t[s]=!0:a==="false"?t[s]=!1:a==="null"?t[s]=null:/^\d+$/.test(a)?t[s]=parseInt(a,10):/^\d*\.\d+$/.test(a)?t[s]=parseFloat(a):t[s]=a}return t}};function Ol(n){n.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 Z({format:A.resolved.format});b.debug("[runtime:update] Starting runtime user update process..."),await new ua(i,r).execute()})}var Ot=class{constructor(e=new ne,t=G()){this.fileManager=e;this.client=t}fileManager;client;async loadDomain(e,t){let i=await this.fileManager.read(e,t);if(i.kind!==Kt)throw new Error(`File '${t}' is not a data domain. The file kind is '${i.kind}', but expected '${Kt}'.`);let r=await this.fileManager.readMedia(e,t),s=r.media;if(s.kind!==Re)throw new Error(`Invalid data domain schema format. The media kind is '${s.kind}', but expected '${Re}'.`);let a=[];if(s.dependencyList&&s.dependencyList.length>0){b.debug(`[domain:load] Fetching dependencies: ${JSON.stringify(s.dependencyList)}`);try{a=(await this.client.dataCatalog.listDependencies(s.dependencyList,{token:this.client.token})).data||[]}catch(l){b.debug(`[domain:load] Failed to fetch dependencies: ${l}`)}}return{domain:new Qe(s,a,{readOnly:!1}),fileMeta:i,metaVersion:r.meta.version,originalSchema:s}}};var He=class extends Oe{fileManager;domainLoader;constructor(e,t,i=new ne,r=new Ot(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){b.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 Xe(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){b.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=F(i);this.formatter.error(r),process.exit(1)}}validateDomain(e,t={}){b.debug("[domain] Validating data domain structure...");let r=new Li(e).validate();if(r&&r.length>0){let s=r.filter(o=>o.severity==="error"),a=r.filter(o=>o.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&&a.length>0&&this.formatter.format!=="json"){console.log(ee.yellow(`\u26A0 Data domain validation reported ${a.length} warning(s):`));for(let o of a)console.log(ee.yellow(` - [${o.rule||"WARNING"}] ${o.message}`))}}}};var ma=class extends He{constructor(e,t,i=new ne){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.debug(`[domain:list] Listing data domain files for org: ${e}, parent: ${this.options.parent||"root"}`);try{let t=await this.fileManager.list(e,{kind:"domain",parent:this.options.parent});b.debug(`[domain:list] Found ${t.length} domain 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=F(t);this.formatter.error(i),process.exit(1)}}};var ha=class extends He{constructor(e,t,i=new ne){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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 je("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!==Re&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${s.kind}', but expected '${Re}'.`}),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=F(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var fa=class extends He{constructor(e,t,i=new ne){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;b.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){b.debug(`[domain:read] Fetching media schema for domain file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;b.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{b.debug(`[domain:read] Fetching metadata for domain file ID '${i}'...`);let r=await this.fileManager.read(e,i);b.debug("[domain:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=F(r);this.formatter.error(s),process.exit(1)}}};var Nt;(function(n){n.add="add",n.remove="remove",n.replace="replace",n.copy="copy",n.move="move",n.test="test"})(Nt||(Nt={}));function ga(n,e,t){let i=new ue(e),r=ci(n,i);if(!bt(r,t))throw new ve([{path:i.raw,message:"Test operation failed. The values are not equal."}]);return{doc:n}}var cI=Object.freeze({add:yt,copy:Oi,move:Yi,remove:Rt,replace:Pi,test:ga});function $l(n){return Array.isArray(n)?new Array(n.length).fill(0).map((e,t)=>`${t}`):Object.keys(n)}function wr(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function Sp(n,e,t={}){if(JSON.stringify(n)===JSON.stringify(e))return[];let i=[...n],r=[...e],s=[],a=0,o=0;for(;a<i.length||o<r.length;)if(a>=i.length){let l=t.fixedIndexes?o:-1;s.push({op:"add",index:l,value:r[o]}),o++}else if(o>=r.length)s.push({op:"remove",index:a}),a++;else if(bt(i[a],r[o]))a++,o++;else{let l=-1,c=-1;for(let p=a;p<i.length;p++)if(bt(i[p],r[o])){l=p;break}for(let p=o;p<r.length;p++)if(bt(r[p],i[a])){c=p;break}if(l===-1&&c===-1)s.push({op:"replace",index:o,value:r[o]}),a++,o++;else if(l===-1)s.push({op:"add",index:o,value:r[o]}),o++;else if(c===-1)s.push({op:"remove",index:a}),a++;else{s.push({op:"move",index:o,from:l});let p=i[l];i.splice(l,1),i.splice(a,0,p),a++,o++}}return s.sort((l,c)=>l.op==="remove"&&c.op==="remove"?c.index-l.index:0)}function $o(n,e,t,i=[],r={}){if(n===e)return;if(n==null&&e!==null&&e!==void 0){t.push({op:"replace",path:"",value:e});return}if(e==null&&n!==null&&n!==void 0){t.push({op:"replace",path:"",value:null});return}typeof e.toJSON=="function"&&(e=e.toJSON());let s=Gt(n),a=Gt(e),o=ps(s),l=ps(a);if(o&&l){bt(n,e)||t.push({op:"replace",path:we(i),value:e});return}if(a!==s){t.push({op:s===void 0?"add":"replace",path:we(i),value:e});return}if(s==="array"){let u=n,h=Sp(u,e,r);for(let f of h){let v=f.index===-1?"-":f.index.toString(),w=[...i,v];f.op==="remove"?(r.invertible&&t.push({op:"test",path:we(w),value:wr(u[f.index])}),t.push({op:f.op,path:we(w)})):f.op==="replace"&&typeof f.value=="object"&&f.value!==null?$o(u[f.index],f.value,t,w,r):f.op==="move"?t.push({op:"move",from:we([...i,f.from.toString()]),path:we(w)}):t.push({op:f.op,path:we(w),value:f.value})}return}let c=$l(e),p=$l(n);for(let u of c){let m=n[u],h=e[u];Object.prototype.hasOwnProperty.call(n,u)?typeof m=="object"&&m!=null&&typeof h=="object"&&h!==null&&Array.isArray(m)===Array.isArray(h)?$o(m,h,t,[...i,u],r):bt(m,h)||(r.invertible&&t.push({op:"test",path:we([...i,u]),value:wr(m)}),t.push({op:"replace",path:we([...i,u]),value:wr(h)})):t.push({op:"add",path:we([...i,u]),value:wr(h)})}for(let u of p)Object.prototype.hasOwnProperty.call(e,u)||(r.invertible&&t.push({op:"test",path:we([...i,u]),value:wr(n[u])}),t.push({op:"remove",path:we([...i,u])}))}function zt(n,e,t){let i=[];return $o(n,e,i,[],t),i}var zi=Object.create(null);zi.add=0;zi.remove=1;zi.replace=2;zi.move=3;zi.copy=4;zi.test=5;var ya=class extends He{constructor(t,i,r,s=new ne,a=new Ot(s)){super(i,r,s,a);this.stateOption=t}stateOption;async execute(){let t=this.resolveOrgId();b.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),a=this.options.ver;if(s.domain.lifecycle==="published"&&r==="draft"&&!a){if(process.stdout.isTTY){let c=s.domain.info.version;a=await je(`Enter new version (current published version is ${c}):`)}a||(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))}b.debug(`[domain:transition] Changing lifecycle state from '${s.domain.lifecycle}' to '${r}'...`),s.domain.changeLifecycle(r,a),this.validateDomain(s.domain);let o=s.domain.toJSON(),l=zt(s.originalSchema,o);if(l.length===0){b.debug("[domain:transition] No changes in domain lifecycle detected."),this.formatter.success(`Data domain is already in '${r}' state.`);return}try{let c=await this.fileManager.patchMedia(t,i,{patchOps:l,version:s.metaVersion});b.debug(`[domain:transition] Patch applied successfully. New file version: ${c.newVersion}`),this.formatter.success(`Successfully transitioned data domain state to '${r}' (new file version: ${c.newVersion}).`,{fileId:i,state:r,version:s.domain.info.version,fileVersion:c.newVersion})}catch(c){let p=F(c);this.formatter.error(p),process.exit(1)}}async resolveTargetState(){let t=this.stateOption,i=["draft","committed","published"];return!t&&process.stdout.isTTY&&(t=await Xe("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 ba=class extends He{client=G();constructor(e,t,i=new ne,r=new Ot(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 a=await this.patchDomainMedia(e,t,i.domain,i.originalSchema,i.metaVersion),o=await this.publishToCatalog(s,r);this.reportSuccess(s,o,a)}async checkPublicationStatus(e,t){b.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 b.debug(`[domain:publish] Domain already published. Catalog key: ${i.key}`),i}catch(i){let r=F(i);if(r.status===404)return b.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 je("Enter semantic version:",h)}let a=s||e.info.version||"1.0.0",o=this.options.scope;!o&&process.stdout.isTTY&&(o=await Xe("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),o||(o="public");let l=["public","organization","private"];l.includes(o)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${o}'.`,detail:`Allowed: ${l.join(", ")}`}),process.exit(1));let c=["dev","beta","stable"];c.includes(this.options.lifecycle)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${this.options.lifecycle}'.`,detail:`Allowed: ${c.join(", ")}`}),process.exit(1));let p=this.options.lifecycle,u=this.options.name,m=this.options.description;return t?(u=u||t.name||e.info.name||"",m=m||t.description||e.info.description||""):(!u&&e.info.name&&(u=e.info.name),!u&&process.stdout.isTTY&&(u=await je("Enter catalog entry name:",e.info.name||"")),u||(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 je("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:a,scope:o,lifecycle:p,name:u,description:m,changelog:this.options.changelog||void 0}}prepareDomainLifecycle(e,t){b.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 a=i.toJSON(),o=zt(r,a);if(o.length===0)return b.debug("[domain:publish] No changes in domain schema detected, skipping patch."),s;b.debug(`[domain:publish] Sending patch request (${o.length} ops) to file media...`);try{let l=await this.fileManager.patchMedia(e,t,{patchOps:o,version:s});return b.debug(`[domain:publish] File media patched. New file version: ${l.newVersion}`),l.newVersion}catch(l){let c=F(l);this.formatter.error(c),process.exit(1)}}async publishToCatalog(e,t){let i;if(t)i=t.key,b.debug(`[domain:publish] Using existing catalog entry key: ${i}`);else{b.debug("[domain:publish] Publishing new data catalog entry...");let s={key:"",kind:ct,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,b.debug(`[domain:publish] Created catalog entry key: ${i}`)}catch(a){let o=F(a);this.formatter.error(o),process.exit(1)}}let r=li.createSchema({scope:e.scope,lifecycle:e.lifecycle,version:e.version,changelog:e.changelog||void 0});b.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 b.debug(`[domain:publish] Version published successfully with key: ${s.key}`),{catalogKey:i,versionKey:s.key,version:e.version}}catch(s){let a=F(s);this.formatter.error(a),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 ka=class extends He{constructor(t,i,r,s=new ne,a=new Ot(s)){super(i,r,s,a);this.file=t}file;async execute(){let t=this.resolveOrgId();b.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 a=await this.loadDomain(t,r);this.assertEditableLifecycle(a.domain.lifecycle,r);let o=zt(a.originalSchema,i);if(o.length===0){this.handleNoOp(r,a.metaVersion);return}if(this.options.dryRun){this.handleDryRun(r,o);return}if(!await this.confirmDestructiveChanges(r,o)){console.log(ee.yellow("Mutation cancelled by user."));return}await this.applyPatch(t,r,o,a.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=F(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!==Re&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${i.kind}', but expected '${Re}'.`}),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=F(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){b.debug("[domain:mutate] Running pre-flight local schema validation...");try{let i=new Qe(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){b.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(b.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(ee.cyan(`\u2139 [Dry-run] Computed ${i.length} patch operation(s) for domain '${t}':`));for(let r of i){let s=r.op==="add"?ee.green("+"):r.op==="remove"?ee.red("-"):ee.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 Jr(`This mutation will remove elements from data domain '${t}'. Do you want to proceed?`,!1):!0}async applyPatch(t,i,r,s){try{let a=await this.fileManager.patchMedia(t,i,{patchOps:r,version:s});b.debug(`[domain:mutate] Patch applied successfully. New file version: ${a.newVersion}`),this.formatter.success(`Successfully mutated data domain '${i}' (new file version: ${a.newVersion}, ${r.length} operation(s) applied).`,{fileId:i,fileVersion:a.newVersion,operationsCount:r.length,updated:!0})}catch(a){let o=F(a);this.formatter.error(o),process.exit(1)}}};function jl(n){let e=n.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 Z({format:A.resolved.format});await new ma(t,i).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 Z({format:A.resolved.format});await new ha(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 Z({format:A.resolved.format});await new fa(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 Z({format:A.resolved.format});await new ya(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 Z({format:A.resolved.format});await new ba(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 Z({format:A.resolved.format});await new ka(t,i,r).execute()})}parseInt(process.versions.node.split(".")[0],10)<22&&(console.error("Error: apinow requires Node.js 22 or higher."),process.exit(1));function Rl(){let n=process.argv.indexOf("--format");if(n!==-1&&n+1<process.argv.length&&process.argv[n+1]==="json")return"json";try{return A.resolved.format||"text"}catch{return"text"}}process.on("uncaughtException",n=>{new Z({format:Rl()}).error({code:"CLI_ERR_UNKNOWN",message:n.message||"An unexpected error occurred.",detail:n.stack}),process.exit(1)});process.on("unhandledRejection",n=>{let e=new Z({format:Rl()}),t=n instanceof Error?n.message:String(n),i=n instanceof Error?n.stack:void 0;e.error({code:"CLI_ERR_UNKNOWN",message:`Unhandled promise rejection: ${t}`,detail:i}),process.exit(1)});xp({pkg:Ki}).notify();A.load();var at=new Pp;at.name("apinow").description("API NOW! Platform CLI Tool").version(Ki.version,"--version").option("--format <format>","Output format: text, json","text").option("--debug","Enable debug/verbose logging").option("-v, --verbose","Enable verbose logging");at.hook("preAction",(n,e)=>{let t,i=e;for(;i;){let r=i.opts();r.format&&!t&&(t=r.format),(r.debug||r.verbose)&&To("debug"),i=i.parent}A.saturate({format:t}),b.debug(`Executing command: ${e.name()} with args: ${JSON.stringify(e.args)}`)});Do(at);Vo(at);Fo(at);qo(at);Xo(at);Pl(at);Ol(at);jl(at);function Cl(n){let e=n.options||[];e.some(t=>t.long==="--format")||n.option("--format <format>","Output format: text, json"),e.some(t=>t.long==="--debug")||n.option("--debug","Enable debug/verbose logging"),e.some(t=>t.long==="--verbose")||(n.options.some(i=>i.short==="-v")?n.option("--verbose","Enable verbose logging"):n.option("-v, --verbose","Enable verbose logging"));for(let t of n.commands)Cl(t)}for(let n of at.commands)Cl(n);await at.parseAsync(process.argv);
53
+ `))}function pl(n,e){return vp(n,e),{options:{directed:n.isDirected(),multigraph:n.isMultigraph(),compound:n.isCompound()},nodes:bp(n,e),edges:kp(n,e)}}function ul(n,e){for(let t of n.nodes()){let i=n.node(t);i&&i.domain.key===e&&n.removeNode(t)}}function Na(n,e,t){let i=new Set,r=new Set;for(let o of e.nodes()){let a=e.node(o);if(!a)continue;let l=`${t}:${o}`;n.setNode(l,a),i.add(l)}for(let o of e.edges()){let a=e.edge(o);if(!a)continue;let l=`${t}:${o.v}`,c=`${t}:${o.w}`;n.setEdge(l,c,{foreign:!0,domain:t,...a}),r.add(`${l}|${c}`)}let s=new Set;for(let o of e.nodes()){let a=`${t}:${o}`;for(let l of e.parents(o)){let c=`${t}:${l}`,p=n.node(a),u=n.node(c);p.kind===R&&u.kind===R?s.has(a)?n.addParent(a,c):(s.add(a),n.setParent(a,c)):n.setParent(a,c)}}return{nodes:i,edges:r}}function dl(n,e){for(let t of e)if(t.w===n)return t.v}function wp(n,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===Re)return new Li(n,s);if(s.kind===Oe)return new oi(n,s);if(s.kind===R)return new Di(n,s);if(s.kind===he){let a=s,l=dl(a.key,t);if(!l){let c={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(c),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new ri(n,l,a)}if(s.kind===de){let a=s,l=dl(a.key,t);if(!l){let c={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(c),i==="strict")throw new Error("Unable to restore data domain graph. Malformed node entry");return}return new Ti(n,l,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 ml(n,e={}){let{json:t,dependencies:i,mode:r="strict"}=e,s=new Fs({compound:!0,multigraph:!0,directed:!0}),o=[],a=new Set,l=new Set;if(i)for(let p of i)try{let u=Na(s,p.graph,p.key);u.edges.size&&(l=new Set([...l,...u.edges])),u.nodes.size&&(a=new Set([...a,...u.nodes])),n.dependencies.set(p.key,p)}catch(u){let m=`Failed to merge dependency "${p.key}": ${u instanceof Error?u.message:String(u)}`;if(r==="strict")throw new Error(m,{cause:u});let h={type:"missing_dependency",severity:"error",message:m,affectedKey:p.key,resolution:"Dependency will be skipped"};o.push(h)}if(!t)return{graph:s,issues:o,success:!0};if(Array.isArray(t.nodes)){let p=new Map;for(let u of t.nodes){let m=wp(n,u.value,t.edges,r,o);m&&(s.setNode(u.v,m),u.parents&&p.set(u.v,u.parents))}for(let[u,m]of p){if(!s.hasNode(u)){let h={type:"missing_node",severity:"warning",message:`Cannot set parents for missing node: ${u}`,affectedKey:u,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 "${u}"`,affectedKey:u,context:{parentKey:h},resolution:"Parent relationship will be skipped"};o.push(f);continue}try{s.setParent(u,h)}catch(f){let v={type:"invalid_parent",severity:"warning",message:`Failed to set parent "${h}" for child "${u}": ${f instanceof Error?f.message:String(f)}`,affectedKey:u,context:{parentKey:h},resolution:"Parent relationship will be skipped"};o.push(v)}}}}if(Array.isArray(t.edges))for(let p of t.edges){if(!p.value){let u="Edge entry missing value";if(r==="strict")throw new Error(u);let m={type:"malformed_entry",severity:"error",message:u,context:{edge:p}};o.push(m);continue}if(p.value.foreign&&!a.has(p.w)){let u={type:"missing_node",severity:"warning",message:`Missing foreign node: ${p.w}`,affectedKey:p.w,resolution:"Edge will be skipped"};o.push(u);continue}if(a.has(p.v)||a.has(p.w)){if(!s.hasNode(p.v)||!s.hasNode(p.w)){let u={type:"missing_node",severity:"warning",message:`Missing foreign node for edge: ${p.v} -> ${p.w}`,context:{sourceNode:p.v,targetNode:p.w},resolution:"Edge will be skipped"};o.push(u);continue}}else{if(!s.hasNode(p.v)){let u={type:"missing_node",severity:"warning",message:`Source node not found for edge: ${p.v}`,affectedKey:p.v,resolution:"Edge will be skipped"};o.push(u);continue}if(!s.hasNode(p.w)){let u={type:"missing_node",severity:"warning",message:`Target node not found for edge: ${p.w}`,affectedKey:p.w,resolution:"Edge will be skipped"};o.push(u);continue}}try{s.setEdge({v:p.v,w:p.w,name:p.name},p.value)}catch(u){let h={type:"malformed_entry",severity:"warning",message:`Failed to create edge ${p.v} -> ${p.w}: ${u instanceof Error?u.message:String(u)}`,context:{sourceNode:p.v,targetNode:p.w},resolution:"Edge will be skipped"};o.push(h)}}for(let p of s.nodes()){let u=s.node(p);if(u){if(u.kind===he){let m=u,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(u.kind===de){let m=u,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 c=o.some(p=>p.severity==="error");return{graph:s,issues:o,success:!c}}var zi=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 Qe=class n extends zi{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=Q(),fields:i,lifecycle:r="draft",previousVersion:s}=e,o=pe.fromJSON(e.info,{name:"Unnamed domain"}).toJSON(),a={kind:je,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=n.createSchema(e),s=[];for(let l of t)if(l instanceof n)l.readOnly?s.push(l):(console.warn(`Domain ${l.key} is not read only, cloning it. This may have performance implications.`),s.push(l.clone({readOnly:!0})));else if(typeof l=="object"&&l.kind===je&&l.key){let c=new n(l,void 0,{readOnly:!0});s.push(c)}else throw new Error(`Invalid foreign domain dependency: ${l}`);super(r.dependencyList,s),this.kind=r.kind,this.key=r.key,this.info=new pe(r.info),this.readOnly=i?.readOnly||!1,this.lifecycle=r.lifecycle||"draft",this.previousVersion=r.previousVersion;let o=i?.mode||"strict",a=ml(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 n(t,i,r)}toJSON(){let e={info:this.info.toJSON(),kind:this.kind,key:this.key,graph:pl(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===Re||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!==Re)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 Li(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!==Re)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?(Ue(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!==Re||(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===Re&&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===Re)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 oi(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?(Ue(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}`,l=this.graph.node(a);l&&(yield l)}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 l=`${s}:${a.key}`,c=this.graph.node(l);c&&(yield c)}}*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 l=this.graph.node(a);if(l&&l.kind===R){let c=l.domain.key===this.key;if(i){l.domain.key===i&&(yield l);continue}s?c||(yield l):r?yield l:c&&(yield l)}}}*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===R)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!==de)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===de)return i}getIncomingAssociations(e){let t=[];for(let i of this.graph.inEdges(e)){let r=this.graph.node(i.v);r&&r.kind===de&&t.push(r)}return t}findAssociationBetween(e,t){let i=this.graph.node(e);if(!i||i.kind!==R)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(y.User))return[];for(let s of t.listAssociations())if(s.hasSemantic(y.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(u=>u.hasSemantic(y.CreatedBy)||u.hasSemantic(y.UpdatedBy)||u.hasSemantic(y.DeletedBy)?!1:u.hasSemantic(y.RelationalResourceOwner)||u.hasSemantic(y.ResourceOwnerIdentifier)?!0:u.listTargets().some(m=>m.hasSemantic(y.User))),c=this.getIncomingAssociations(s.key).filter(u=>{if(u.hasSemantic(y.CreatedBy)||u.hasSemantic(y.UpdatedBy)||u.hasSemantic(y.DeletedBy))return!1;let m=u.getParentInstance();return m?m.hasSemantic(y.User)||u.schema?.embedded===!0:!1}),p=[...a,...c];for(let u of p){let m=u.getParentInstance();if(!m)continue;let h=[...u.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 v=this.findEntity(k);if(!v)continue;let E=[...s.path,u];if(v.hasSemantic(y.User)||u.hasSemantic(y.ResourceOwnerIdentifier))return E;r.add(k),i.push({key:k,path:E})}}}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!==he)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===he)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}),Na(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),ul(this.graph,t.key)}removeDomainElement(e,t){switch(t){case Re:this.removeNamespace(e);break;case Oe:this.removeModel(e);break;case R:this.removeEntity(e);break;case he:this.removeProperty(e);break;case de: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),l=m=>!i||i.length===0?!0:i.includes(m),c=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)},p=m=>{if(!t)return[];let h=[],{info:f}=m;return c(f.name)&&h.push("name"),c(f.displayName)&&h.push("displayName"),c(f.description)&&h.push("description"),h},u=m=>m.includes(":");for(let m of this.graph.nodes()){let h=this.graph.node(m);if(!h||!h.info)continue;let f=u(m);if(f&&!r||!l(h.kind))continue;if(a){o.push({node:h,matchedFields:[],key:m,isForeign:f});continue}let k=p(h);(!t||k.length>0)&&o.push({node:h,matchedFields:k,key:m,isForeign:f})}return o}};var Ks=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","COMMIT","ROLLBACK","SAVEPOINT","BEGIN","END","CASE","WHEN","THEN","ELSE","END CASE","EXCEPTION","RAISE","RETURN","FUNCTION","PROCEDURE"]);function qs(n){let e=[],t=n.info.getLabel(),i=n.getParentInstance();if(!i)return e;let r;if(i.kind===R)r=i.key;else{let a=i.getParentInstance();if(!a)return e;r=a.key}let s=n.kind===he?"property":"association";if(!n.info.name){let a=`The "${t}" ${s} has no name.`,l=`The ${s} must have a name.`;return e.push({field:"name",rule:"required",message:a,help:l,severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}}),e}let o=n.info.name;if(o.length<2){let a=`The "${t}" ${s} name is too short.`;e.push({field:"name",rule:"length",message:a,help:"The name must be at least 2 characters long.",severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(o.length>59){let a=`The "${t}" ${s} name is too long.`;e.push({field:"name",rule:"length",message:a,help:"The name must be at most 59 characters long.",severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){let a=`The "${t}" ${s} name is invalid.`;e.push({field:"name",rule:"format",message:a,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:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(/^[A-Z]/.test(o)){let a=`The "${t}" ${s} name is not in snake case.`;e.push({field:"name",rule:"snake_case",message:a,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}if(Ks.has(o.toUpperCase())){let a=`The "${t}" ${s} name is a reserved keyword.`;e.push({field:"name",rule:"reserved",message:a,help:"The name should not be a reserved keyword.",severity:"error",key:n.key,kind:n.kind,parent:i.key,parentKind:i.kind,...r?{entityKey:r}:{}})}return e}var Js=class{domain;constructor(e){this.domain=e}validate(e){let t=[],i;if(typeof e=="string"?i=this.domain.findAssociation(e):i=e,!i){let a=`The "${e}" association does not exist.`;return t.push({field:"*",rule:"exists",message:a,help:"The association must be defined in the domain.",key:e,kind:de,severity:"error",parentKind:R}),t}let r=this.validateName(i);t.push(...r);let s=this.validateTargets(i);t.push(...s);let o=this.validateSemantics(i);return t.push(...o),t}validateName(e){return qs(e)}validateTargets(e){let t=[],i=e.info.getLabel(),r=e.getParentInstance();if(!e.targets.length){let s=`The "${i}" association has no target.`;return t.push({field:"targets",rule:"required",message:s,help:"An association must have at least one target.",severity:"error",key:e.key,kind:e.kind,parent:r.key,parentKind:R}),t}for(let s of e.targets)if(!this.domain.findEntity(s.key,s.domain)){let a=`The "${i}" association has an invalid target "${s.key}".`;t.push({field:"targets",rule:"exists",message:a,help:"The target must be defined in the domain.",severity:"error",key:e.key,kind:e.kind,parent:r.key,parentKind:R})}return t}validateSemantics(e){let t=[],i=e.info.getLabel(),r=e.getParentInstance();if(e.hasSemantic(y.RelationalResourceOwner))for(let s of e.targets){let o=this.domain.findEntity(s.key,s.domain);o&&this.domain.resolveOwnershipPath(o.key)===null&&t.push({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:R})}return t}};var Bs=class{domain;constructor(e){this.domain=e}validate(e){let t=[],i;if(typeof e=="string"?i=this.domain.findEntity(e):i=e,!i){let c=`The "${e}" entity does not exist.`;return t.push({field:"*",rule:"exists",message:c,help:"The entity must be defined in the domain.",key:e,kind:R,severity:"error",parentKind:R}),t}let r=this.validatePrimaryKey(i);t.push(...r);let s=this.minimumRequiredProperties(i);t.push(...s);let o=this.validateName(i);t.push(...o);let a=this.uniqueName(i);t.push(...a);let l=this.validateUserSemantics(i);return t.push(...l),t}validatePrimaryKey(e){let t=[];if(!e.primaryKey()){let r=`The "${e.info.getLabel()}" entity has no identifier.`;t.push({field:"properties",rule:"primary_key",message:r,help:"An entity that can exists by itself must have identifier defined.",severity:"error",key:e.key,kind:e.kind,parentKind:R})}return t}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){let t=[],i=this.hasPropertiesInherited(e),r=this.hasAssociationsInherited(e);if(!i&&!r){let s=`The "${e.info.getLabel()}" entity has no properties. It will be ignored.`;t.push({field:"properties",rule:"required",message:s,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:R})}return t}validateName(e){let t=[],i=e.info.getLabel();if(!e.info.name){let s=`The "${i}" entity has no name.`;return t.push({field:"name",rule:"required",message:s,help:"An entity must have a name.",severity:"error",key:e.key,kind:e.kind,parentKind:R}),t}let r=e.info.name;if(r.length<2){let s=`The "${i}" entity name is too short.`;t.push({field:"name",rule:"length",message:s,help:"The name must be at least 2 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:R})}if(r.length>31){let s=`The "${i}" entity name is too long.`;t.push({field:"name",rule:"length",message:s,help:"The name must be at most 31 characters long.",severity:"error",key:e.key,kind:e.kind,parentKind:R})}if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(r)){let s=`The "${i}" entity name is invalid.`;t.push({field:"name",rule:"format",message:s,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:R})}if(/^[A-Z]/.test(r)){let s=`The "${i}" entity name is not in snake case.`;t.push({field:"name",rule:"snake_case",message:s,help:"The name should be in snake case (lowercase letters and underscores).",severity:"info",key:e.key,kind:e.kind,parentKind:R})}if(Ks.has(r.toUpperCase())){let s=`The "${i}" entity name is a reserved keyword.`;t.push({field:"name",rule:"reserved",message:s,help:"The name should not be a reserved keyword.",severity:"error",key:e.key,kind:e.kind,parentKind:R})}return t}uniqueName(e){let t=[],i=e.info.name?.toLowerCase();if(!i)return t;for(let r of this.domain.listEntities())if(r.info.name?.toLowerCase()===i&&r.key!==e.key){let s=`The "${i}" entity name is already used in the data domain.`;t.push({field:"name",rule:"unique",message:s,help:"The name must be unique. This includes references to other data domains.",severity:"error",key:r.key,kind:r.kind,parentKind:R})}for(let r of this.domain.listEntities({foreignOnly:!0}))if(r.info.name?.toLowerCase()===i&&r.key!==e.key){let s=`The "${i}" entity name is already used in the foreign data domain.`;t.push({field:"name",rule:"unique",message:s,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:R})}return t}validateUserSemantics(e){let t=[],i=!1,r=!1;for(let s of e.withInheritedProperties())s.hasSemantic(y.Username)&&(i=!0),s.hasSemantic(y.Password)&&(r=!0);if((i||r)&&!e.hasSemantic(y.User)){let s=`The "${e.info.getLabel()}" entity has Username or Password properties but does not have the User taxonomy.`;t.push({field:"semantics",rule:"user_taxonomy_required",message:s,help:"Entities containing authentication credentials like usernames or passwords must be tagged with the User taxonomy.",severity:"error",key:e.key,kind:e.kind,parentKind:R})}if(r&&!i){let s=`The "${e.info.getLabel()}" entity has Password credentials but lacks Username semantics.`;t.push({field:"semantics",rule:"username_required_for_password",message:s,help:"An entity with Password credentials must also define a Username property for authentication.",severity:"error",key:e.key,kind:e.kind,parentKind:R})}return t}};function xt(n,e){let t=n;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 Gs=class{domain;constructor(e){this.domain=e}validate(e){let t=[],i;if(typeof e=="string"?i=this.domain.findProperty(e):i=e,!i){let l=`The "${e}" property does not exist.`;return t.push({field:"*",rule:"exists",message:l,help:"The property must be defined in the domain.",key:e,kind:he,severity:"error",parentKind:R}),t}let r=this.validateName(i);t.push(...r);let s=this.validatePrimaryKeyDefault(i);t.push(...s);let o=this.validateJsonIndex(i);t.push(...o);let a=this.validateSchema(i);return t.push(...a),t}validateName(e){return qs(e)}validatePrimaryKeyDefault(e){let t=[];if(e.primary){let i=e.getParentInstance();if(!i)return t;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.push({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.`;t.push({field:"schema.defaultValue",rule:"primary_key_no_default",message:s,help:'Without a default generator (e.g., the "random" function), the client application must generate and supply primary key values manually.',severity:"warning",key:e.key,kind:e.kind,parentKind:i.kind})}}return t}validateJsonIndex(e){let t=[],i=e.jsonIndex;if(!i)return t;let r=e.getParentInstance();if(!r)return t;if(e.type!=="json")return t.push({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}),t;if(i.paths&&e.jsonSchema)for(let s of i.paths){if(!s.path){t.push({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(".");xt(e.jsonSchema,o)||t.push({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})}return t}validateSchema(e){let t=[],i=e.schema;if(!i)return t;let r=e.getParentInstance();if(!r)return t;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",l=e.info.getLabel();return t.push({field:a,rule:"schema_boundary_unsupported_type",message:`The property "${l}" 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}),t}let o=!1;if(i.minimum!==void 0){let a=this.validateBoundaryValue(e,"minimum",i.minimum,r.kind);a&&(o=!0,t.push(a))}if(i.maximum!==void 0){let a=this.validateBoundaryValue(e,"maximum",i.maximum,r.kind);a&&(o=!0,t.push(a))}if(!o&&i.minimum!==void 0&&i.maximum!==void 0){let a=this.validateBoundaryRange(e,r.kind);a&&t.push(a)}return t}validateBoundaryRange(e,t){let{schema:i,type:r}=e;if(!i||i.minimum===void 0||i.maximum===void 0)return;let{minimum:s,maximum:o,exclusiveMinimum:a,exclusiveMaximum:l}=i,c=e.info.getLabel();if(r==="number"||r==="string"){if(typeof s!="number"||typeof o!="number")return;if(s>o)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum value (${s}) greater than its maximum value (${o}).`,help:"The minimum constraint must be less than or equal to the maximum constraint.",severity:"error",key:e.key,kind:e.kind,parentKind:t};if(s===o&&(a||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} to ${o}).`,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(r==="date"){if(typeof s!="string"||typeof o!="string"||!this.isValidIsoDate(s)||!this.isValidIsoDate(o))return;if(s>o)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum date (${s}) later than its maximum date (${o}).`,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};if(s===o&&(a||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} to ${o}).`,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(r==="datetime"){if(typeof s!="string"||typeof o!="string"||!this.isValidIsoDateTime(s)||!this.isValidIsoDateTime(o))return;let p=Date.parse(s),u=Date.parse(o);if(p>u)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum datetime (${s}) later than its maximum datetime (${o}).`,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};if(p===u&&(a||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} to ${o}).`,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(r==="time"){if(typeof s!="string"||typeof o!="string"||!this.isValidIsoTime(s)||!this.isValidIsoTime(o))return;let p=this.isoTimeToSeconds(s),u=this.isoTimeToSeconds(o);if(p>u)return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has a minimum time (${s}) later than its maximum time (${o}).`,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};if(p===u&&(a||l))return{field:"schema.minimum",rule:"schema_boundary_range",message:`The property "${c}" has exclusive boundaries that result in an empty range (${s} to ${o}).`,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){let{type:s}=e,o=e.info.getLabel(),a=t==="minimum"?"schema_minimum_type":"schema_maximum_type",l=`schema.${t}`;if(s==="number"){if(typeof i!="number")return{field:l,rule:a,message:`The property "${o}" 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}}else if(s==="string"){if(typeof i!="number"||!Number.isInteger(i)||i<0)return{field:l,rule:a,message:`The property "${o}" 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}}else if(s==="date"){if(!this.isValidIsoDate(i))return{field:l,rule:a,message:`The property "${o}" 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}}else if(s==="datetime"){if(!this.isValidIsoDateTime(i))return{field:l,rule:a,message:`The property "${o}" 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}}else if(s==="time"&&!this.isValidIsoTime(i))return{field:l,rule:a,message:`The property "${o}" 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}}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,l=(Number(t[4])*3600+Number(t[5])*60)*a;o-=l}return o}};var Hs=class{domain;constructor(e){this.domain=e}validate(){let e=[],t=this.validateUserEntity();e.push(...t);let i=this.validateTimestampSemantics();e.push(...i);let r=this.validateSoftDeleteSemantics();e.push(...r);let s=this.validatePropertySemanticsDataTypes();e.push(...s);let o=this.validateCurrencySemantics();e.push(...o);let a=this.validateGeospatialEndpoints();e.push(...a);let l=this.validateOrganizationSemantics();e.push(...l);let c=this.validateProjectSemantics();e.push(...c);let p=this.validateAssociationSemanticsPreconditions();return e.push(...p),e}validateUserEntity(){let e=[],t=0;for(let i of this.domain.listEntities())if(i.hasSemantic(y.User)){t++;let r=!1,s=!1,o=!1;for(let a of i.withInheritedProperties())if(a.hasSemantic(y.Username)&&(r=!0),a.hasSemantic(y.Password)&&(s=!0),a.hasSemantic(y.UserRole)&&(o=!0),r&&s&&o)break;r||e.push({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:R,parentKind:R}),s||e.push({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:R,parentKind:R}),o||e.push({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:R,parentKind:R})}return t===0?e.push({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:R,parentKind:R}):t>1&&e.push({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:R,parentKind:R}),e}validateTimestampSemantics(){let e=[];for(let t of this.domain.listEntities()){let i=!1,r=!1;for(let s of t.withInheritedProperties())s.hasSemantic(y.CreatedTimestamp)&&(i=!0),s.hasSemantic(y.UpdatedTimestamp)&&(r=!0);i||e.push({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}),r||e.push({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:R})}return e}validateSoftDeleteSemantics(){let e=[];for(let t of this.domain.listEntities()){let i=!1;for(let r of t.withInheritedProperties())if(r.hasSemantic(y.DeletedTimestamp)||r.hasSemantic(y.DeletedFlag)){i=!0;break}i||e.push({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:R})}return e}validatePropertySemanticsDataTypes(){let e=[];for(let t of this.domain.listEntities())for(let i of t.withInheritedProperties())for(let r of i.semantics){let s=dt[r.id];ps(s)&&s.applicableDataTypes&&(s.applicableDataTypes.includes(i.type)||e.push({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:R}))}return e}validateCurrencySemantics(){let e=[];for(let t of this.domain.listEntities())for(let i of t.withInheritedProperties()){let r=i.getSemantic(y.Currency);if(r){let s=r.config;i.type==="number"&&s?.allowedCurrencies&&s.allowedCurrencies.length>1&&e.push({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:t.key,parentKind:R})}}return e}validateGeospatialEndpoints(){let e=[];for(let t of this.domain.listEntities()){let i=new Map;for(let r of t.withInheritedProperties()){let s=r.getSemantic(y.GeospatialCoordinates);if(s){let o=s.config??{},a=!!o.enableDistanceQueries,l=!!o.enableBoundingBoxQueries,c=!!o.enablePolygonQueries,p=!!o.enableGeoClustering;if(a||l||c||p){let u=(o.apiEndpointPrefix||"/nearby").trim().toLowerCase();i.has(u)||i.set(u,[]),i.get(u)?.push(r.info.getLabel())}}}for(let[r,s]of i.entries())s.length>1&&e.push({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:R})}return e}validateOrganizationSemantics(){let e=[],t=Array.from(this.domain.listEntities()).filter(c=>c.hasSemantic(y.Organization));if(t.length===0)return e;t.length>1&&e.push({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:R,parentKind:R});let i=t[0],r=Array.from(this.domain.listEntities()).find(c=>c.hasSemantic(y.User));if(!r)return e.push({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:R,parentKind:R}),e;let s=Array.from(i.withInheritedAssociations()).find(c=>c.hasSemantic(y.OrganizationMembers)),o=Array.from(r.withInheritedAssociations()).find(c=>c.hasSemantic(y.OrganizationMembers));!s&&!o&&e.push({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:R,parentKind:R}),s&&(s.targets.length===1&&s.targets[0].key===r.key||e.push({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:R})),o&&(o.targets.length===1&&o.targets[0].key===i.key||e.push({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:R}));let a=[s,o].filter(Boolean);a.length>0&&e.push(...this.validateBiDirectionalSemanticLinks(y.OrganizationMembers,"organization_members",a));let l=a.find(c=>!c.getSemantic(y.OrganizationMembers)?.link);if(l){e.push(...this.validateAssociationPropertyCollisions("organization_members",l));let c=l.getParentInstance(),p=Array.from(l.listProperties()).filter(u=>u.hasSemantic(y.OrganizationRole)||u.hasSemantic(y.AssociationRole));if(p.length===0)e.push({field:"semantics",rule:"organization_role_missing",message:`Association "${l.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${c?.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:l.key,kind:l.kind,parent:c?.key,parentKind:R});else if(p.length>1)e.push({field:"semantics",rule:"organization_role_multiple",message:`Association "${l.info.getLabel()}" marked with Semantic#OrganizationMembers on entity "${c?.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:l.key,kind:l.kind,parent:c?.key,parentKind:R});else{let u=p[0],m=u.schema?.enum;(!m||!Array.isArray(m)||m.length===0)&&e.push({field:"semantics",rule:"organization_role_enum_missing",message:`The organization role property "${u.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 OrganizationRole property to set valid roles.",severity:"warning",key:u.key,kind:u.kind,parent:l.key,parentKind:de})}}return e}validateProjectSemantics(){let e=[],t=Array.from(this.domain.listEntities()).filter(s=>s.hasSemantic(y.Project));if(t.length===0)return e;t.length>1&&e.push({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:R,parentKind:R});let i=Array.from(this.domain.listEntities()).find(s=>s.hasSemantic(y.User)),r=i?Array.from(i.withInheritedAssociations()).filter(s=>s.hasSemantic(y.ProjectMembers)):[];for(let s of r)s.targets.length===1&&t.some(a=>a.key===s.targets[0].key)||e.push({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:R});for(let s of t){let o=Array.from(s.withInheritedAssociations()).find(p=>p.hasSemantic(y.ProjectMembers)),a=r.find(p=>p.targets.some(u=>u.key===s.key));o&&(i&&o.targets.length===1&&o.targets[0].key===i?.key||e.push({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:R}));let l=[o,a].filter(Boolean),c=l.find(p=>!p.getSemantic(y.ProjectMembers)?.link);if(c){e.push(...this.validateAssociationPropertyCollisions("project_members",c));let p=c.getParentInstance(),u=Array.from(c.listProperties()).filter(m=>m.hasSemantic(y.ProjectRole)||m.hasSemantic(y.AssociationRole));if(u.length===0)e.push({field:"semantics",rule:"project_role_missing",message:`Association "${c.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${p?.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:c.key,kind:c.kind,parent:p?.key,parentKind:R});else if(u.length>1)e.push({field:"semantics",rule:"project_role_multiple",message:`Association "${c.info.getLabel()}" marked with Semantic#ProjectMembers on entity "${p?.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:c.key,kind:c.kind,parent:p?.key,parentKind:R});else{let m=u[0],h=m.schema?.enum;(!h||!Array.isArray(h)||h.length===0)&&e.push({field:"semantics",rule:"project_role_enum_missing",message:`The project role property "${m.info.getLabel()}" on association "${c.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:c.key,parentKind:de})}}l.length>0&&e.push(...this.validateBiDirectionalSemanticLinks(y.ProjectMembers,"project_members",l))}return e}validateAssociationPropertyCollisions(e,t){let i=[],r=t.getParentInstance();if(!r)return i;let s=Array.from(t.listTargets()),o=[r,...s];for(let a of t.listProperties()){let l=a.info.name;for(let c of o)Array.from(c.withInheritedProperties()).find(u=>u.info.name===l)&&i.push({field:"properties",rule:`${e}_property_collision`,message:`Property "${l}" on association "${t.info.getLabel()}" collides with a property of the same name on entity "${c.info.getLabel()}".`,help:`Rename the property "${l}" on the association to avoid conflicts when joining tables in the API (e.g., use a prefix like "${e.split("_")[0]}_${l}").`,severity:"error",key:a.key,kind:a.kind,parent:t.key,parentKind:de})}return i}validateBiDirectionalSemanticLinks(e,t,i){let r=[],s=[],o=[];for(let a of i){let l=a.getSemantic(e);if(l)if(l.link){o.push(a),l.config&&Object.keys(l.config).length>0&&r.push({field:"semantics",rule:"semantic_link_config_forbidden",message:`The association "${a.info.getLabel()}" has a semantic link set for "${e}", 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:a.key,kind:a.kind,parent:a.getParentInstance()?.key,parentKind:R});let c=this.domain.findAssociation(l.link.key,l.link.domain);if(!c)r.push({field:"semantics",rule:"semantic_link_target_not_found",message:`The association "${a.info.getLabel()}" has a semantic link targeting "${l.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:a.key,kind:a.kind,parent:a.getParentInstance()?.key,parentKind:R});else{let p=c.getSemantic(e);p?p.link&&r.push({field:"semantics",rule:"semantic_link_target_is_link",message:`The association "${a.info.getLabel()}" links to "${c.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:a.key,kind:a.kind,parent:a.getParentInstance()?.key,parentKind:R}):r.push({field:"semantics",rule:"semantic_link_target_invalid",message:`The association "${a.info.getLabel()}" links to "${c.info.getLabel()}", but the target association does not have the "${e}" semantic.`,help:`Ensure the target association has the "${e}" semantic applied.`,severity:"error",key:a.key,kind:a.kind,parent:a.getParentInstance()?.key,parentKind:R})}}else s.push(a)}if(i.length>1){if(s.length===0)r.push({field:"semantics",rule:"semantic_link_primary_missing",message:`All associations with the "${e}" 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:o[0].key,kind:o[0].kind,parent:o[0].getParentInstance()?.key,parentKind:R});else if(s.length>1)for(let a=1;a<s.length;a++){let l=s[a];r.push({field:"semantics",rule:`${t}_link_required`,message:`Multiple associations have the "${e}" semantic, but "${l.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:l.key,kind:l.kind,parent:l.getParentInstance()?.key,parentKind:R})}}return r}validateAssociationSemanticsPreconditions(){let e=[];for(let t of this.domain.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.push({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:R})}return e}};var Vi=class{domain;report=[];#e=0;#t=0;#i=0;#r=!1;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.domain=e}validate(){this.#r=!1,this.report=[];let e=new Bs(this.domain),t=new Gs(this.domain),i=new Js(this.domain),r=new Hs(this.domain),s=!1;for(let a of this.domain.listEntities()){if(a.domain.key!==this.domain.key)continue;s=!0;let l=e.validate(a);this.report.push(...l);for(let c of a.properties){if(c.domain.key!==this.domain.key)continue;let p=t.validate(c);this.report.push(...p)}for(let c of a.associations){if(c.domain.key!==this.domain.key)continue;let p=i.validate(c);this.report.push(...p)}}if(!s)return this.report;let o=r.validate();return this.report.push(...o),this.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 $a=[],Ra=[],hl={},gr={},yr={};function fl(n){return typeof n=="string"?new RegExp("^"+n+"$","i"):n}function Ws(n,e){return n===e?e:n===n.toLowerCase()?e.toLowerCase():n===n.toUpperCase()?e.toUpperCase():n[0]===n[0].toUpperCase()?e.charAt(0).toUpperCase()+e.slice(1).toLowerCase():e.toLowerCase()}function Sp(n,e){return n.replace(/\$(\d{1,2})/g,function(t,i){return e[i]||""})}function Ap(n,e){return n.replace(e[0],function(t,i){let r=Sp(e[1],arguments);return Ws(t===""?n[i-1]:t,r)})}function gl(n,e,t){if(!n.length||Object.hasOwn(hl,n))return e;let i=t.length;for(;i--;){let r=t[i];if(r[0].test(e))return Ap(e,r)}return e}function yl(n,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?Ws(i,r):Object.prototype.hasOwnProperty.call(n,r)?Ws(i,n[r]):gl(r,i,t)}}function bl(n,e,t){return function(i){let r=i.toLowerCase();return Object.prototype.hasOwnProperty.call(e,r)?!0:Object.prototype.hasOwnProperty.call(n,r)?!1:gl(r,r,t)===r}}var De=function(n,e,t){let i=e===1?De.singular(n):De.plural(n);return(t?e+" ":"")+i};De.plural=yl(yr,gr,$a);De.isPlural=bl(yr,gr,$a);De.singular=yl(gr,yr,Ra);De.isSingular=bl(gr,yr,Ra);De.addPluralRule=function(n,e){$a.push([fl(n),e])};De.addSingularRule=function(n,e){Ra.push([fl(n),e])};De.addUncountableRule=function(n){if(typeof n=="string"){hl[n.toLowerCase()]=!0;return}De.addPluralRule(n,"$0"),De.addSingularRule(n,"$0")};De.addIrregularRule=function(n,e){e=e.toLowerCase(),n=n.toLowerCase(),yr[n]=e,gr[e]=n};[["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(n){De.addIrregularRule(n[0],n[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(n){De.addPluralRule(n[0],n[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(n){De.addSingularRule(n[0],n[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(De.addUncountableRule);var Xs=De;function Ot(n,e){let t=n.domain||e;return t?`${t}:${n.key}`:n.key}function br(n){if(!n)throw new g("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=n.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 g(`Cannot generate a valid parameter name from "${n}".`,{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 l=o.toLowerCase();return a===0?l:l.charAt(0).toUpperCase()+l.slice(1)}).join("");return/^[0-9]/.test(s)&&(s="_"+s),`${s}Id`}function ai(n){let e=n.trim(),t=e.startsWith("/")?e:`/${e}`;return t==="/"?"/":t.replace(/\/+$/,"")}function Ys(n,e){let t=n.endsWith("/")?n.slice(0,-1):n,i=e.startsWith("/")?e:`/${e}`;return`${t}${i}`}var A;(function(n){n.PRE_FETCH="pre-fetch",n.FETCH="fetch",n.POST_FETCH="post-fetch"})(A||(A={}));var ge=class{type;parent;isIdentityConstraining=!1;isBroadIdentityRule=!1;#e;get metadata(){if(!this.#e)throw new Error("Metadata not set for access rule "+this.type);return this.#e}constructor(e,t,i={}){this.parent=e,this.type=i.type??"",this.#e={...t,...i.metadata}}toJSON(){let e={type:this.type};return this.#e&&(e.metadata=this.#e),e}};var kr=class n{description;key;rate;interval;burst;constructor(e={}){this.description=e.description,this.key=n.isRateLimitRuleKey(e.key)?structuredClone(e.key):void 0,this.rate=typeof e.rate=="number"?e.rate:void 0,this.interval=n.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),n.isRateLimitRuleKey(this.key)&&(e.key=structuredClone(this.key)),typeof this.rate=="number"&&(e.rate=this.rate),n.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 Mt=class{rules;constructor(e={}){this.rules=e.rules?.map(t=>new kr(t))||[]}toJSON(){return{rules:this.rules.map(e=>e.toJSON())}}};var yi=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,{list:A.PRE_FETCH,create:A.PRE_FETCH,search:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.PRE_FETCH},t),this.type="allowAuthenticated"}};var Zs=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!0;constructor(e,t={}){super(e,{list:A.PRE_FETCH,create:A.PRE_FETCH,search:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.PRE_FETCH},t),this.type="allowPublic"}};var Qs=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;domains;requireVerified;constructor(e,t={}){super(e,{list:A.PRE_FETCH,create:A.PRE_FETCH,search:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.PRE_FETCH},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 bi=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;target;constructor(e,t={}){super(e,{list:A.FETCH,search:A.FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.FETCH},t),this.type="matchResourceOwner",this.association=t.association?{...t.association}:void 0;let i="association";t.target==="user-entity"?i="user-entity":t.target==="association"&&(i="association"),this.target=i}toJSON(){let e={...super.toJSON(),target:this.target};return this.association&&(e.association={...this.association}),e}};var eo=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;parameters;constructor(e,t={}){super(e,{list:A.PRE_FETCH,search:A.PRE_FETCH,create:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.PRE_FETCH},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 ki=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;attribute;operator;value;values;constructor(e,t={}){super(e,{list:A.FETCH,search:A.FETCH,read:A.POST_FETCH,update:A.POST_FETCH,delete:A.POST_FETCH,link:A.POST_FETCH,unlink:A.POST_FETCH,restore:A.FETCH},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"?n.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?n.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isScalarOperator(e.operator):!1}static assertArray(e){if(!n.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!n.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return n.isArrayOperator(this.operator)}get isScalar(){return n.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 to=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!1;isBroadIdentityRule=!1;allowedStatuses;deniedStatuses;constructor(e,t={}){super(e,{list:A.FETCH,search:A.FETCH,read:A.POST_FETCH,update:A.POST_FETCH,delete:A.POST_FETCH,link:A.POST_FETCH,unlink:A.POST_FETCH,restore:A.FETCH},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 n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;property;operator;value;values;constructor(e,t={}){super(e,{list:A.PRE_FETCH,create:A.PRE_FETCH,search:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.PRE_FETCH},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"?n.isArrayOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isArrayOperator(e.operator):!1}static isScalar(e){return typeof e=="string"?n.isScalarOperator(e):typeof e=="object"&&e!==null&&"operator"in e?n.isScalarOperator(e.operator):!1}static assertArray(e){if(!n.isArray(e))throw new TypeError(`Expected an array operator or rule ('in' | 'notIn'), received: ${JSON.stringify(e)}`)}static assertScalar(e){if(!n.isScalar(e))throw new TypeError(`Expected a scalar operator or rule, received: ${JSON.stringify(e)}`)}get isArray(){return n.isArrayOperator(this.operator)}get isScalar(){return n.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 io=class n extends ge{static allowedLevels=["api","exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;mode;allowed;denied;minimumRole;maximumRole;roleMatch;constructor(e,t={}){super(e,{list:A.PRE_FETCH,create:A.PRE_FETCH,search:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.PRE_FETCH},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 wi=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;isIdentityConstraining=!0;isBroadIdentityRule=!1;roles;constructor(e,t={}){super(e,{list:A.FETCH,search:A.FETCH,create:A.PRE_FETCH,read:A.POST_FETCH,update:A.POST_FETCH,delete:A.POST_FETCH,link:A.POST_FETCH,unlink:A.POST_FETCH,restore:A.FETCH},t),this.roles=Array.isArray(t.roles)?[...t.roles]:typeof t.roles=="string"?[t.roles]:[]}toJSON(){return{...super.toJSON(),roles:[...this.roles]}}};var ro=class n extends wi{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchOrganizationRole"}};var so=class n extends wi{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,t),this.type="matchProjectRole"}};var oo=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;association;allowedRoles;constructor(e,t={}){super(e,{list:A.FETCH,search:A.FETCH,create:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.FETCH},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 ao=class n extends ge{static allowedLevels=["exposure","action"];allowedLevels=n.allowedLevels;type;isIdentityConstraining=!0;isBroadIdentityRule=!1;constructor(e,t={}){super(e,{list:A.FETCH,search:A.FETCH,create:A.PRE_FETCH,read:A.PRE_FETCH,update:A.PRE_FETCH,delete:A.PRE_FETCH,link:A.PRE_FETCH,unlink:A.PRE_FETCH,restore:A.FETCH},t),this.type="relationalResourceOwner"}toJSON(){return{...super.toJSON()}}};function kl(n,e){switch(e.type){case"allowAuthenticated":return new yi(n,e);case"allowPublic":return new Zs(n,e);case"matchEmailDomain":return new Qs(n,e);case"matchResourceOwner":return new bi(n,e);case"relationalResourceOwner":return new ao(n,e);case"matchPathParameter":return new eo(n,e);case"matchResourceAttribute":return new ki(n,e);case"lifecycleStatus":return new to(n,e);case"matchUserProperty":return new vi(n,e);case"matchUserRole":return new io(n,e);case"matchOrganizationRole":return new ro(n,e);case"matchProjectRole":return new so(n,e);case"matchAssociation":return new oo(n,e);default:throw new g("Unknown access rule kind",{code:"E_UNKNOWN_ACCESS_RULE_KIND",status:422})}}var ht=class{key;label;rules;parent;constructor(e,t={}){this.parent=e,this.key=t.key||Q(),t.label!==void 0&&(this.label=t.label),this.rules=Array.isArray(t.rules)?t.rules.map(i=>kl(this.parent,i)):[]}toJSON(){let e={key:this.key,rules:this.rules.map(t=>t.toJSON())};return this.label!==void 0&&this.label!==""&&(e.label=this.label),e}};var Ie=class{kind;accessScenarios;overrideParentScenarios;rateLimiting;projection;parent;constructor(e,t={}){this.kind=t.kind??"",this.accessScenarios=t.accessScenarios?t.accessScenarios.map(i=>new ht(this,i)):[],this.overrideParentScenarios=t.overrideParentScenarios??!1,t.rateLimiting&&(this.rateLimiting=new Mt(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 vr=class extends Ie{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 ni=class extends Ie{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 Lt=class extends Ie{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 Si=class extends Ie{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 Ut=class extends Ie{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 Ai=class extends Ie{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 wr=class extends Ie{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 Sr=class extends Ie{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 _i=class extends Ie{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 ja(n,e){switch(e.kind){case"list":return new Lt(n,e);case"read":return new Si(n,e);case"create":return new vr(n,e);case"update":return new Ai(n,e);case"delete":return new ni(n,e);case"search":return new Ut(n,e);case"link":return new wr(n,e);case"unlink":return new Sr(n,e);case"restore":return new _i(n,e);default:throw new g("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}function vl(n,e){switch(e){case"list":return new Lt(n);case"read":return new Si(n);case"create":return new vr(n);case"update":return new Ai(n);case"delete":return new ni(n);case"search":return new Ut(n);case"link":return new wr(n);case"unlink":return new Sr(n);case"restore":return new _i(n);default:throw new g("Unknown action kind",{code:"E_UNKNOWN_ACTION_KIND",status:422})}}var Fi=class n{kind;key;entity;hasCollection;collectionPath;resourcePath;isRoot;parent;actions;accessScenarios;rateLimiting;paginationContract;truncated;api;static createSchema(e={}){let{key:t=Q(),entity:i={key:""},collectionPath:r,resourcePath:s="/",hasCollection:o=!0,isRoot:a,parent:l,actions:c=[],accessScenarios:p,rateLimiting:u,truncated:m,paginationContract:h}=e,f=!!l?.selfRoute,k={kind:Jt,key:t,entity:{...i},hasCollection:f?!1:o,resourcePath:f?"/me":s,actions:c.map(v=>({...v}))};return!f&&r!==void 0&&(k.collectionPath=r),a!==void 0&&(k.isRoot=f?!1:a),l!==void 0&&(k.parent={key:l.key,...l.association?{association:{...l.association}}:{},...l.selfRoute!==void 0?{selfRoute:l.selfRoute}:{}}),Array.isArray(p)&&(k.accessScenarios=p.map(v=>({...v}))),u!==void 0&&(k.rateLimiting={...u}),m!==void 0&&(k.truncated=m),h!==void 0&&(k.paginationContract=structuredClone(h)),k}constructor(e,t){this.api=e;let i=n.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=>ja(this,r)):[],this.accessScenarios=i.accessScenarios?i.accessScenarios.map(r=>new ht(this,r)):[],i.rateLimiting&&(this.rateLimiting=new Mt(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 g("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 g(`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 g(`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 l=this.resourcePath.split("/").filter(Boolean)[1];l&&/^\{[A-Za-z_][A-Za-z0-9_]*\}$/.test(l)&&(s=l)}if(!s){let a=this.api.domain?.findEntity(this.entity.key,this.entity.domain);if(!a||!a.info.name)throw new g("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=`{${br(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 g("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 g(`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 g(`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 g(`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 g(`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 g(`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 g(`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 g(`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?Ys(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=Ys(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=Ys(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 g(`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 g(`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=ja(this,e);if(this.parent?.selfRoute){let i=new ht(t,{key:`${this.key}-current-user-scenario`,label:"Current User Invariant"});i.rules=[new yi(t),new bi(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 g(`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 g(`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=vl(this,e);if(this.parent?.selfRoute){let i=new ht(t,{key:`${this.key}-current-user-scenario`,label:"Current User Invariant"});i.rules=[new yi(t),new bi(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 g(`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 l=s.getAbsoluteCollectionPath();if(l&&(l===e||l===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 g("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 g(`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 g(`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 g(`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 g(`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 l=s.key,c=o.key,p=a.getParentInstance()?.key,u=p===l||s.listAllParents("up").some(F=>F.key===p),m=a.targets.some(F=>F.key===c||o.listAllParents("up").some(P=>P.key===F.key));if(!u||!m)throw new g(`Association "${t.key}" does not connect parent "${s.info.getLabel()||l}" to "${o.info.getLabel()||c}".`,{code:"E_ASSOCIATION_NOT_FOUND",help:"Ensure there is a defined association in the data domain connecting these entities."});let h=Ot(e,i.key),f=Ot(t,i.key);for(let F of this.api.exposes.values())if(F.parent?.key===r.key&&Ot(F.entity,i.key)===h&&F.parent.association&&Ot(F.parent.association,i.key)===f)throw new g(`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(),v=!!a.multiple,E=v?Xs(k.toLocaleLowerCase()):k.toLocaleLowerCase(),$=br(o.info.name||""),j=v?`/${E}`:void 0,C=v?`/${E}/{${$}}`:`/${E}`;if(v&&j){let F=new Set;for(let O of this.api.exposes.values())O.parent?.key===r.key&&O.hasCollection&&O.collectionPath&&F.add(O.collectionPath);let P=1,w=j;for(;F.has(j);)j=`${w}-${P}`,C=`${j}/{${$}}`,P++}let I=a.namespace&&this.api.domain?.key&&a.namespace!==this.api.domain.key,T={kind:Jt,key:Q(),entity:{...e},actions:[],isRoot:!1,collectionPath:j,resourcePath:"",hasCollection:v,parent:{key:r.key,association:{key:a.key,...I?{domain:a.namespace}:{}}}},U=new n(this.api,T);return U.setResourcePath(C),this.api.exposes.set(U.key,U),this.api.notifyChange(),U}};var Ar=(n={})=>{let e={...no,...n};return n.metadata&&(e.metadata={...n.metadata}),{id:y.Currency,config:e}},no={storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1,validateCurrencyCode:!0},WP={USD_DECIMAL:Ar({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),USD_CENTS:Ar({storageFormat:"integer_cents",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!1}),MULTI_CURRENCY:Ar({storageFormat:"complex_object",allowedCurrencies:["USD","EUR","GBP","JPY","CAD"],decimalPlaces:2,allowNegative:!1}),WITH_NEGATIVES:Ar({storageFormat:"decimal",defaultCurrency:"USD",decimalPlaces:2,allowNegative:!0}),HIGH_PRECISION:Ar({storageFormat:"decimal",defaultCurrency:"BTC",decimalPlaces:8,allowNegative:!1})};var lo={requireVerification:!0,allowSubaddressing:!0,allowInternational:!0};var wl={requireCountryCode:!0,format:"international",allowExtension:!1,requireVerification:!1,verificationMethod:"sms"};var Ca=["allowAuthenticated","allowPublic","matchEmailDomain","matchResourceOwner","relationalResourceOwner","matchPathParameter","matchResourceAttribute","lifecycleStatus","matchUserProperty","matchAssociation","matchProjectRole"],_p={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"],matchResourceOwner:["exposure","action"],relationalResourceOwner:["exposure","action"],matchResourceAttribute:["exposure","action"],matchAssociation:["exposure","action"],matchPathParameter:["exposure","action"],lifecycleStatus:["exposure","action"]};function Sl(n,e){let t;switch(n){case"RBAC":t=[...Ca,"matchUserRole"];break;case"OrganizationRBAC":t=[...Ca,"matchOrganizationRole"];break;case"EnterpriseRBAC":t=[...Ca,"matchUserRole","matchOrganizationRole"];break;default:t=[];break}return e?t.filter(i=>_p[i]?.includes(e)):t}function Pt(n,e){if(e){let t=n.findEntity(e.key,e.domain);return t&&t.hasSemantic(y.User)?t:void 0}for(let t of n.listEntities({includeForeign:!0}))if(t.hasSemantic(y.User))return t}function zt(n,e){let t=e||Pt(n),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(y.UserRole)?(i.roleProperty=r,i.hasRole=!0):r.hasSemantic(y.Username)?(i.usernameProperty=r,i.hasUsername=!0):r.hasSemantic(y.Password)&&(i.passwordProperty=r,i.hasPassword=!0);return i}function Ki(n){let e,t;for(let a of n.listEntities())if(!e&&a.hasSemantic(y.Organization)&&(e=a),!t&&a.hasSemantic(y.User)&&(t=a),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=co(i,y.OrganizationMembers,y.OrganizationRole),o=s;return!o&&e&&(o=Array.from(e.withInheritedProperties()).find(a=>a.hasSemantic(y.OrganizationRole))),!o&&t&&(o=Array.from(t.withInheritedProperties()).find(a=>a.hasSemantic(y.OrganizationRole))),{hasOrganization:!!e,hasMembersAssociation:!!r,hasOrganizationRole:!!o,orgEntity:e,membersAssoc:r,roleProperty:o}}function Ta(n){let e,t;for(let a of n.listEntities())if(!e&&a.hasSemantic(y.Project)&&(e=a),!t&&a.hasSemantic(y.User)&&(t=a),e&&t)break;let i=[e,t].filter(Boolean),{membersAssoc:r,roleProperty:s}=co(i,y.ProjectMembers,y.ProjectRole),o=s;return!o&&e&&(o=Array.from(e.withInheritedProperties()).find(a=>a.hasSemantic(y.ProjectRole))),!o&&t&&(o=Array.from(t.withInheritedProperties()).find(a=>a.hasSemantic(y.ProjectRole))),{hasProject:!!e,hasMembersAssociation:!!r,hasProjectRole:!!o,projectEntity:e,membersAssoc:r,roleProperty:o}}function co(n,e,t){let i,r;for(let s of n){let o=[];for(let a of s.listAssociations())o.push(a);for(let a of s.listAllParents("up"))for(let l of a.listAssociations())o.some(c=>c.key===l.key)||o.push(l);for(let a of o)if(a.hasSemantic(e)){let l=a.getSemantic(e);if(!l?.link&&!i&&(i=a),!l?.link)for(let c of a.properties)!r&&c.hasSemantic(t)&&(r=c)}}return{membersAssoc:i,roleProperty:r}}function Ep(n){let e=n.type,i=n.readWebBinding()?.format,r=n.multiple,s;if(e==="string"){let o=n.schema?.maximum,a=typeof o=="number"?o:void 0;if(n.schema?.defaultValue?.type==="function"&&n.schema.defaultValue.value==="random"){let l=n.schema.defaultValue.config;if(l){let c=0,p=!1;l.isFixed?l.length&&(c=l.length,p=!0):a&&(c=a,p=!0),p&&(l.prefix&&(c+=l.prefix.length),l.suffix&&(c+=l.suffix.length),(!a||c>a)&&(a=c))}}s=a?`VARCHAR(${a})`:"TEXT"}else if(e==="number"){let o=n.schema?.defaultValue?.type==="function"&&n.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 Al(n){let e=n.getExposedName();if(!e)throw new g("Property missing a name definition.",{code:"E_PROPERTY_NAME_MISSING",status:500});let t=null;if(n.schema?.defaultValue){let u=n.schema.defaultValue.type,m=String(n.schema.defaultValue.value);if(u==="function"){let h=n.type;if(h==="string"){if(m==="uuid-v4"&&n.primary)throw new g("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 g(`Function '${m}' is not supported for string properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else if(h==="number"){if(m!=="incremental")throw new g(`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 g(`Function '${m}' is not supported for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}else throw new g(`Functions are not supported as default values for ${h} properties.`,{code:"E_INVALID_DEFAULT_FUNCTION",status:400})}t={type:u,value:m}}let i=!!n.primary,r=!n.required&&!i,s=!!n.unique;!t&&n.hasSemantic(y.DeletedFlag)&&(t={type:"literal",value:"false"});let o=n.getSemantic(y.Currency);if(o){let u=o.config??{},m=u.storageFormat||no.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=u.decimalPlaces??no.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:u.defaultCurrency||"USD"}}]}}let a=[{name:e,dataType:Ep(n),isNullable:r,isPrimary:i,isUnique:s,defaultRule:t}],l=!1,c=n.getSemantic(y.Email);c&&(l=!!(c.config??lo).requireVerification);let p=n.getSemantic(y.Phone);return p&&(l=(p.config??wl).requireVerification===!0),l&&a.push({name:`_${e}_verified`,dataType:"BOOLEAN",isNullable:!1,isPrimary:!1,isUnique:!1,defaultRule:{type:"literal",value:"false"}},{name:`_${e}_token`,dataType:"VARCHAR(255)",isNullable:!0,isPrimary:!1,isUnique:!1,defaultRule:null},{name:`_${e}_expires_at`,dataType:"TIMESTAMPTZ",isNullable:!0,isPrimary:!1,isUnique:!1,defaultRule:null}),a}function xp(n){let e=n.toUpperCase().split("(")[0];return e==="CHARACTER VARYING"&&(e="VARCHAR"),e==="CHARACTER"&&(e="CHAR"),e}function Op(n,e){let t=e.toUpperCase(),i=xp(n.dataType),r=t.split("(")[0];if(i===r){if(i==="VARCHAR"){let o=n.dataType.match(/\((\d+)\)/),a=o?Number.parseInt(o[1],10):null,l=t.match(/\((\d+)\)/),c=l?Number.parseInt(l[1],10):null;return!!(!c||a&&c>=a)}return!0}return{INTEGER:["BIGINT","NUMERIC","VARCHAR","TEXT"],BIGINT:["NUMERIC","VARCHAR","TEXT"],DATE:["TIMESTAMPTZ"],BOOLEAN:["VARCHAR","TEXT"]}[i]?.includes(r)||!1}function Pp(n,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 l=Array.from(o.withInheritedProperties()),c=new Set(l.map(m=>m.key)),p=Array.from(o.withInheritedAssociations()),u=new Set(p.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(u.has(k)){let v=p.find(E=>E.key===k);f.length>1&&(!v||v.schema?.embedded!==!0)&&r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:`Projected association '${h.key}' is invalid because association '${k}' is not embedded.`})}else{let v=!1,E=`Projected association '${h.key}' no longer exists on entity '${o.info.getLabel()}'.`;if(a){let $=Array.from(a.withInheritedAssociations()).find(j=>j.key===k);if($){let j;try{j=$.getExposedName()}catch{}if(j){let C=p.find(I=>{try{return I.getExposedName()===j}catch{return!1}});C&&(f.length>1&&C.schema?.embedded!==!0?E=`Projected association '${h.key}' is invalid because remapped association '${C.key}' is not embedded.`:v=!0)}}}v||r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"association",fieldKey:h.key,reason:E})}}else{let f=h.key.split("."),k=f[0];if(c.has(k)){let v=l.find(E=>E.key===k);f.length>1&&(!v||v.type!=="json"?r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid because root property '${k}' is not of type 'json'.`}):v.jsonSchema&&(xt(v.jsonSchema,f.slice(1))||r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' is invalid according to the JSON Schema of '${k}'.`})))}else{let v=!1;if(a){let E=Array.from(a.withInheritedProperties()).find($=>$.key===k);if(E){let $;try{$=E.getExposedName()}catch{}if($){let j=l.find(C=>{try{return C.getExposedName()===$}catch{return!1}});j&&(f.length===1||j.type==="json")&&(v=!0,f.length>1&&j.jsonSchema&&(xt(j.jsonSchema,f.slice(1))||(v=!1)))}}}v||r.actionProjectionsWithMismatches.push({exposureKey:n,actionKind:m.kind,fieldType:"property",fieldKey:h.key,reason:`Projected property '${h.key}' no longer exists on entity '${o.info.getLabel()}'.`})}}}function Ip(n,e,t,i,r){if(!e.paginationContract)return;let s=e.paginationContract,o=e.entity.key,a=t.get(o);if(!a)return;let l=Array.from(a.withInheritedProperties()),c=new Set(l.map(m=>m.key)),p=i.findEntity(o),u=(m,h)=>{if(!(!m||!Array.isArray(m)))for(let f of m){let k=f.split("."),v=k[0];if(c.has(v)){let E=l.find($=>$.key===v);k.length>1&&(!E||E.type!=="json"?r.paginationFieldsWithMismatches.push({exposureKey:n,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid because root property '${v}' is not of type 'json'.`}):E.jsonSchema&&(xt(E.jsonSchema,k.slice(1))||r.paginationFieldsWithMismatches.push({exposureKey:n,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' is invalid according to the JSON Schema of '${v}'.`})))}else{let E=!1;if(p){let $=Array.from(p.withInheritedProperties()).find(j=>j.key===v);if($){let j;try{j=$.getExposedName()}catch{}if(j){let C=l.find(I=>{try{return I.getExposedName()===j}catch{return!1}});C&&(k.length===1||C.type==="json")&&(E=!0,k.length>1&&C.jsonSchema&&(xt(C.jsonSchema,k.slice(1))||(E=!1)))}}}E||r.paginationFieldsWithMismatches.push({exposureKey:n,fieldGroup:h,fieldKey:f,reason:`The ${h} field '${f}' no longer exists on entity '${a.info.getLabel()}'.`})}}};u(s.filterableFields,"filterable"),u(s.sortableFields,"sortable"),u(s.searchableFields,"searchable")}function _l(n,e){let t=n.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,w]of n.exposes.entries()){let O=r.has(w.entity.key),z=s.get(w.entity.key);if(!z){let V=r.get(w.entity.key)?.info.getLabel()||w.entity.key;i.exposedEntitiesToRemove.push({key:P,entityKey:w.entity.key,name:w.entity.key,reason:`Entity ${V} no longer exists in the domain.`}),o.add(P);continue}if(O){let V=r.get(w.entity.key),B=new Map;for(let ae of V.withInheritedProperties())try{let re=ae.getExposedName();re&&B.set(re,ae)}catch{}let Z=new Map;for(let ae of z.withInheritedProperties())try{let re=ae.getExposedName();re&&Z.set(re,ae)}catch{}for(let[ae,re]of B.entries()){let Ne=Z.get(ae);if(!Ne)continue;let we=Al(re),le=Al(Ne);for(let ne of we){let ve=le.find(at=>at.name===ne.name);if(!ve)continue;if(ne.isPrimary&&!ve.isPrimary){i.canProceed=!1;let at=V.info.getLabel(),nt=`Cannot remove Primary Key constraint from column '${ne.name}' in entity '${at}'.`;i.breakingChanges.push({type:"primary_key_removed",entityKey:V.key,propertyKey:re.key,reason:nt})}if(!Op(ne,ve.dataType)){i.canProceed=!1;let at=V.info.getLabel(),nt=`Cannot safely cast column '${ne.name}' in entity '${at}' from ${ne.dataType} to ${ve.dataType}.`;i.breakingChanges.push({type:"type_change_unsafe",entityKey:V.key,propertyKey:re.key,reason:nt})}let $e=ne.isNullable&&!ve.isNullable,Ve=!!ve.defaultRule;if($e&&!Ve){i.canProceed=!1;let at=V.info.getLabel(),nt=`Cannot make column '${ne.name}' in entity '${at}' required without providing a default value to backfill existing records.`;i.breakingChanges.push({type:"column_not_null_missing_default",entityKey:V.key,propertyKey:re.key,reason:nt})}}}}}let a=!0;for(;a;){a=!1;for(let[P,w]of n.exposes.entries())if(!o.has(P)){if(w.isRoot===!1&&!w.parent){let O=r.get(w.entity.key)?.info.getLabel()||w.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:"",associationKey:"",name:w.entity.key,reason:`Sub-endpoint for entity ${O} is missing a parent reference.`}),o.add(P),a=!0;continue}if(w.parent){let O=n.exposes.get(w.parent.key);if(!O){i.subEndpointsToRemove.push({key:P,parentKey:w.parent.key,associationKey:w.parent.association?.key??"unknown",name:w.entity.key,reason:`Parent exposure "${w.parent.key}" does not exist in the API model.`}),o.add(P),a=!0;continue}let z=r.get(O.entity.key),V=z?.info.getLabel()||O.entity.key;if(o.has(w.parent.key)){i.subEndpointsToRemove.push({key:P,parentKey:w.parent.key,associationKey:w.parent.association?.key??"unknown",name:w.entity.key,reason:`Parent exposure for entity ${V} is scheduled for removal.`}),o.add(P),a=!0;continue}let B=s.get(O.entity.key);if(!B){i.subEndpointsToRemove.push({key:P,parentKey:w.parent.key,associationKey:w.parent.association?.key??"unknown",name:w.entity.key,reason:`Parent entity ${V} is scheduled for removal.`}),o.add(P),a=!0;continue}if(!w.parent.association||!w.parent.association.key){let Me=r.get(w.entity.key)?.info.getLabel()||w.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:w.parent.key,associationKey:"unknown",name:w.entity.key,reason:`Sub-endpoint for entity ${Me} does not define a parent association.`}),o.add(P),a=!0;continue}let Z=w.parent.association.key,ae=w.parent.association.domain,re=e.findAssociation(Z,ae)??Array.from(B.withInheritedAssociations()).find(Me=>Me.key===Z),Ne=t.findAssociation(Z,ae)??(z?Array.from(z.withInheritedAssociations()).find(Me=>Me.key===Z):void 0),we=re?.info.getLabel()||Ne?.info.getLabel()||Z;if(!re){i.subEndpointsToRemove.push({key:P,parentKey:w.parent.key,associationKey:Z,name:w.entity.key,reason:`Parent association ${we} is missing in the new domain.`}),o.add(P),a=!0;continue}let le=s.get(w.entity.key),ne=B.key,ve=w.entity.key,$e=re.getParentInstance()?.key,Ve=$e===ne||B.listAllParents("up").some(Me=>Me.key===$e),at=$e===ve||le&&le.listAllParents("up").some(Me=>Me.key===$e),nt=re.targets.some(Me=>Me.key===ve||le&&le.listAllParents("up").some(Bi=>Bi.key===Me.key)),ql=re.targets.some(Me=>Me.key===ne||B.listAllParents("up").some(Bi=>Bi.key===Me.key));if(!(Ve&&nt||at&&ql)){let Bi=(r.get(w.entity.key)||le)?.info.getLabel()||w.entity.key;i.subEndpointsToRemove.push({key:P,parentKey:w.parent.key,associationKey:Z,name:w.entity.key,reason:`Target entity ${Bi} is no longer a valid target for the parent association ${we}.`}),o.add(P),a=!0;continue}}}}let l,c;if(n.user&&(l=r.get(n.user.key),c=s.get(n.user.key),!c)){i.canProceed=!1;let w=`User entity '${l?.info.getLabel()||n.user.key}' no longer exists in the new domain version.`;i.breakingChanges.push({type:"user_entity_missing",entityKey:n.user.key,propertyKey:"",reason:w})}if(n.user&&c&&l){let P=Array.from(l.withInheritedProperties()),w=Array.from(c.withInheritedProperties());if(n.session?.properties)for(let O of n.session.properties){let z=P.find(Z=>Z.key===O.key);if(!z){i.sessionPropertiesToRemove.push(O.key);continue}let V;try{V=z.getExposedName()}catch{}if(!V){i.sessionPropertiesToRemove.push(O.key);continue}let B=w.find(Z=>{try{return Z.getExposedName()===V}catch{return!1}});B?B.key!==z.key&&i.userModelRemapping.push({oldPropertyKey:z.key,newPropertyKey:B.key,exposedName:V,reason:`Property ${z.info.getLabel(z.key)} has been renamed to ${B.info.getLabel(B.key)}.`}):i.sessionPropertiesToRemove.push(O.key)}}let p=zt(e,c),u=Ki(e),m=Ta(e),h=p.roleProperty??(c?Array.from(c.withInheritedProperties()).find(P=>P.hasSemantic(y.UserRole)):void 0),f=u.roleProperty,k=m.roleProperty,v=h?.schema?.enum,E=f?.schema?.enum,$=k?.schema?.enum,j=(P,w)=>{if(P.type==="matchOrganizationRole"){let O=P;if(!f)i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:w,reason:"No organization role property configured in the new domain model."});else if(E&&Array.isArray(E)&&O.roles)for(let z of O.roles)E.includes(z)||i.accessRulesWithMismatches.push({ruleType:"matchOrganizationRole",location:w,reason:`Organization role '${z}' is no longer a valid role in the new domain model.`})}else if(P.type==="matchProjectRole"){let O=P;if(!k)i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:w,reason:"No project role property configured in the new domain model."});else if($&&Array.isArray($)&&O.roles)for(let z of O.roles)$.includes(z)||i.accessRulesWithMismatches.push({ruleType:"matchProjectRole",location:w,reason:`Project role '${z}' is no longer a valid role in the new domain model.`})}},C=(P,w)=>{if(P.type==="matchUserRole"){let O=P;if(!h){i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:w,reason:"No role field configured on the new user model."});return}if(!v||!Array.isArray(v))return;let z=O.mode;if(z==="allowlist")for(let V of O.allowed??[])v.includes(V)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:w,reason:`Role '${V}' in the allowed list is no longer a valid role in the new user model.`});else if(z==="denylist")for(let V of O.denied??[])v.includes(V)||i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:w,reason:`Role '${V}' in the denied list is no longer a valid role in the new user model.`});else z==="minRole"?O.minimumRole&&!v.includes(O.minimumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:w,reason:`minimumRole '${O.minimumRole}' is no longer a valid role in the new user model.`}):z==="maxRole"&&O.maximumRole&&!v.includes(O.maximumRole)&&i.accessRulesWithMismatches.push({ruleType:"matchUserRole",location:w,reason:`maximumRole '${O.maximumRole}' is no longer a valid role in the new user model.`})}},I=(P,w,O)=>{if(P.type==="matchResourceAttribute"){let z=P;if(!O)return;let V=s.get(O);if(!V)return;let B=Array.from(V.withInheritedProperties());if(!B.some(ae=>ae.key===z.attribute)){let ae=r.get(O),re=z.attribute,Ne=!1;if(ae){let we=Array.from(ae.withInheritedProperties()).find(le=>le.key===z.attribute);if(we){re=we.info.getLabel(we.key);let le;try{le=we.getExposedName()}catch{}le&&B.find(ve=>{try{return ve.getExposedName()===le}catch{return!1}})&&(Ne=!0)}}if(!Ne){let we=V.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceAttribute",location:w,reason:`Property attribute '${re}' no longer exists on entity '${we}'.`})}}}},T=(P,w,O)=>{if(P.type==="matchResourceOwner"){let z=P;if(z.target==="user-entity"){n.user&&!c&&i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:w,reason:"User entity is missing in the new domain."});return}if(!O)return;let V=s.get(O);if(!V)return;if(z.association&&z.association.key){let B=z.association.key,Z=z.association.domain,ae=e.findAssociation(B,Z),re=Array.from(V.withInheritedAssociations());if(!(ae?re.some(we=>we.key===ae.key):re.some(we=>we.key===B))){let we=r.get(O),le=B,ne=!1;if(we){let $e=Array.from(we.withInheritedAssociations()).find(Ve=>Ve.key===B);if($e){le=$e.info.getLabel($e.key);let Ve;try{Ve=$e.getExposedName()}catch{}Ve&&re.find(nt=>{try{return nt.getExposedName()===Ve}catch{return!1}})&&(ne=!0)}}if(!ne){let ve=V.info.getLabel();e.resolveOwnershipPath(O)!==null?i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:w,reason:`Direct ownership association '${le}' no longer exists on entity '${ve}'. The resolved ownership path will be used instead.`}):i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:w,reason:`Ownership association '${le}' no longer exists on entity '${ve}' and no transitively resolved ownership path is available.`})}}}else if(!(e.resolveOwnershipPath(O)!==null)){let Z=V.info.getLabel();i.accessRulesWithMismatches.push({ruleType:"matchResourceOwner",location:w,reason:`No ownership association specified and no transitively resolved ownership path exists for entity '${Z}'.`})}}},U=(P,w)=>{if(P.type==="matchUserProperty"){let O=P;if(n.user&&!c){i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:w,reason:"User entity is missing in the new domain."});return}c&&O.property&&(Array.from(c.withInheritedProperties()).some(B=>B.key===O.property)||i.userModelRemapping.some(Z=>Z.oldPropertyKey===O.property)||i.accessRulesWithMismatches.push({ruleType:"matchUserProperty",location:w,reason:`User property '${O.property}' no longer exists on the User entity.`}))}},F=(P,w,O)=>{if(P.type==="matchAssociation"){let V=P.association;if(!V||!V.key){i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:w,reason:"No target association specified for match association access rule."});return}let B=V.key,Z=V.domain;if(!e.findAssociation(B,Z)){let re=O?s.get(O):void 0,Ne=re?Array.from(re.withInheritedAssociations()):[];if(!Ne.some(le=>le.key===B)){let le=O?r.get(O):void 0,ne=!1;if(le){let $e=Array.from(le.withInheritedAssociations()).find(Ve=>Ve.key===B);if($e){let Ve;try{Ve=$e.getExposedName()}catch{}Ve&&Ne.find(nt=>{try{return nt.getExposedName()===Ve}catch{return!1}})&&(ne=!0)}}if(!ne){let ve=re?.info.getLabel()||le?.info.getLabel()||O||"Entity";i.accessRulesWithMismatches.push({ruleType:"matchAssociation",location:w,reason:`Target association '${B}' no longer exists in domain or on entity '${ve}'.`})}}}}};if(n.accessScenarios)for(let P of n.accessScenarios)for(let w of P.rules)C(w,{type:"api",key:n.key}),j(w,{type:"api",key:n.key}),U(w,{type:"api",key:n.key});for(let[P,w]of n.exposes.entries())if(!o.has(P)){if(w.accessScenarios)for(let O of w.accessScenarios)for(let z of O.rules)C(z,{type:"exposure",key:P}),j(z,{type:"exposure",key:P}),I(z,{type:"exposure",key:P},w.entity.key),T(z,{type:"exposure",key:P},w.entity.key),U(z,{type:"exposure",key:P}),F(z,{type:"exposure",key:P},w.entity.key);if(w.actions){for(let O of w.actions)if(O.accessScenarios)for(let z of O.accessScenarios)for(let V of z.rules)C(V,{type:"action",key:`${P}:${O.kind}`}),j(V,{type:"action",key:`${P}:${O.kind}`}),I(V,{type:"action",key:`${P}:${O.kind}`},w.entity.key),T(V,{type:"action",key:`${P}:${O.kind}`},w.entity.key),U(V,{type:"action",key:`${P}:${O.kind}`}),F(V,{type:"action",key:`${P}:${O.kind}`},w.entity.key)}Pp(P,w,s,t,i),Ip(P,w,s,t,i)}return i}function El(n,e,t){if(!t.canProceed)throw new g("Cannot apply domain update because it contains breaking changes. Details in the report.",{code:"E_CANNOT_PROCEED_WITH_UPGRADE",status:400});let i=n.domain;n.dependencies.clear(),n.dependencies.set(e.key,e),n.dependencyList=[{key:e.key,version:e.info.version}];let r=[...t.exposedEntitiesToRemove,...t.subEndpointsToRemove];for(let $ of r)n.exposes.delete($.key);if(n.user&&n.session){let $=new Set(t.sessionPropertiesToRemove),j=new Map;for(let C of t.userModelRemapping)j.set(C.oldPropertyKey,C.newPropertyKey);if(n.session.properties){let C=[];for(let I of n.session.properties){if($.has(I.key))continue;let T=j.get(I.key);T?C.push({...I,key:T}):C.push(I)}n.session.properties=C}}let s=new Map;for(let $ of e.listEntities())s.set($.key,$);let o=n.user?s.get(n.user.key):void 0,a=zt(e,o),l=Ki(e),c=Ta(e),p=a.roleProperty??(o?Array.from(o.withInheritedProperties()).find($=>$.hasSemantic(y.UserRole)):void 0),u=l.roleProperty,m=c.roleProperty,h=p?.schema?.enum,f=u?.schema?.enum,k=m?.schema?.enum,v=($,j,C,I,T)=>{if($.type===j){let U=$;if(!C)return!0;if(I&&Array.isArray(I)&&U.roles&&U.roles.length>0){let F=U.roles.filter(P=>I.includes(P));if(F.length===0)return!0;U.roles=F}return T.push($),!0}return!1},E=($,j)=>{let C=[];for(let I of $)if(I.type==="matchUserRole"){let T=I;if(!p)continue;if(h&&Array.isArray(h)){let U=T.mode;if(U==="allowlist"){let F=T.allowed??[];if(F.length>0){let P=F.filter(w=>h.includes(w));if(P.length===0)continue;T.allowed=P}}else if(U==="denylist"){let F=T.denied??[];F.length>0&&(T.denied=F.filter(P=>h.includes(P)))}else if(U==="minRole"){if(T.minimumRole&&!h.includes(T.minimumRole))continue}else if(U==="maxRole"&&T.maximumRole&&!h.includes(T.maximumRole))continue}C.push(I)}else{if(v(I,"matchOrganizationRole",u,f,C))continue;if(v(I,"matchProjectRole",m,k,C))continue;if(I.type==="matchResourceAttribute"&&j){let T=I,U=s.get(j);if(!U)continue;let F=Array.from(U.withInheritedProperties());if(F.some(w=>w.key===T.attribute))C.push(I);else{let w,O=i?.findEntity(j);if(O){let V=Array.from(O.withInheritedProperties()).find(B=>B.key===T.attribute);if(V){let B;try{B=V.getExposedName()}catch{}B&&(w=F.find(Z=>{try{return Z.getExposedName()===B}catch{return!1}}))}}if(w)T.attribute=w.key,C.push(I);else continue}}else if(I.type==="matchResourceOwner"&&j){let T=I;if(T.target==="user-entity")C.push(I);else if(T.association&&T.association.key){let U=s.get(j);if(!U)continue;let F=Array.from(U.withInheritedAssociations()),P=T.association.key;if(F.some(O=>O.key===P))C.push(I);else{let O,z=i?.findEntity(j);if(z){let B=Array.from(z.withInheritedAssociations()).find(Z=>Z.key===P);if(B){let Z;try{Z=B.getExposedName()}catch{}if(Z){let ae=F.find(re=>{try{return re.getExposedName()===Z}catch{return!1}});ae&&(O=ae.key)}}}O?(T.association.key=O,C.push(I)):(T.association=void 0,C.push(I))}}else C.push(I)}else if(I.type==="matchUserProperty"){let T=I;if(n.user){let U=s.get(n.user.key);if(U&&T.property)if(Array.from(U.withInheritedProperties()).some(w=>w.key===T.property))C.push(I);else{let w=t.userModelRemapping.find(O=>O.oldPropertyKey===T.property);w?(T.property=w.newPropertyKey,C.push(I)):(T.property="",C.push(I))}else C.push(I)}else C.push(I)}else if(I.type==="matchAssociation"){let T=I;if(T.association&&T.association.key){let U=j?s.get(j):void 0;if(U&&j){let F=Array.from(U.withInheritedAssociations());if(!F.some(w=>w.key===T.association.key)){let w=i?.findEntity(j);if(w){let z=Array.from(w.withInheritedAssociations()).find(V=>V.key===T.association.key);if(z){let V;try{V=z.getExposedName()}catch{}if(V){let B=F.find(Z=>{try{return Z.getExposedName()===V}catch{return!1}});B&&(T.association.key=B.key)}}}}}}C.push(I)}else C.push(I)}return C};if(n.accessScenarios)for(let $ of n.accessScenarios)$.rules=E($.rules);for(let $ of n.exposes.values()){let j=$.entity.key,C=s.get(j),I=i?.findEntity(j),T=w=>w,U=w=>w,F=!1,P=!1;if(C){let w=Array.from(C.withInheritedProperties()),O=new Set(w.map(B=>B.key)),z=Array.from(C.withInheritedAssociations()),V=new Set(z.map(B=>B.key));T=B=>{let Z=B.split("."),ae=Z[0],re=ae,Ne=!1;if(O.has(ae))Ne=!0;else if(I){let le=Array.from(I.withInheritedProperties()).find(ne=>ne.key===ae);if(le){let ne;try{ne=le.getExposedName()}catch{}if(ne){let ve=w.find($e=>{try{return $e.getExposedName()===ne}catch{return!1}});ve&&(re=ve.key,Ne=!0)}}}Z[0]=re;let we=Z.join(".");return Ne||(F=!0),we},U=B=>{let Z=B.split("."),ae=Z[0],re=ae,Ne=!1;if(V.has(ae))Ne=!0;else if(I){let le=Array.from(I.withInheritedAssociations()).find(ne=>ne.key===ae);if(le){let ne;try{ne=le.getExposedName()}catch{}if(ne){let ve=z.find($e=>{try{return $e.getExposedName()===ne}catch{return!1}});ve&&(re=ve.key,Ne=!0)}}}Z[0]=re;let we=Z.join(".");return Ne||(P=!0),we}}if($.accessScenarios)for(let w of $.accessScenarios)w.rules=E(w.rules,j);if($.actions)for(let w of $.actions){if(w.accessScenarios)for(let O of w.accessScenarios)O.rules=E(O.rules,j);w.projection&&Array.isArray(w.projection.fields)&&(w.projection.fields=w.projection.fields.map(O=>{if(O.type==="association"){P=!1;let z=U(O.key),B=t.actionProjectionsWithMismatches.some(Z=>Z.exposureKey===$.key&&Z.actionKind===w.kind&&Z.fieldType==="association"&&Z.fieldKey===O.key)||P?!0:O.invalid;return{...O,key:z,invalid:B}}else{F=!1;let z=T(O.key),B=t.actionProjectionsWithMismatches.some(Z=>Z.exposureKey===$.key&&Z.actionKind===w.kind&&Z.fieldType==="property"&&Z.fieldKey===O.key)||F?!0:O.invalid;return{...O,key:z,invalid:B}}}))}if($.paginationContract&&C){let w=$.paginationContract;w.filterableFields&&(w.filterableFields=w.filterableFields.map(T)),w.sortableFields&&(w.sortableFields=w.sortableFields.map(T)),w.searchableFields&&(w.searchableFields=w.searchableFields.map(T))}}n.notifyChange()}var po=class n extends zi{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=Q(),exposes:i=[],pagination:r}=e,s=pe.fromJSON(e.info,{name:"Unnamed API"}).toJSON(),o={kind:Te,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=n.createSchema(e),r=[];if(t instanceof Qe)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===je)r.push(new Qe(t,void 0,{readOnly:!0}));else if(t)throw new g("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 g(`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 pe(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 Fi(this,s)])):this.exposes=new Map,Array.isArray(i.accessScenarios)?this.accessScenarios=i.accessScenarios.map(s=>new ht(this,s)):this.accessScenarios=[],i.rateLimiting&&(this.rateLimiting=new Mt(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 g("No domain attached to API model",{code:"E_NO_DOMAIN",help:"Attach a data domain to the API model before exposing entities."});let r=Ot(e,this.domain?.key);if(t.selfRoute){if(!t.parentId)throw new g("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 g("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 g(`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 g("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 g(`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(y.User))throw new g("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 v of this.exposes.values())if(v.parent?.selfRoute&&v.parent.key===t.parentId)throw new g(`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:Jt,key:Q(),entity:e,actions:[],isRoot:!1,hasCollection:!1,resourcePath:"/me",parent:{key:m.key,selfRoute:!0}},k=new Fi(this,f);return this.exposes.set(k.key,k),this.notifyChange(),k}let{parentId:s,association:o}=t;if(s&&!o)throw new g("Association not specified for nested entity",{code:"E_NO_ASSOCIATION",help:"Provide an association when exposing a nested entity."});if(!s&&o)throw new g("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 g(`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&&Ot(m.entity,this.domain?.key)===r)throw new g(`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 g(`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:l,resourcePath:c}=this.generateUniqueRootPaths(a.info.name||""),p={kind:Jt,key:Q(),entity:{...e},actions:[],isRoot:!0,collectionPath:l,resourcePath:c,hasCollection:!0},u=new Fi(this,p);return this.exposes.set(u.key,u),this.notifyChange(),u}generateUniqueRootPaths(e){let t=Xs(e.toLocaleLowerCase()),i=br(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 g(`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 g("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(y.User)){this.user={key:t.key};break}this.notifyChange()}findExposedByEntity(e){let t=Ot(e,this.domain?.key);for(let i of this.exposes.values())if(Ot(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 _l(this,e)}applyDomainUpdate(e,t){El(this,e,t),this.notifyChange()}};function xl(n,e,t,i,r,s,o,a,l,c){let p=[],u=a.domain;if(!u)return p;let m=Pt(u,a.user),h=Array.from(u.listEntities({includeForeign:!0})).find(f=>f.hasSemantic(i));if(m||p.push({code:S("RULE","MISSING_USER_MODEL"),message:`The API specifies a "Match ${t.toLowerCase()} 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:c}),h||p.push({code:S("RULE",`MISSING_${t.toUpperCase()}_MODEL`),message:`The API specifies a "Match ${t.toLowerCase()} role access" rule, but no ${t} entity is configured.`,suggestion:`Annotate an entity in the domain with the ${t} semantic.`,severity:"error",context:c}),h){let f=u.findEntity(l.entity.key,l.entity.domain),k=[h,m].filter(Boolean),{membersAssoc:v,roleProperty:E}=co(k,r,o),$=E;if($||($=Array.from(h.withInheritedProperties()).find(j=>j.hasSemantic(o))||(m?Array.from(m.withInheritedProperties()).find(j=>j.hasSemantic(o)):void 0)),f&&!(f.key===h.key))if(f.hasSemantic(y.User))v||p.push({code:S("RULE",`${t.toUpperCase()}_NOT_LINKED`),message:`[${f.info.getLabel()}]: The access rule is set to "Match ${t.toLowerCase()} role access", but the resource is not linked to the ${t} entity.`,suggestion:`Establish an association between the ${t} entity and this resource entity.`,severity:"error",context:c});else{let C=Array.from(h.withInheritedAssociations()).filter(U=>U.targets.some(F=>F.key===f.key)),I=Array.from(f.withInheritedAssociations()).filter(U=>U.targets.some(F=>F.key===h.key));if(!(C.find(U=>U.hasSemantic(s))||I.find(U=>U.hasSemantic(s)))){let U=C[0]||I[0];if(U){let F=U.info.displayName||(U.info.name&&U.info.name!=="new_association"?U.info.name:U.key);p.push({code:S("RULE",`MISSING_${t.toUpperCase()}_RESOURCE_SEMANTIC`),message:`[${f.info.getLabel()}]: Association "${F}" links ${t} to "${f.info.getLabel()}", but is missing the ${t}Resource semantic annotation.`,suggestion:`Add the ${t}Resource semantic to the association so the runtime can resolve inherited ${t.toLowerCase()} access.`,severity:"error",context:c})}else p.push({code:S("RULE",`${t.toUpperCase()}_NOT_LINKED`),message:`[${f.info.getLabel()}]: The access rule is set to "Match ${t.toLowerCase()} role access", but the resource is not linked to the ${t} entity.`,suggestion:`Establish an association between the ${t} entity and this resource entity.`,severity:"error",context:c})}}if(e&&e.length>0&&$){let j=$.schema?.enum;if(j&&Array.isArray(j))for(let C of e)j.includes(C)||p.push({code:S("RULE",`INVALID_${t.toUpperCase()}_ROLE`),message:`${t} role "${C}" is not defined in the ${t} role enum list.`,suggestion:`Select a valid role from: [${j.join(", ")}].`,severity:"warning",context:c})}}return p}function S(n,e){return`${n}_${e}`}function Ol(n){let e=[],t={apiModelKey:n.key,kind:Te,key:n.key};return n.kind!==Te&&e.push({code:S("API","INVALID_KIND"),message:"The API model type is incorrect.",suggestion:'Set the model type to "ApiModel".',severity:"error",context:{...t,property:"kind"}}),(!n.key||typeof n.key!="string"||n.key.trim()==="")&&e.push({code:S("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:{...t,property:"key"}}),(!n.info||!n.info.name||n.info.name.trim()==="")&&e.push({code:S("API","MISSING_NAME"),message:"The API model has no defined name.",suggestion:"Provide a descriptive name for your API.",severity:"error",context:{...t,property:"info.name"}}),(!n.info||!n.info.description||n.info.description.trim()==="")&&e.push({code:S("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:{...t,property:"info.description"}}),e}function Pl(n){let e=[],t={apiModelKey:n.key,kind:Te,key:n.key},i=n.domain;return i?((!i.info||!i.info.version)&&e.push({code:S("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:t}),e):(e.push({code:S("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:t}),e)}function Il(n){let e=[],t={apiModelKey:n.key,kind:Te,key:n.key},i=n.domain?Pt(n.domain,n.user):void 0;if(!n.authentication)e.push({code:S("API","MISSING_AUTHENTICATION"),message:"The API is missing authentication settings.",suggestion:"Go to the security settings and configure how users authenticate.",severity:"error",context:{...t,property:"authentication"}});else if(n.authentication.strategy==="UsernamePassword"&&i){let r;for(let o of i.properties)if(o.hasSemantic(y.Password)){r=o;break}r||e.push({code:S("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:{...t,property:"user"}});let s;for(let o of i.properties)if(o.hasSemantic(y.Username)){s=o;break}s||e.push({code:S("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:{...t,property:"user"}})}if(!n.authorization)e.push({code:S("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:{...t,property:"authorization"}});else{let r=n.authorization.strategy;if(r==="RBAC"){if(n.domain){let s=zt(n.domain,i);i&&!s.hasRole&&e.push({code:S("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:{...t,property:"user"}})}}else if(r==="OrganizationRBAC"){if(n.domain){let s=Ki(n.domain);s.hasOrganization||e.push({code:S("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:{...t,property:"authorization"}}),s.hasMembersAssociation||e.push({code:S("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:{...t,property:"authorization"}}),s.hasOrganizationRole||e.push({code:S("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:{...t,property:"authorization"}})}}else if(r==="EnterpriseRBAC"&&n.domain){let s=zt(n.domain,i);i&&!s.hasRole&&e.push({code:S("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:{...t,property:"user"}});let o=Ki(n.domain);o.hasOrganization||e.push({code:S("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:{...t,property:"authorization"}}),o.hasMembersAssociation||e.push({code:S("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:{...t,property:"authorization"}}),o.hasOrganizationRole||e.push({code:S("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:{...t,property:"authorization"}})}}if(!n.session)e.push({code:S("API","MISSING_SESSION"),message:"The API is missing session configuration.",suggestion:"Configure how user sessions will be handled.",severity:"error",context:{...t,property:"session"}});else{if(n.session.secret||e.push({code:S("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:{...t,property:"session.secret"}}),!n.session.properties||n.session.properties.length===0)e.push({code:S("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:{...t,property:"session.properties"}});else if(n.authorization&&(n.authorization.strategy==="RBAC"||n.authorization.strategy==="EnterpriseRBAC")&&n.domain){let o=zt(n.domain,i);o.roleProperty&&!n.session.properties.find(a=>a.key===o.roleProperty?.key)&&e.push({code:S("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:{...t,property:"session.properties"}})}let{cookie:r,jwt:s}=n.session;(!r||!r.enabled)&&(!s||!s.enabled)&&e.push({code:S("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:{...t,property:"session"}})}if(n.user?n.domain&&!n.domain.findEntity(n.user.key,n.user.domain)&&e.push({code:S("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:{...t,property:"user"}}):e.push({code:S("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:{...t,property:"user"}}),n.accessScenarios&&n.accessScenarios.length>0)for(let r of n.accessScenarios)for(let s of r.rules)e.push(...Da(s,"api",void 0,n));return e}function Nl(n){let e=[],t={apiModelKey:n.key,kind:Te,key:n.key},i=/^https?:\/\//i,r=/^[^\s@]+@[^\s@]+\.[^\s@]+$/;return n.contact?(n.contact.email&&!r.test(n.contact.email)&&e.push({code:S("API","INVALID_CONTACT_EMAIL"),message:"The contact email address looks invalid.",suggestion:"Please double check the email address formatting.",severity:"error",context:{...t,property:"contact.email"}}),n.contact.url&&!i.test(n.contact.url)&&e.push({code:S("API","INVALID_CONTACT_URL"),message:"The contact link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...t,property:"contact.url"}})):e.push({code:S("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:{...t,property:"contact"}}),n.license?n.license.url&&!i.test(n.license.url)&&e.push({code:S("API","INVALID_LICENSE_URL"),message:"The license link looks invalid.",suggestion:"Provide a working link, starting with http:// or https://.",severity:"error",context:{...t,property:"license.url"}}):e.push({code:S("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:{...t,property:"license"}}),n.termsOfService||e.push({code:S("API","MISSING_TOS"),message:"Terms of Service help legal compliance.",suggestion:"Add a link to the terms of your API service.",severity:"info",context:{...t,property:"termsOfService"}}),e}function $l(n){let e=[],t={apiModelKey:n.key,kind:Te,key:n.key},i=!1;for(let r of n.exposes.values())if(r.actions.some(s=>Lt.isListAction(s)||Ut.isSearchAction(s))){i=!0;break}return i&&(!n.pagination||!n.pagination.kind?e.push({code:S("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:{...t,property:"pagination"}}):(n.pagination.defaultLimit===void 0&&e.push({code:S("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:{...t,property:"pagination.defaultLimit"}}),n.pagination.maxLimit===void 0&&e.push({code:S("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:{...t,property:"pagination.maxLimit"}}))),e}function Np(n,e,t){let i=[],r={apiModelKey:t.key,kind:"Action",key:n.kind,parentExposedEntityKey:e.key};if(ni.isDeleteAction(n)&&(n.strategy?n.strategy==="hard"&&i.push({code:S("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:{...r,property:"strategy"}}):i.push({code:S("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:{...r,property:"strategy"}})),Ai.isUpdateAction(n)&&(!n.allowedMethods||n.allowedMethods.length===0)&&i.push({code:S("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:{...r,property:"allowedMethods"}}),_i.isRestoreAction(n)){let c=e.actions.find(ni.isDeleteAction);(!c||c.strategy!=="soft")&&i.push({code:S("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:{...r,property:"kind"}})}if(n.getAllRateLimiters().some(c=>c.rules.length)||i.push({code:S("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:r}),n.accessScenarios)for(let c of n.accessScenarios)for(let p of c.rules)i.push(...Da(p,"action",e,t,n));n.overrideParentScenarios&&n.accessScenarios.length===0&&i.push({code:S("ACTION","OVERRIDE_BUT_NO_SCENARIOS"),message:`Action "${n.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:{...r,property:"overrideParentScenarios"}});let a=n.getAllScenarios();for(let c of a)c.rules.some(u=>u.isIdentityConstraining)||i.push({code:S("ACTION","SCENARIO_MISSING_IDENTITY_RULE"),message:`Scenario "${c.label||c.key}" on action "${n.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:{...r,property:"accessScenarios"}});let l=null;for(let c of a){let p=c.rules.filter(u=>u.isIdentityConstraining);if(p.length>0){if(p.every(m=>m.isBroadIdentityRule))l||(l=c);else if(l){i.push({code:S("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:{...r,property:"accessScenarios"}});break}}}if(n.projection&&(Lt.isListAction(n)||Ut.isSearchAction(n)||Si.isReadAction(n)||i.push({code:S("ACTION","INVALID_PROJECTION_SEVERITY"),message:`Projections are only supported for read actions (List, Search, Read). The action "${n.kind}" does not support projections.`,suggestion:"Remove projection configuration from this write action.",severity:"warning",context:{...r,property:"projection"}}),n.projection.type!=="include"&&n.projection.type!=="exclude"&&i.push({code:S("ACTION","INVALID_PROJECTION_TYPE"),message:'Projection type must be either "include" or "exclude".',suggestion:"Select a valid projection type.",severity:"error",context:{...r,property:"projection"}}),Array.isArray(n.projection.fields))){let p=e.entity?t.domain?.findEntity(e.entity.key,e.entity.domain):void 0;if(p){let u=Array.from(p.withInheritedProperties()),m=new Set(u.map(f=>f.key)),h=new Set(Array.from(p.withInheritedAssociations()).map(f=>f.key));n.projection.fields.forEach((f,k)=>{if(f.invalid===!0){i.push({code:S("ACTION","INVALID_PROJECTION_FIELD"),message:`The projected field "${f.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:{...r,property:`projection.fields[${k}]`}});return}if(f.type==="association"){let v=f.key.split("."),E=v[0];if(!h.has(E))i.push({code:S("ACTION","INVALID_PROJECTION_ASSOCIATION"),message:`The projected association "${f.key}" does not exist on this entity.`,suggestion:"Select a valid association or remove it.",severity:"error",context:{...r,property:`projection.fields[${k}]`}});else{let $=Array.from(p.withInheritedAssociations()).find(j=>j.key===E);v.length>1&&(!$||$.schema?.embedded!==!0)&&i.push({code:S("ACTION","INVALID_PROJECTION_ASSOCIATION_EMBEDDED"),message:`The projected association "${f.key}" is invalid because association "${E}" is not embedded.`,suggestion:"Ensure the association is marked as embedded to use dot-notation.",severity:"error",context:{...r,property:`projection.fields[${k}]`}})}}else{let v=f.key.split("."),E=v[0];if(!m.has(E))i.push({code:S("ACTION","INVALID_PROJECTION_PROPERTY"),message:`The projected property "${f.key}" does not exist on this entity.`,suggestion:"Select a valid property or remove it.",severity:"error",context:{...r,property:`projection.fields[${k}]`}});else{let $=u.find(j=>j.key===E);v.length>1&&(!$||$.type!=="json"?i.push({code:S("ACTION","INVALID_PROJECTION_JSON_ROOT"),message:`The projected property "${f.key}" is invalid because root property "${E}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...r,property:`projection.fields[${k}]`}}):$.jsonSchema&&(xt($.jsonSchema,v.slice(1))||i.push({code:S("ACTION","INVALID_PROJECTION_JSON_PATH"),message:`The projected property "${f.key}" is invalid according to the JSON Schema of "${E}".`,suggestion:"Configure a valid JSON Schema path or update the projection path.",severity:"error",context:{...r,property:`projection.fields[${k}]`}})))}}})}}return i}function Rl(n,e){let t=[],i={apiModelKey:e.key,kind:Jt,key:n.key},r=n.entity?e.domain?.findEntity(n.entity.key,n.entity.domain):void 0,s=r?.info.getLabel()||r?.key||"unknown";!n.entity||!n.entity.key?t.push({code:S("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:{...i,property:"entity"}}):r||t.push({code:S("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:{...i,property:"entity"}});let o=r?.hasSemantic(y.User);if(n.isRoot&&r&&!o&&e.domain&&e.domain.resolveOwnershipPath(r.key)===null&&t.push({code:S("EXPOSURE","MISSING_OWNER_PATH"),message:`[${s}]: 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:i}),n.parent?.selfRoute){let l=e.exposes.get(n.parent.key);l?(!l.hasCollection||!l.collectionPath)&&t.push({code:S("EXPOSURE","SELF_ROUTE_REQUIRES_COLLECTION"),message:`[${s}]: 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:{...i,property:"parent.key"}}):t.push({code:S("EXPOSURE","SELF_ROUTE_PARENT_NOT_FOUND"),message:`[${s}]: The parent exposed entity "${n.parent.key}" for selfRoute does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...i,property:"parent.key"}}),n.parent.association&&t.push({code:S("EXPOSURE","SELF_ROUTE_ASSOCIATION_FORBIDDEN"),message:`[${s}]: A selfRoute exposure must not specify an association on its parent reference.`,suggestion:"Remove the association from the selfRoute parent reference.",severity:"error",context:{...i,property:"parent.association"}}),r&&!r.hasSemantic(y.User)&&t.push({code:S("EXPOSURE","SELF_ROUTE_NOT_USER_ENTITY"),message:`[${s}]: 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:{...i,property:"entity"}});let c=["read","update","delete","unlink"],p=n.actions.filter(u=>!c.includes(u.kind));p.length>0&&t.push({code:S("EXPOSURE","SELF_ROUTE_INVALID_ACTION"),message:`[${s}]: The /me endpoint is a singleton resource. Only 'read', 'update', 'delete', and 'unlink' actions are permitted.`,suggestion:`Remove unsupported actions (${p.map(u=>`'${u.kind}'`).join(", ")}) from this selfRoute exposure.`,severity:"error",context:{...i,property:"actions"}});for(let u of n.actions)u.accessScenarios.some(h=>{let f=h.rules.some(v=>v.type==="allowAuthenticated"),k=h.rules.some(v=>v.type==="matchResourceOwner"&&v.target==="user-entity");return f&&k})||t.push({code:S("EXPOSURE","SELF_ROUTE_MISSING_PREDEFINED_RULES"),message:`[${s}]: Action "${u.kind}" on a selfRoute exposure must include the invariant security rules (AllowAuthenticated and MatchResourceOwner with target 'user-entity').`,suggestion:"Add an access scenario with AllowAuthenticated and MatchResourceOwner (target: user-entity) rules to this action.",severity:"error",context:{...i,property:"actions"}});for(let u of e.exposes.values())if(u.key!==n.key&&u.parent?.selfRoute&&u.parent.key===n.parent.key){t.push({code:S("EXPOSURE","SELF_ROUTE_DUPLICATE"),message:`[${s}]: Only one selfRoute exposure may be registered per parent exposure.`,suggestion:"Remove duplicate selfRoute under this parent exposure.",severity:"error",context:{...i,property:"parent"}});break}}if(!n.isRoot&&e.domain){if(!n.parent)t.push({code:S("EXPOSURE","MISSING_PARENT_REF"),message:`[${s}]: 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:{...i,property:"parent"}});else if(!n.parent.selfRoute){let l=e.exposes.get(n.parent.key);if(!l)t.push({code:S("EXPOSURE","INVALID_PARENT_EXPOSURE"),message:`[${s}]: The parent exposed entity "${n.parent.key}" does not exist.`,suggestion:"Ensure that the parent endpoint is exposed.",severity:"error",context:{...i,property:"parent.key"}});else if(!n.parent.association)t.push({code:S("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${s}]: 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:{...i,property:"parent.association"}});else{let c=e.domain.findEntity(l.entity.key,l.entity.domain),p=n.parent.association.key,u=e.domain.findAssociation(p,n.parent.association.domain);if(!u)t.push({code:S("EXPOSURE","MISSING_PARENT_ASSOCIATION"),message:`[${s}]: The parent association "${p}" 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:{...i,property:"parent.association"}});else{let m=c?.key,h=r?.key,f=u.getParentInstance()?.key===m,k=u.getParentInstance()?.key===h,v=u.targets.some(j=>j.key===m),E=u.targets.some(j=>j.key===h);f&&E||k&&v||t.push({code:S("EXPOSURE","INVALID_PARENT_ASSOCIATION"),message:`[${s}]: The parent association "${p}" does not connect the parent entity "${c?.info.name||m}" with the child entity "${r?.info.name||h}".`,suggestion:"Use an association that directly connects the parent and child data entities.",severity:"error",context:{...i,property:"parent.association"}})}}}}if(n.hasCollection){if(!n.collectionPath)t.push({code:S("EXPOSURE","MISSING_COLLECTION_PATH"),message:`[${s}]: 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:{...i,property:"collectionPath"}});else{let l=n.collectionPath.split("/").filter(Boolean);(l.length!==1||!n.collectionPath.startsWith("/"))&&t.push({code:S("EXPOSURE","INVALID_COLLECTION_PATH"),message:`[${s}]: The collection URL should start with "/" and have no extra slashes.`,suggestion:`Ensure the path looks like exactly "/${l[0]||"subresource"}".`,severity:"error",context:{...i,property:"collectionPath"}})}n.resourcePath?n.collectionPath&&(new RegExp(`^${n.collectionPath}/\\{[a-zA-Z0-9_]+\\}$`).test(n.resourcePath)||t.push({code:S("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${s}]: The single item route should match exactly your collection path plus one identifier variable.`,suggestion:`Make sure the item path is formatted exactly like "${n.collectionPath}/{id}".`,severity:"error",context:{...i,property:"resourcePath"}})):t.push({code:S("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${s}]: You need an identifier to locate single items.`,suggestion:'Specify the identification parameter format, like "{id}".',severity:"error",context:{...i,property:"resourcePath"}})}else n.resourcePath?(n.resourcePath.split("/").filter(Boolean).length!==1||!n.resourcePath.startsWith("/"))&&t.push({code:S("EXPOSURE","INVALID_RESOURCE_PATH_FORMAT"),message:`[${s}]: The URL route ${n.resourcePath} must only contain one exact part or level.`,suggestion:"Simplify the endpoint URL to a single segment.",severity:"error",context:{...i,property:"resourcePath"}}):t.push({code:S("EXPOSURE","MISSING_RESOURCE_PATH"),message:`[${s}]: Exposed entity representing a single item must declare their URL route.`,suggestion:'Set the URL path (such as "/profile").',severity:"error",context:{...i,property:"resourcePath"}});n.isRoot&&(n.collectionPath&&e.findCollectionPathCollision(n.collectionPath,n.key)&&t.push({code:S("EXPOSURE","ROOT_COLLECTION_COLLISION"),message:`[${s}]: The route "${n.collectionPath}" is already used by another view.`,suggestion:"Give this resource a different path to avoid conflicts.",severity:"error",context:{...i,property:"collectionPath"}}),n.resourcePath&&e.findResourcePathCollision(n.resourcePath,n.key)&&t.push({code:S("EXPOSURE","ROOT_RESOURCE_COLLISION"),message:`[${s}]: The route "${n.resourcePath}" is already used by another one.`,suggestion:"Give this single-item resource a different path to avoid conflicts.",severity:"error",context:{...i,property:"resourcePath"}}));let a=n.getAbsoluteResourcePath();if(a){let l=[...a.matchAll(/\{([^}]+)\}/g)].map(p=>p[1]);if(new Set(l).size!==l.length){let u=l.filter((m,h)=>l.indexOf(m)!==h)[0];t.push({code:S("EXPOSURE","DUPLICATE_PATH_PARAMETER"),message:`[${s}]: The path parameter "{${u}}" 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:{...i,property:"resourcePath"}})}}if(!n.actions||n.actions.length===0)t.push({code:S("EXPOSURE","MISSING_ACTIONS"),message:`[${s}]: This exposed entity does not let users do anything.`,suggestion:"Enable at least one operation like Create, Read, or Update.",severity:"error",context:{...i,property:"actions"}});else{let l=!1,c=!1,p=!1,u=!1;for(let m of n.actions)t.push(...Np(m,n,e)),Ut.isSearchAction(m)&&(l=!0),Lt.isListAction(m)&&(c=!0),(m.kind==="link"||m.kind==="unlink")&&(p=!0),(m.kind==="create"||m.kind==="delete")&&(u=!0),m.getAllScenarios().length===0&&t.push({code:S("ACTION","MISSING_ACCESS_RULES"),message:`[${s}]: The ${m.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:{...i,kind:"Action",key:m.kind,parentExposedEntityKey:n.key}});if(p&&u&&t.push({code:S("EXPOSURE","MUTUALLY_EXCLUSIVE_ACTIONS"),message:`[${s}]: 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:{...i,property:"actions"}}),c||l){let m=n.paginationContract;if(!m)t.push({code:S("EXPOSURE","MISSING_PAGINATION_CONTRACT"),message:`[${s}]: The List or Search action needs a pagination contract.`,suggestion:"Add a pagination contract to the exposed entity.",severity:"error",context:i});else{if(c&&((!m.filterableFields||m.filterableFields.length===0)&&t.push({code:S("EXPOSURE","LIST_MISSING_FILTERS"),message:`[${s}]: Listing all elements without filters could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow filtering.",severity:"warning",context:i}),(!m.sortableFields||m.sortableFields.length===0)&&t.push({code:S("EXPOSURE","LIST_MISSING_SORTING"),message:`[${s}]: Listing all elements without sorting could be overwhelming for large tables.`,suggestion:"Select a few important fields to allow sorting.",severity:"warning",context:i})),l){let h=[];Array.isArray(m.searchableFields)&&h.push(...m.searchableFields),Array.isArray(m.filterableFields)&&h.push(...m.filterableFields),h.length||t.push({code:S("EXPOSURE","SEARCH_MISSING_FIELDS"),message:`[${s}]: 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:i})}if(r){let h=Array.from(r.withInheritedProperties()),f=new Set(h.map(v=>v.key)),k=(v,E,$,j)=>{if(v&&Array.isArray(v))for(let C of v){let I=C.split("."),T=I[0];if(!f.has(T))t.push({code:S("EXPOSURE",$),message:`[${s}]: The ${j} field "${C}" does not exist on this entity.`,suggestion:`Select a valid property on the entity for ${j}.`,severity:"error",context:{...i,property:`paginationContract.${E}Fields`}});else{let U=h.find(F=>F.key===T);I.length>1&&(!U||U.type!=="json"?t.push({code:S("EXPOSURE",$),message:`[${s}]: The ${j} field "${C}" is invalid because root property "${T}" is not of type "json".`,suggestion:'Make sure the root property is of type "json" to use dot-notation.',severity:"error",context:{...i,property:`paginationContract.${E}Fields`}}):U.jsonSchema&&(xt(U.jsonSchema,I.slice(1))||t.push({code:S("EXPOSURE",$),message:`[${s}]: The ${j} field "${C}" is invalid according to the JSON Schema of "${T}".`,suggestion:"Configure a valid JSON Schema path or update the field path.",severity:"error",context:{...i,property:`paginationContract.${E}Fields`}})))}}};k(m.filterableFields,"filterable","INVALID_FILTER_FIELD","filterable"),k(m.sortableFields,"sortable","INVALID_SORT_FIELD","sortable"),k(m.searchableFields,"searchable","INVALID_SEARCH_FIELD","searchable")}}}}if(n.accessScenarios)for(let l of n.accessScenarios)for(let c of l.rules)t.push(...Da(c,"exposure",n,e));return t}function Da(n,e,t,i,r){let s=[],o={apiModelKey:i.key,kind:"AccessRule",key:n.type,...t?{parentExposedEntityKey:t.key}:{}};if(!n.allowedLevels.includes(e)){if(e==="api")s.push({code:S("RULE","INVALID_LEVEL"),message:`[${i.info.getLabel()}]: The "${n.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:o});else{let a=e==="exposure"?"an exposed entity":"an action",l=n.allowedLevels.join(", ");s.push({code:S("RULE","INVALID_LEVEL"),message:`[${t?.entity?.key??t?.key}]: The "${n.type}" access rule cannot be used at the ${e} level because it is only allowed at: [${l}].`,suggestion:`Move this access rule to ${l.includes("api")?"the API level":a==="an exposed entity"?"an action":"an exposed entity"}.`,severity:"error",context:o})}return s}if(i.authorization?.strategy&&(Sl(i.authorization.strategy,e).includes(n.type)||s.push({code:S("RULE","INCOMPATIBLE_RULE_FOR_STRATEGY"),message:`The "${n.type}" access rule is not compatible with the ${i.authorization.strategy} authorization strategy.`,suggestion:"Switch to a strategy that supports this rule.",severity:"error",context:o})),n.type==="matchUserRole"){let a=n,l=i.domain,c=["allowlist","denylist","minRole","maxRole"];if((!a.mode||!c.includes(a.mode))&&s.push({code:S("RULE","MATCH_USER_ROLE_INVALID_MODE"),message:`The "matchUserRole" access rule has an invalid or missing mode "${a.mode??""}". Valid modes are: allowlist, denylist, minRole, maxRole.`,suggestion:"Set the mode to one of: allowlist, denylist, minRole, or maxRole.",severity:"error",context:o}),a.roleMatch!==void 0&&a.roleMatch!=="any"&&a.roleMatch!=="all"&&s.push({code:S("RULE","MATCH_USER_ROLE_INVALID_ROLE_MATCH"),message:`The "matchUserRole" access rule has an invalid roleMatch "${a.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}),a.mode==="allowlist")a.allowed?a.allowed.length===0&&s.push({code:S("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}):s.push({code:S("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});else if(a.mode==="denylist")a.denied?a.denied.length===0&&s.push({code:S("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}):s.push({code:S("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});else if(a.mode==="minRole"||a.mode==="maxRole"){let p=a.mode==="minRole",u=p?"minimumRole":"maximumRole",m=p?a.minimumRole:a.maximumRole,h=p?"minimum":"maximum";if(!m)s.push({code:S("RULE",p?"MATCH_USER_ROLE_MIN_ROLE_MISSING":"MATCH_USER_ROLE_MAX_ROLE_MISSING"),message:`The "matchUserRole" access rule is in ${a.mode} mode, but "${u}" is not specified.`,suggestion:`Specify the ${h} required role name in the "${u}" field.`,severity:"error",context:o});else if(l){let f=Pt(l,i.user);if(f){let k=zt(l,f),v=k.roleProperty?.schema?.enum;Array.isArray(v)&&!v.includes(m)&&s.push({code:S("RULE",p?"MATCH_USER_ROLE_MIN_ROLE_NOT_IN_ENUM":"MATCH_USER_ROLE_MAX_ROLE_NOT_IN_ENUM"),message:`The "${u}" value "${m}" does not exist in the UserRole enum. Valid roles are: ${v.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}),a.mode==="maxRole"&&k.roleProperty?.multiple&&a.roleMatch!=="all"&&s.push({code:S("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(l&&(a.mode==="allowlist"||a.mode==="denylist")){let p=Pt(l,i.user);if(p){let m=zt(l,p).roleProperty?.schema?.enum;if(Array.isArray(m)){let h=a.mode==="allowlist"?a.allowed??[]:a.denied??[],f=a.mode==="allowlist"?"allowed":"denied";for(let k of h)m.includes(k)||s.push({code:S("RULE","MATCH_USER_ROLE_INVALID_ROLE_VALUE"),message:`The role "${k}" in the "${f}" list does not exist in the UserRole enum.`,suggestion:`Remove "${k}" or correct it to a valid UserRole enum value: ${m.join(", ")}.`,severity:"warning",context:o})}}}}else if(n.type==="matchEmailDomain"){let a=n,l=i.domain;if(l){let c=Pt(l,i.user);if(!c)s.push({code:S("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 p=Array.from(c.withInheritedProperties()).find(u=>u.hasSemantic(y.Email));p?a.requireVerified!==!1&&((p.getSemantic(y.Email)?.config?.requireVerification??lo.requireVerification??!0)||s.push({code:S("RULE","EMAIL_VERIFICATION_MISMATCH"),message:`The "Match email domain" access rule requires verified email addresses (requireVerified: true), but the Email data semantic on property "${p.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})):s.push({code:S("RULE","MISSING_EMAIL_SEMANTIC"),message:`The access rule is set to "Match email domain", but the User entity "${c.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})}}(!a.domains||a.domains.length===0)&&s.push({code:S("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 if(n.type==="matchUserProperty"){let a=n,l=i.domain;if(l){let u=Pt(l,i.user);if(!u)s.push({code:S("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(a.property){let m=Array.from(u.withInheritedProperties());if(!m.some(f=>f.key===a.property))s.push({code:S("RULE","INVALID_USER_PROPERTY"),message:`The user property "${a.property}" does not exist on the User entity "${u.info.getLabel()}".`,suggestion:"Select a valid property on the User entity.",severity:"error",context:o});else if(i.session?.properties&&!i.session.properties.some(k=>k.key===a.property)){let v=m.find(E=>E.key===a.property)?.info.getLabel()??a.property;s.push({code:S("RULE","USER_PROPERTY_NOT_IN_SESSION"),message:`The user property "${v}" 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})}}else s.push({code:S("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})}let c=vi.isArrayOperator(a.operator),p=vi.isScalarOperator(a.operator);!c&&!p?s.push({code:S("RULE","INVALID_USER_PROPERTY_OPERATOR"),message:`The operator "${a.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}):c?Array.isArray(a.values)?a.values.length===0&&s.push({code:S("RULE","MATCH_USER_PROPERTY_EMPTY_ARRAY"),message:`The "${a.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.push({code:S("RULE","MATCH_USER_PROPERTY_ARRAY_REQUIRED"),message:`The "${a.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:o}):Array.isArray(a.value)&&s.push({code:S("RULE","MATCH_USER_PROPERTY_SCALAR_REQUIRED"),message:`The "${a.operator}" operator does not accept array 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})}if(!t)return s;if(n.type==="relationalResourceOwner"){let a=i.domain;if(!a)return s;let l=t.entity.key,c=a.findEntity(l),p=c?c.info.getLabel():t.key;if(t.isRoot||!t.parent)return s.push({code:S("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:o}),s;let u=t.parent.key,m=!1,h=new Set([t.key]);for(;u&&!h.has(u);){h.add(u);let f=i.exposes.get(u);if(!f)break;let k=a.findEntity(f.entity.key,f.entity.domain);if(k){if(k.hasSemantic(y.User)){m=!0;break}let v=!1;for(let E of k.withInheritedAssociations())if(E.hasSemantic(y.ResourceOwnerIdentifier)){v=!0;break}if(v){m=!0;break}}u=f.parent?.key}m||s.push({code:S("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:o})}else if(n.type==="matchResourceOwner"){let a=n,l=i.domain;if(!l)return s;let c=t.entity.key,p=l.findEntity(c);if(!p)return s;if(a.target==="user-entity")p.hasSemantic(y.User)||s.push({code:S("RULE","INVALID_USER_ENTITY_TARGET"),message:`[${p.info.getLabel()}]: 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:o});else if(a.association&&a.association.key){let u=a.association.key,m=a.association.domain,h=l.findAssociation(u,m),f=Array.from(p.withInheritedAssociations());(h?f.some(v=>v.key===h.key):f.some(v=>v.key===u))||s.push({code:S("RULE","INVALID_OWNERSHIP_ASSOCIATION"),message:`[${p.info.getLabel()}]: The ownership association "${u}" does not exist on this entity.`,suggestion:"Select a valid association, or clear the field to use transitively resolved ownership.",severity:"error",context:o})}else l.resolveOwnershipPath(c)===null&&s.push({code:S("RULE","MISSING_OWNERSHIP_PATH"),message:`[${p.info.getLabel()}]: The access rule is set to "Match resource owner", but no direct association or transitive ownership path to the User entity exists.`,suggestion:"Annotate an association with the ResourceOwnerIdentifier or RelationalResourceOwner semantic.",severity:"error",context:o})}else if(n.type==="matchResourceAttribute"){let a=n,l=i.domain;if(!l)return s;let c=l.findEntity(t.entity.key,t.entity.domain);if(!c)return s;a.attribute?Array.from(c.withInheritedProperties()).some(f=>f.key===a.attribute)||s.push({code:S("RULE","INVALID_RESOURCE_ATTRIBUTE"),message:`[${c.info.getLabel()}]: The resource attribute property "${a.attribute}" does not exist.`,suggestion:"Select a valid property on the entity.",severity:"error",context:o}):s.push({code:S("RULE","MISSING_RESOURCE_ATTRIBUTE"),message:`[${c.info.getLabel()}]: 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 p=ki.isArrayOperator(a.operator),u=ki.isScalarOperator(a.operator);!p&&!u?s.push({code:S("RULE","INVALID_RESOURCE_ATTRIBUTE_OPERATOR"),message:`[${c.info.getLabel()}]: The operator "${a.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}):p?Array.isArray(a.values)?a.values.length===0&&s.push({code:S("RULE","MATCH_RESOURCE_ATTRIBUTE_EMPTY_ARRAY"),message:`[${c.info.getLabel()}]: The "${a.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.push({code:S("RULE","MATCH_RESOURCE_ATTRIBUTE_ARRAY_REQUIRED"),message:`[${c.info.getLabel()}]: The "${a.operator}" operator requires an array of values.`,suggestion:'Provide an array of values in the "values" property to match against.',severity:"error",context:o}):Array.isArray(a.value)&&s.push({code:S("RULE","MATCH_RESOURCE_ATTRIBUTE_SCALAR_REQUIRED"),message:`[${c.info.getLabel()}]: The "${a.operator}" operator does not accept array 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})}else if(n.type==="matchOrganizationRole"){let a=n;s.push(...xl("matchOrganizationRole",a.roles,"Organization",y.Organization,y.OrganizationMembers,y.OrganizationResource,y.OrganizationRole,i,t,o))}else if(n.type==="matchProjectRole"){let a=n;s.push(...xl("matchProjectRole",a.roles,"Project",y.Project,y.ProjectMembers,y.ProjectResource,y.ProjectRole,i,t,o))}else if(n.type==="matchAssociation"){let a=n,l=i.domain;if(l)if(Pt(l,i.user)||s.push({code:S("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}),!a.association||!a.association.key)s.push({code:S("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 p=a.association.key,u=a.association.domain,m=l.findAssociation(p,u),h=t.entity.key,f=l.findEntity(h),k=f?Array.from(f.withInheritedAssociations()).find(v=>v.key===p):void 0;if(!m&&!k){let v=f?f.info.getLabel():h;s.push({code:S("RULE","INVALID_ASSOCIATION_TARGET"),message:`[${v}]: The target association "${p}" does not exist in the domain.`,suggestion:"Select a valid association configured in the data domain.",severity:"error",context:o})}}}else if(n.type==="matchPathParameter"){let a=n;if(!a.parameters||a.parameters.length===0)s.push({code:S("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:o});else{let l;if(e==="action"&&r)if(["list","create","search","link"].includes(r.kind)){let m=t.getAbsoluteCollectionPath()??"";l=new Set([...m.matchAll(/\{([^}]+)\}/g)].map(h=>h[1]))}else{let m=t.getAbsoluteResourcePath();l=new Set([...m.matchAll(/\{([^}]+)\}/g)].map(h=>h[1]))}else l=new Set(t.getPathParameters({absolute:!0}));let c=i.domain,p=c?Pt(c,i.user):void 0,u=new Set;if(i.session?.properties)for(let m of i.session.properties)m.key&&u.add(m.key);if(p)for(let m of p.withInheritedProperties())u.add(m.key);for(let m of a.parameters){if(!m.pathParameter||m.pathParameter.trim()==="")s.push({code:S("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:o});else if(!l.has(m.pathParameter)){let h=t.entity?c?.findEntity(t.entity.key,t.entity.domain)?.info.getLabel()??t.entity.key:t.key,f=l.size>0?`[${Array.from(l).join(", ")}]`:"none";s.push({code:S("RULE","MATCH_PATH_PARAMETER_MISSING_ROUTE_PARAM"),message:`[${h}]: Path parameter "${m.pathParameter}" declared in "Match path parameter" rule was not found in the route hierarchy.`,suggestion:`Ensure the route path includes "{${m.pathParameter}}" or select from available parameters: ${f}.`,severity:"error",context:o})}!m.sessionProperty||m.sessionProperty.trim()===""?s.push({code:S("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:o}):u.size>0&&!u.has(m.sessionProperty)&&s.push({code:S("RULE","MATCH_PATH_PARAMETER_INVALID_SESSION_PROPERTY"),message:`Session property "${m.sessionProperty}" was not found in the configured session properties or User model.`,suggestion:`Select a valid session property from: [${Array.from(u).join(", ")}].`,severity:"error",context:o})}}}return s}var uo=class{model;report=[];#e=0;#t=0;#i=0;#r=!1;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(){if(this.#r=!1,this.report=[],this.report.push(...Ol(this.model)),this.report.push(...Pl(this.model)),this.report.push(...Il(this.model)),this.report.push(...$l(this.model)),this.report.push(...Nl(this.model)),!this.model.exposes||this.model.exposes.size===0)this.report.push({code:"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:Te,key:this.model.key,property:"exposes"}});else for(let e of this.model.exposes.values())this.report.push(...Rl(e,this.model));return this.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 ho=class extends Se{constructor(t,i,r){super(i,r);this.file=t}file;async execute(){b.debug("[validate] Executing schema validation...");try{this.validateArguments();let t=await this.loadSchema();this.validateSchemaStructure(t);let i=t.kind,r=[];i===je?r=await this.validateDataDomain(t):i===Te?r=await this.validateApiModel(t):(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Unsupported schema kind "${i}". Supported kinds: "${je}", "${Te}".`}),process.exit(1)),this.reportResults(r,i)}catch(t){let i=D(t);this.formatter.error(i),process.exit(1)}}get isRemoteValidationWithoutOrg(){return!!(this.options.fid&&!this.options.org&&!_.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 b.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.");b.debug(`[validate] Fetching remote schema file ID '${this.options.fid}' from organization '${t}'...`);let i=G(),{media:r}=await i.files.readMedia(t,this.options.fid,{token:i.token});return b.debug("[validate] Remote schema loaded successfully."),r}async loadLocalSchema(){let t;if(this.shouldReadFromStdin)b.debug("[validate] Reading schema from STDIN..."),t=await this.readStdin();else if(this.file){let i=jl.resolve(this.file);b.debug(`[validate] Reading local schema file from path: ${i}`),mo.existsSync(i)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`File not found at path: ${i}`}),process.exit(1)),t=mo.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 b.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){b.debug("[validate:domain] Validating schema as Data Domain...");let i=[];if(this.options.fid){let a=G(),l=t.dependencyList||[];l.length>0&&(b.debug(`[validate:domain] Listing ${l.length} dependency data domains from catalog...`),i=(await a.dataCatalog.listDependencies(l,{token:a.token})).data||[])}let r=new Qe(t,i,{readOnly:!0}),o=new Vi(r).validate();return b.debug(`[validate:domain] Domain validation rules executed. Issues found: ${o.length}`),o}async validateApiModel(t){b.debug("[validate:api] Validating schema as API Model...");let i;if(this.options.fid){let a=G(),l=t.dependencyList||[];if(l.length>0){b.debug(`[validate:api] Listing ${l.length} dependency data domains from catalog...`);let p=(await a.dataCatalog.listDependencies(l,{token:a.token})).data||[];p.length>0&&(i=new Qe(p[0],p,{readOnly:!0}))}}else if(this.options.domain){let a=jl.resolve(this.options.domain);b.debug(`[validate:api] Loading domain dependency from local path: ${a}`),mo.existsSync(a)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Domain dependency file not found at path: ${a}`}),process.exit(1));let l;try{l=JSON.parse(mo.readFileSync(a,"utf8"))}catch(c){let p=c instanceof Error?c.message:String(c);this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Failed to parse domain dependency JSON: ${p}`}),process.exit(1)}i=new Qe(l,[],{readOnly:!0})}let r=new po(t,i),o=new uo(r).validate();return b.debug(`[validate:api] API Model validation rules executed. Issues found: ${o.length}`),o}reportResults(t,i){b.debug(`[validate] Reporting results. Found ${t.length} validation issue(s).`);let r=t.some(s=>s.severity==="error");if(_.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(c=>c.severity==="error").length,a=t.filter(c=>c.severity==="warning").length,l=t.filter(c=>c.severity==="info").length;console.log(""),o>0?console.error(te.red(`\u2716 Validation failed: ${o} error(s), ${a} warning(s), ${l} info(s).`)):console.log(te.yellow(`\u26A0 Validation passed with warnings: ${a} warning(s), ${l} info(s).`))}r&&process.exit(1)}formatIssues(t,i){return t.map(r=>{let s=r.severity||"info",o=r.message||"",a,l,c;if(i===je){let p=r;a=p.rule||"unknown",l=p.help||"",c=p.key?`${p.kind||"unknown"}: ${p.key}`:p.field||""}else{let p=r;a=p.code||"unknown",l=p.suggestion||"";let u=p.context||{};c=`${u.kind||"unknown"}: ${u.key||""}${u.property?"."+u.property:""}`}return{severity:s,code:a,message:o,suggestion:l,context:c}})}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 Cl(n){n.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 W({format:_.resolved.format});b.debug("[validate] Starting validation process..."),await new ho(e,t,i).execute()})}var fo=class extends Se{async execute(){b.debug("[runtime:update] Executing runtime user update...");try{let e=G();Pi(e,this.formatter);let t=this.resolveOrgId("Organization ID is not specified.","Use --org <oid> or configure a default organization.");b.debug(`[runtime:update] Using organization ID: ${t}`),b.debug("[runtime:update] Parsing properties...");let i=this.parseProperties(this.options.property),r={};for(let[o,a]of Object.entries(i)){let l=["token","password","secret","key"].some(c=>o.toLowerCase().includes(c));r[o]=l?"**********":a}b.debug(`[runtime:update] Parsed properties: ${JSON.stringify(r)}`),b.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});b.debug("[runtime:update] Runtime user updated successfully."),this.formatter.success(`User '${this.options.userId}' updated successfully!`,s)}catch(e){let t=D(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 Tl(n){n.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 W({format:_.resolved.format});b.debug("[runtime:update] Starting runtime user update process..."),await new fo(i,r).execute()})}import{InvalidArgumentError as Dl}from"commander";function go(n){if(!/^\d+$/.test(n.trim()))throw new Dl("Must be a positive integer.");let e=parseInt(n,10);if(e<1)throw new Dl("Must be a positive integer.");return e}var It=class{constructor(e=new ee,t=G()){this.fileManager=e;this.client=t}fileManager;client;async loadDomain(e,t){let i=await this.fileManager.read(e,t);if(i.kind!==qt)throw new Error(`File '${t}' is not a data domain. The file kind is '${i.kind}', but expected '${qt}'.`);let r=await this.fileManager.readMedia(e,t),s=r.media;if(s.kind!==je)throw new Error(`Invalid data domain schema format. The media kind is '${s.kind}', but expected '${je}'.`);let o=[];if(s.dependencyList&&s.dependencyList.length>0){b.debug(`[domain:load] Fetching dependencies: ${JSON.stringify(s.dependencyList)}`);try{o=(await this.client.dataCatalog.listDependencies(s.dependencyList,{token:this.client.token})).data||[]}catch(l){b.debug(`[domain:load] Failed to fetch dependencies: ${l}`)}}return{domain:new Qe(s,o,{readOnly:!1}),fileMeta:i,metaVersion:r.meta.version,originalSchema:s}}};var ze=class extends Se{fileManager;domainLoader;constructor(e,t,i=new ee,r=new It(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){b.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 Ke(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){b.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=D(i);this.formatter.error(r),process.exit(1)}}validateDomain(e,t={}){b.debug("[domain] Validating data domain structure...");let r=new Vi(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(te.yellow(`\u26A0 Data domain validation reported ${o.length} warning(s):`));for(let a of o)console.log(te.yellow(` - [${a.rule||"WARNING"}] ${a.message}`))}}}};var yo=class extends ze{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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});b.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=D(t);this.formatter.error(i),process.exit(1)}}};var bo=class extends ze{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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 be("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!==je&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${s.kind}', but expected '${je}'.`}),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=D(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var ko=class extends ze{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;b.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){b.debug(`[domain:read] Fetching media schema for domain file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;b.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{b.debug(`[domain:read] Fetching metadata for domain file ID '${i}'...`);let r=await this.fileManager.read(e,i);b.debug("[domain:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=D(r);this.formatter.error(s),process.exit(1)}}};var Nt;(function(n){n.add="add",n.remove="remove",n.replace="replace",n.copy="copy",n.move="move",n.test="test"})(Nt||(Nt={}));function vo(n,e,t){let i=new ue(e),r=di(n,i);if(!kt(r,t))throw new Ae([{path:i.raw,message:"Test operation failed. The values are not equal."}]);return{doc:n}}var S$=Object.freeze({add:bt,copy:$i,move:tr,remove:Tt,replace:Ni,test:vo});function Ll(n){return Array.isArray(n)?new Array(n.length).fill(0).map((e,t)=>`${t}`):Object.keys(n)}function _r(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function $p(n,e,t={}){if(JSON.stringify(n)===JSON.stringify(e))return[];let i=[...n],r=[...e],s=[],o=0,a=0;for(;o<i.length||a<r.length;)if(o>=i.length){let l=t.fixedIndexes?a:-1;s.push({op:"add",index:l,value:r[a]}),a++}else if(a>=r.length)s.push({op:"remove",index:o}),o++;else if(kt(i[o],r[a]))o++,a++;else{let l=-1,c=-1;for(let p=o;p<i.length;p++)if(kt(i[p],r[a])){l=p;break}for(let p=a;p<r.length;p++)if(kt(r[p],i[o])){c=p;break}if(l===-1&&c===-1)s.push({op:"replace",index:a,value:r[a]}),o++,a++;else if(l===-1)s.push({op:"add",index:a,value:r[a]}),a++;else if(c===-1)s.push({op:"remove",index:o}),o++;else{s.push({op:"move",index:a,from:l});let p=i[l];i.splice(l,1),i.splice(o,0,p),o++,a++}}return s.sort((l,c)=>l.op==="remove"&&c.op==="remove"?c.index-l.index:0)}function Ma(n,e,t,i=[],r={}){if(n===e)return;if(n==null&&e!==null&&e!==void 0){t.push({op:"replace",path:"",value:e});return}if(e==null&&n!==null&&n!==void 0){t.push({op:"replace",path:"",value:null});return}typeof e.toJSON=="function"&&(e=e.toJSON());let s=Wt(n),o=Wt(e),a=hs(s),l=hs(o);if(a&&l){kt(n,e)||t.push({op:"replace",path:_e(i),value:e});return}if(o!==s){t.push({op:s===void 0?"add":"replace",path:_e(i),value:e});return}if(s==="array"){let u=n,h=$p(u,e,r);for(let f of h){let k=f.index===-1?"-":f.index.toString(),v=[...i,k];f.op==="remove"?(r.invertible&&t.push({op:"test",path:_e(v),value:_r(u[f.index])}),t.push({op:f.op,path:_e(v)})):f.op==="replace"&&typeof f.value=="object"&&f.value!==null?Ma(u[f.index],f.value,t,v,r):f.op==="move"?t.push({op:"move",from:_e([...i,f.from.toString()]),path:_e(v)}):t.push({op:f.op,path:_e(v),value:f.value})}return}let c=Ll(e),p=Ll(n);for(let u of c){let m=n[u],h=e[u];Object.prototype.hasOwnProperty.call(n,u)?typeof m=="object"&&m!=null&&typeof h=="object"&&h!==null&&Array.isArray(m)===Array.isArray(h)?Ma(m,h,t,[...i,u],r):kt(m,h)||(r.invertible&&t.push({op:"test",path:_e([...i,u]),value:_r(m)}),t.push({op:"replace",path:_e([...i,u]),value:_r(h)})):t.push({op:"add",path:_e([...i,u]),value:_r(h)})}for(let u of p)Object.prototype.hasOwnProperty.call(e,u)||(r.invertible&&t.push({op:"test",path:_e([...i,u]),value:_r(n[u])}),t.push({op:"remove",path:_e([...i,u])}))}function Vt(n,e,t){let i=[];return Ma(n,e,i,[],t),i}var qi=Object.create(null);qi.add=0;qi.remove=1;qi.replace=2;qi.move=3;qi.copy=4;qi.test=5;var wo=class extends ze{constructor(t,i,r,s=new ee,o=new It(s)){super(i,r,s,o);this.stateOption=t}stateOption;async execute(){let t=this.resolveOrgId();b.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 c=s.domain.info.version;o=await be(`Enter new version (current published version is ${c}):`)}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))}b.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(),l=Vt(s.originalSchema,a);if(l.length===0){b.debug("[domain:transition] No changes in domain lifecycle detected."),this.formatter.success(`Data domain is already in '${r}' state.`);return}try{let c=await this.fileManager.patchMedia(t,i,{patchOps:l,version:s.metaVersion});b.debug(`[domain:transition] Patch applied successfully. New file version: ${c.newVersion}`),this.formatter.success(`Successfully transitioned data domain state to '${r}' (new file version: ${c.newVersion}).`,{fileId:i,state:r,version:s.domain.info.version,fileVersion:c.newVersion})}catch(c){let p=D(c);this.formatter.error(p),process.exit(1)}}async resolveTargetState(){let t=this.stateOption,i=["draft","committed","published"];return!t&&process.stdout.isTTY&&(t=await Ke("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 So=class extends ze{client=G();constructor(e,t,i=new ee,r=new It(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){b.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 b.debug(`[domain:publish] Domain already published. Catalog key: ${i.key}`),i}catch(i){let r=D(i);if(r.status===404)return b.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 be("Enter semantic version:",h)}let o=s||e.info.version||"1.0.0",a=this.options.scope;!a&&process.stdout.isTTY&&(a=await Ke("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),a||(a="public");let l=["public","organization","private"];l.includes(a)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${a}'.`,detail:`Allowed: ${l.join(", ")}`}),process.exit(1));let c=["dev","beta","stable"];c.includes(this.options.lifecycle)||(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${this.options.lifecycle}'.`,detail:`Allowed: ${c.join(", ")}`}),process.exit(1));let p=this.options.lifecycle,u=this.options.name,m=this.options.description;return t?(u=u||t.name||e.info.name||"",m=m||t.description||e.info.description||""):(!u&&e.info.name&&(u=e.info.name),!u&&process.stdout.isTTY&&(u=await be("Enter catalog entry name:",e.info.name||"")),u||(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 be("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:p,name:u,description:m,changelog:this.options.changelog||void 0}}prepareDomainLifecycle(e,t){b.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=Vt(r,o);if(a.length===0)return b.debug("[domain:publish] No changes in domain schema detected, skipping patch."),s;b.debug(`[domain:publish] Sending patch request (${a.length} ops) to file media...`);try{let l=await this.fileManager.patchMedia(e,t,{patchOps:a,version:s});return b.debug(`[domain:publish] File media patched. New file version: ${l.newVersion}`),l.newVersion}catch(l){let c=D(l);this.formatter.error(c),process.exit(1)}}async publishToCatalog(e,t){let i;if(t)i=t.key,b.debug(`[domain:publish] Using existing catalog entry key: ${i}`);else{b.debug("[domain:publish] Publishing new data catalog entry...");let s={key:"",kind:ct,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,b.debug(`[domain:publish] Created catalog entry key: ${i}`)}catch(o){let a=D(o);this.formatter.error(a),process.exit(1)}}let r=ci.createSchema({scope:e.scope,lifecycle:e.lifecycle,version:e.version,changelog:e.changelog||void 0});b.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 b.debug(`[domain:publish] Version published successfully with key: ${s.key}`),{catalogKey:i,versionKey:s.key,version:e.version}}catch(s){let o=D(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 Ao=class extends ze{constructor(t,i,r,s=new ee,o=new It(s)){super(i,r,s,o);this.file=t}file;async execute(){let t=this.resolveOrgId();b.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=Vt(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(te.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=D(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!==je&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid data domain schema. The media kind is '${i.kind}', but expected '${je}'.`}),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=D(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){b.debug("[domain:mutate] Running pre-flight local schema validation...");try{let i=new Qe(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){b.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(b.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(te.cyan(`\u2139 [Dry-run] Computed ${i.length} patch operation(s) for domain '${t}':`));for(let r of i){let s=r.op==="add"?te.green("+"):r.op==="remove"?te.red("-"):te.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 Hr(`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});b.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=D(o);this.formatter.error(a),process.exit(1)}}};var _o=class extends ze{constructor(t,i,r,s=new ee){super(i,r,s);this.queryArg=t}queryArg;async execute(){let t=this.resolveOrgId(),i=await this.resolveQueries();b.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});b.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=D(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 be("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 zl(n){let e=n.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 W({format:_.resolved.format});await new yo(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",go).option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new W({format:_.resolved.format});await new _o(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 W({format:_.resolved.format});await new bo(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 W({format:_.resolved.format});await new ko(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 W({format:_.resolved.format});await new wo(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 W({format:_.resolved.format});await new So(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 W({format:_.resolved.format});await new Ao(t,i,r).execute()})}var $t=class extends Se{fileManager;constructor(e,t,i=new ee){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){b.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 Ke(t,r.map(s=>({name:`${s.info?.name||"Unnamed"} (${s.key})`,value:s.key}))))}catch(r){b.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 Eo=class extends $t{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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});b.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=D(t);this.formatter.error(i),process.exit(1)}}};var xo=class extends $t{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId();b.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 be("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!==Te&&(this.formatter.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid API model schema. The media kind is '${s.kind}', but expected '${Te}'.`}),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=D(i);this.formatter.error({code:"CLI_ERR_API_FAILURE",...s}),process.exit(1)}}};var Oo=class extends $t{constructor(e,t,i=new ee){super(e,t,i)}async execute(){let e=this.resolveOrgId(),t=this.options.file||this.options.id;b.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){b.debug(`[api:read] Fetching media schema for API model file ID '${i}'...`);let s=(await this.fileManager.readMedia(e,i)).media;b.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{b.debug(`[api:read] Fetching metadata for API model file ID '${i}'...`);let r=await this.fileManager.read(e,i);b.debug("[api:read] Metadata retrieved successfully."),this.formatter.object(r)}}catch(r){let s=D(r);this.formatter.error(s),process.exit(1)}}};var Po=class extends $t{constructor(t,i,r,s=new ee){super(i,r,s);this.queryArg=t}queryArg;async execute(){let t=this.resolveOrgId(),i=await this.resolveQueries();b.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});b.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=D(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 be("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 Vl(n){let e=n.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 W({format:_.resolved.format});await new Eo(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",go).option("--org <oid>","Organization ID (optional, defaults to configured default org)").action(async(t,i)=>{let r=new W({format:_.resolved.format});await new Po(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 W({format:_.resolved.format});await new xo(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 W({format:_.resolved.format});await new Oo(t,i).execute()})}parseInt(process.versions.node.split(".")[0],10)<22&&(console.error("Error: apinow requires Node.js 22 or higher."),process.exit(1));function Fl(){let n=process.argv.indexOf("--format");if(n!==-1&&n+1<process.argv.length&&process.argv[n+1]==="json")return"json";try{return _.resolved.format||"text"}catch{return"text"}}process.on("uncaughtException",n=>{new W({format:Fl()}).error({code:"CLI_ERR_UNKNOWN",message:n.message||"An unexpected error occurred.",detail:n.stack}),process.exit(1)});process.on("unhandledRejection",n=>{let e=new W({format:Fl()}),t=n instanceof Error?n.message:String(n),i=n instanceof Error?n.stack:void 0;e.error({code:"CLI_ERR_UNKNOWN",message:`Unhandled promise rejection: ${t}`,detail:i}),process.exit(1)});Tp({pkg:Gi}).notify();_.load();var et=new Dp;et.name("apinow").description("API NOW! Platform CLI Tool").version(Gi.version,"--version").option("--format <format>","Output format: text, json","text").option("--debug","Enable debug/verbose logging").option("-v, --verbose","Enable verbose logging");et.hook("preAction",(n,e)=>{let t,i=e;for(;i;){let r=i.opts();r.format&&!t&&(t=r.format),(r.debug||r.verbose)&&Fa("debug"),i=i.parent}_.saturate({format:t}),b.debug(`Executing command: ${e.name()} with args: ${JSON.stringify(e.args)}`)});Ka(et);Ha(et);Wa(et);Ya(et);sn(et);Cl(et);Tl(et);zl(et);Vl(et);function Kl(n){let e=n.options||[];e.some(t=>t.long==="--format")||n.option("--format <format>","Output format: text, json"),e.some(t=>t.long==="--debug")||n.option("--debug","Enable debug/verbose logging"),e.some(t=>t.long==="--verbose")||(n.options.some(i=>i.short==="-v")?n.option("--verbose","Enable verbose logging"):n.option("-v, --verbose","Enable verbose logging"));for(let t of n.commands)Kl(t)}for(let n of et.commands)Kl(n);await et.parseAsync(process.argv);
54
54
  /*! Bundled license information:
55
55
 
56
56
  @pawel-up/data-mock/build/src/lib/MersenneTwister.js: