@api-now/cli 1.17.1 → 1.17.2

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 (2) hide show
  1. package/dist/index.js +22 -9
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var hp=Object.create;var Gn=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var gp=Object.getOwnPropertyNames;var yp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var kp=(c,e)=>()=>{try{return e||c((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ll=(c,e)=>{for(var t in e)Gn(c,t,{get:e[t],enumerable:!0})},vp=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gp(e))!bp.call(c,r)&&r!==t&&Gn(c,r,{get:()=>e[r],enumerable:!(i=fp(e,r))||i.enumerable});return c};var wp=(c,e,t)=>(t=c!=null?hp(yp(c)):{},vp(e||!c||!c.__esModule?Gn(t,"default",{value:c,enumerable:!0}):t,c));var Ad=kp((xE,Sd)=>{var Dc=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,Am=Object.getOwnPropertyNames,Em=Object.prototype.hasOwnProperty,_m=(c,e)=>{for(var t in e)Dc(c,t,{get:e[t],enumerable:!0})},xm=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Am(e))!Em.call(c,r)&&r!==t&&Dc(c,r,{get:()=>e[r],enumerable:!(i=Sm(e,r))||i.enumerable});return c},Im=c=>xm(Dc({},"__esModule",{value:!0}),c),bd={};_m(bd,{AmfModelExpander:()=>$m,JsonLd:()=>yi,JsonLdOptions:()=>vd});Sd.exports=Im(bd);var Pm=class kd{validate(e){if(e===void 0)throw new Error("Node must not be undefined");if(Array.isArray(e))throw new Error("Node must not be an array");if(e["@id"]===void 0)throw new Error("Node must have an @id")}static empty(){return new kd}withNode(e){this.validate(e);let t=e["@id"];if(this[t]!==void 0)throw new Error(`Cannot add node with duplicate id ${e["@id"]} to dictionary`);return this[t]=e,this}withNodes(e){return e.forEach(t=>this.withNode(t)),this}},Vo=class{static targetOrLink(c,e){let t=e[c["@id"]];return t!==void 0?t:c}static isLinkObject(c){let e=typeof c=="object",t=!Array.isArray(c),i=c["@id"]!==void 0,r=Object.keys(c).length===1;return e&&t&&i&&r}static isArrayOfLinks(c){return c.every(e=>this.isLinkObject(e))}},Rm=class{static embedNodeLinks(c,e,t){let r=t||(()=>!0);return Object.entries(c).filter(([s,o])=>r(s,o)).forEach(([s,o])=>{typeof o=="object"&&(Vo.isLinkObject(o)?c[s]=Vo.targetOrLink(o,e):Array.isArray(o)&&Vo.isArrayOfLinks(o)&&(c[s]=o.map(a=>Vo.targetOrLink(a,e))))}),c}},gd=class Cc{static expandIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.expandIri(i,t);e[s]=r})}static compactIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.compactIri(i,t);e[s]=r})}static compactIri(e,t){switch(typeof t){case"string":return e.replace(t,"");case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))return e;try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(o));return e.replace(r,`${i}:`)}catch{return e}default:throw new Error("Context must be either an object or a string")}}static expandIri(e,t){switch(typeof t){case"string":return`${t}${e}`;case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(s));return e.replace(`${i}:`,r)}catch{return e}else return e;default:throw new Error("Context must be either an object or a string")}}static isCompacted(e,t){let i=!0;return Object.values(t).forEach(r=>{e.startsWith(r)&&(i=!1)}),i}},yd=class{static expandStructure(c){return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.expandType(c,t);break;default:this.expandValue(c,e,t);break}}),c}static expandType(c,e){typeof e=="string"?c["@type"]=[e]:c["@type"]=e}static expandValue(c,e,t){switch(typeof t){case"string":case"number":case"boolean":c[e]=[{"@value":t}];break;case"object":Array.isArray(t)?t.map(r=>{switch(typeof r){case"string":case"number":case"boolean":return[{"@value":t}];default:return r}}):c[e]=[t]}}static compactStructure(c){if(Array.isArray(c)){let[e]=c;return this.compactStructure(e)}else return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.compactType(c,t);break;default:this.compactValue(c,e,t);break}}),c}static compactType(c,e){Array.isArray(e)&&e.length===1&&(c["@type"]=e[0])}static compactValue(c,e,t){if(t.length===1){let[i]=t;this.isWrappedScalar(i)?c[e]=i["@value"]:c[e]=i}else t.map(i=>this.isWrappedScalar(i)?i["@value"]:i)}static isWrappedScalar(c){return c["@value"]!==void 0}},yi=class{static process(c,e){let t=this.getGraph(c),i=this.getContext(c),r=Pm.empty().withNodes(t);t.forEach(o=>{e.embeddedLinks&&Rm.embedNodeLinks(o,r,e.linkEmbeddingFilter),i!==void 0&&(e.expandedIris?gd.expandIris(o,i):e.compactedIris&&gd.compactIris(o,i)),e.expandedStructure?yd.expandStructure(o):e.compactedStructure&&yd.compactStructure(o)});let s=e.rootNodeId===void 0?{"@graph":t}:this.findNode(t,e.rootNodeId);return i!==void 0&&(s["@context"]=i),e.expandedStructure?[s]:s}static getContext(c){return c["@context"]}static getGraph(c){return c["@graph"]}static findNode(c,e){return c.find(t=>t["@id"]===e)}static stringify(c,e=!1){return JSON.stringify(c,null,e?2:0)}},vd=class wd{expandedIris;expandedStructure;embeddedLinks;compactedIris;compactedStructure;rootNodeId;linkEmbeddingFilter;static apply(){return new wd}withCompactedStructure(){return this.expandedStructure=!1,this.compactedStructure=!0,this}withRootNode(e){return this.rootNodeId=e,this}withExpandedStructure(){return this.expandedStructure=!0,this.compactedStructure=!1,this}withExpandedIris(){return this.expandedIris=!0,this.compactedIris=!1,this}withCompactedIris(){return this.expandedIris=!1,this.compactedIris=!0,this}withEmbeddedLinks(e){return this.linkEmbeddingFilter=e,this.embeddedLinks=!0,this}},$m=class{static expand(c){if(this.isInExpandedForm(c))return c;{let e=(r,s)=>!r.endsWith("fixPoint");this.preprocessLegacyRootNodeId(c);let t=this.resolveRootNodeId(c),i=vd.apply().withEmbeddedLinks(e).withCompactedIris().withExpandedStructure().withRootNode(t);return yi.process(c,i)}}static isInExpandedForm(c){return c["@graph"]===void 0}static preprocessLegacyRootNodeId(c){let e=yi.getGraph(c);if(e!=null){let t=yi.findNode(e,"./");t!=null&&(t["@id"]="")}}static resolveRootNodeId(c){let e=yi.getGraph(c);if(e==null||yi.findNode(e,"")!=null)return"";let t=yi.getContext(c);if(t!=null&&t["@base"]!=null){let r=t["@base"];if(yi.findNode(e,r)!=null)return r}let i=e.find(r=>Object.entries(r).some(([s,o])=>(s==="doc:root"||s==="http://a.ml/vocabularies/document#root")&&o===!0));return i!=null?i["@id"]:""}}});import ch from"update-notifier";import{Command as lh}from"commander";var kt={name:"@api-now/cli",description:"API Now! CLI",version:"1.17.1",private:!1,publishConfig:{registry:"https://registry.npmjs.org/","@api-now:registry":"https://registry.npmjs.org/",access:"public"},files:["dist"],engines:{node:">=22.0.0"},type:"module",bin:{apinow:"dist/index.js"},scripts:{build:"node esbuild.config.js",postbuild:"node dist/index.js --help",dev:"tsx src/index.ts",typecheck:"tsc --noEmit",lint:'eslint "src/**/*.ts"',format:'prettier --write "src/**/*.ts"',test:"tsx --test tests/**/*.test.ts",prepare:"husky",prepublishOnly:"npm run build",knip:"knip"},dependencies:{"@inquirer/prompts":"^8.5.0",commander:"^15.0.0",dompurify:"^3.4.11",jsdom:"^30.0.1",nanoid:"^6.0.1",open:"^11.0.0",tslib:"^2.8.1","update-notifier":"^7.3.1",winston:"^3.19.0"},devDependencies:{"@api-now/core":"^1.55.1","@api-now/json":"^1.0.0","@commitlint/cli":"^21.0.1","@commitlint/config-conventional":"^21.0.1","@eslint/js":"^10.0.1","@semantic-release/changelog":"^7.0.0","@semantic-release/git":"^11.0.1","@types/node":"^26.2.0","@types/update-notifier":"^6.0.8",esbuild:"^0.28.0",eslint:"^10.4.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.6",globals:"^17.6.0",husky:"^9.1.7",knip:"^6.14.2",prettier:"^3.8.3","semantic-release":"^25.0.3",tsx:"^4.7.1",typescript:"^6.0.3","typescript-eslint":"^8.60.0"}};import Jn from"node:os";import Jt from"node:path";import Be from"node:fs";var _r="https://api.apinow.app",Wn="apinow-cli",Ap="config.json",Hn=class{_resolved=null;get resolved(){this._resolved||this.load();let e=this._resolved;if(!e)throw new Error("Configuration could not be loaded.");return e}configDir=this.#t();configPath=Jt.join(this.configDir,Ap);#e(e,t){if(!e.profiles&&(e.token||e.org||e.apiUrl)){let i={profiles:{default:{token:e.token||"",org:e.org,apiUrl:e.apiUrl||_r}},activeProfile:"default"};return t&&this.#o(i),i}return e}load(){let t=this.#r()??this.#s(),i=t.activeProfile,r=i&&t.profiles?t.profiles[i]:void 0,s=process.env.APINOW_API_TOKEN||process.env.APINOW_TOKEN||r?.token,o=process.env.APINOW_API_URL||r?.apiUrl||_r,a=r?.org||"";this._resolved={token:s,apiUrl:o,org:a,activeProfile:i,format:"text"}}saturate(e){this._resolved||this.load();let t=this._resolved;if(!t)throw new Error("Configuration could not be loaded.");this._resolved={token:t.token,apiUrl:t.apiUrl,org:t.org,activeProfile:t.activeProfile,format:e.format==="json"?"json":"text"}}listProfiles(){let e=this.#s();return e.profiles?{...e.profiles}:{}}getActiveProfile(){return this.#s().activeProfile}setActiveProfile(e){let t=this.#s();t.activeProfile=e,this.#o(t),this.load()}upsertProfile(e,t){let i=this.#s(),r=i.profiles?{...i.profiles}:{},s=r[e]||{token:""};r[e]={token:t.token!==void 0?t.token:s.token,org:t.org!==void 0?t.org:s.org,apiUrl:t.apiUrl!==void 0?t.apiUrl:s.apiUrl||_r},i.profiles=r,this.#o(i),this.load()}deleteProfile(e){let t=this.#s();if(t.profiles&&e in t.profiles){let i={...t.profiles};delete i[e],t.profiles=i,t.activeProfile===e&&delete t.activeProfile,this.#o(t),this.load()}}writeTokenToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,token:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}writeOrgToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,org:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}#t(){if(process.platform==="win32"){let e=process.env.APPDATA||Jt.join(Jn.homedir(),"AppData","Roaming");if(!e)throw new Error("Could not determine the configuration directory.");return Jt.join(e,Wn)}return process.platform==="darwin"?Jt.join(Jn.homedir(),"Library","Preferences",Wn):Jt.join(process.env.XDG_CONFIG_HOME||Jt.join(Jn.homedir(),".config"),Wn)}#i(){let e=process.cwd();for(;;){let t=Jt.join(e,"apinow.json");if(Be.existsSync(t))try{if(Be.statSync(t).isFile())return t}catch{}let i=Jt.join(e,".apinowrc.json");if(Be.existsSync(i))try{if(Be.statSync(i).isFile())return i}catch{}let r=Jt.dirname(e);if(r===e)break;e=r}return null}#r(){let e=this.#i();if(!e)return null;try{let t=Be.readFileSync(e,"utf8"),i=JSON.parse(t);return this.#e(i,!1)}catch{return null}}#s(){try{if(!Be.existsSync(this.configPath))return{};let e=Be.readFileSync(this.configPath,"utf8"),t=JSON.parse(e);return this.#e(t,!0)}catch{return{}}}writeProperty(e,t){let i=this.#s();e==="activeProfile"&&(i.activeProfile=t),this.#o(i),this.load()}#o(e){try{Be.existsSync(this.configDir)||Be.mkdirSync(this.configDir,{recursive:!0}),Be.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf8")}catch(t){console.error("Failed to write configuration:",t)}}clearConfigKey(e){try{let t=this.#s();delete t[e],this.#o(t),this.load()}catch(t){console.error(`Failed to clear key ${e} from configuration:`,t)}}reset(){try{Be.existsSync(this.configPath)&&Be.unlinkSync(this.configPath),Be.existsSync(this.configDir)&&Be.readdirSync(this.configDir).length===0&&Be.rmdirSync(this.configDir),this._resolved=null}catch(e){console.error("Failed to reset configuration:",e)}}},N=new Hn;import{styleText as Wi}from"node:util";import Ep from"node:path";import _p from"node:os";import xp from"node:crypto";import vt from"winston";var Ip=xp.randomBytes(4).toString("hex"),Pp=Date.now(),Ds=Ep.join(_p.tmpdir(),`apinow-cli-${Pp}-${Ip}.log`),dl=new vt.transports.Console({stderrLevels:Object.keys(vt.config.cli.levels),level:"info",format:vt.format.combine(vt.format.colorize(),vt.format.simple())}),Rp=new vt.transports.File({filename:Ds,level:"debug",format:vt.format.combine(vt.format.timestamp(),vt.format.printf(({timestamp:c,level:e,message:t})=>{let i=typeof t=="string"?t.replace(/\u001b\[\d+m/g,""):t;return`${c} [${e.toUpperCase()}]: ${i}`}))}),y=vt.createLogger({levels:vt.config.cli.levels,level:"debug",transports:[dl,Rp]});function pl(c){dl.level=c}var Yn=kt.version;var ie={green:c=>Wi("green",c),red:c=>Wi("red",c),yellow:c=>Wi("yellow",c),cyan:c=>Wi("cyan",c),dim:c=>Wi("dim",c),bold:c=>Wi("bold",c)};function $p(c,e,t){if(c.length===0)return"No data available.";let i={},r=t||e;for(let n=0;n<e.length;n++){let l=e[n],d=r[n]||l;i[l]=d.length}for(let n of c)for(let l of e){let d=typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"");d.length>(i[l]||0)&&(i[l]=d.length)}let s=e.map((n,l)=>(r[l]||n).toUpperCase().padEnd(i[n])).join(" "),o=e.map(n=>"-".repeat(i[n])).join(" "),a=c.map(n=>e.map(l=>(typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"")).padEnd(i[l])).join(" "));return[s,o,...a].join(`
2
+ var hp=Object.create;var Gn=Object.defineProperty;var fp=Object.getOwnPropertyDescriptor;var gp=Object.getOwnPropertyNames;var yp=Object.getPrototypeOf,bp=Object.prototype.hasOwnProperty;var kp=(c,e)=>()=>{try{return e||c((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ll=(c,e)=>{for(var t in e)Gn(c,t,{get:e[t],enumerable:!0})},vp=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of gp(e))!bp.call(c,r)&&r!==t&&Gn(c,r,{get:()=>e[r],enumerable:!(i=fp(e,r))||i.enumerable});return c};var wp=(c,e,t)=>(t=c!=null?hp(yp(c)):{},vp(e||!c||!c.__esModule?Gn(t,"default",{value:c,enumerable:!0}):t,c));var Ad=kp((xE,Sd)=>{var Dc=Object.defineProperty,Sm=Object.getOwnPropertyDescriptor,Am=Object.getOwnPropertyNames,Em=Object.prototype.hasOwnProperty,_m=(c,e)=>{for(var t in e)Dc(c,t,{get:e[t],enumerable:!0})},xm=(c,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Am(e))!Em.call(c,r)&&r!==t&&Dc(c,r,{get:()=>e[r],enumerable:!(i=Sm(e,r))||i.enumerable});return c},Im=c=>xm(Dc({},"__esModule",{value:!0}),c),bd={};_m(bd,{AmfModelExpander:()=>$m,JsonLd:()=>yi,JsonLdOptions:()=>vd});Sd.exports=Im(bd);var Pm=class kd{validate(e){if(e===void 0)throw new Error("Node must not be undefined");if(Array.isArray(e))throw new Error("Node must not be an array");if(e["@id"]===void 0)throw new Error("Node must have an @id")}static empty(){return new kd}withNode(e){this.validate(e);let t=e["@id"];if(this[t]!==void 0)throw new Error(`Cannot add node with duplicate id ${e["@id"]} to dictionary`);return this[t]=e,this}withNodes(e){return e.forEach(t=>this.withNode(t)),this}},Vo=class{static targetOrLink(c,e){let t=e[c["@id"]];return t!==void 0?t:c}static isLinkObject(c){let e=typeof c=="object",t=!Array.isArray(c),i=c["@id"]!==void 0,r=Object.keys(c).length===1;return e&&t&&i&&r}static isArrayOfLinks(c){return c.every(e=>this.isLinkObject(e))}},Rm=class{static embedNodeLinks(c,e,t){let r=t||(()=>!0);return Object.entries(c).filter(([s,o])=>r(s,o)).forEach(([s,o])=>{typeof o=="object"&&(Vo.isLinkObject(o)?c[s]=Vo.targetOrLink(o,e):Array.isArray(o)&&Vo.isArrayOfLinks(o)&&(c[s]=o.map(a=>Vo.targetOrLink(a,e))))}),c}},gd=class Cc{static expandIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.expandIri(i,t);e[s]=r})}static compactIris(e,t){Object.entries(e).forEach(([i,r])=>{delete e[i];let s=Cc.compactIri(i,t);e[s]=r})}static compactIri(e,t){switch(typeof t){case"string":return e.replace(t,"");case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))return e;try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(o));return e.replace(r,`${i}:`)}catch{return e}default:throw new Error("Context must be either an object or a string")}}static expandIri(e,t){switch(typeof t){case"string":return`${t}${e}`;case"object":if(Array.isArray(t))throw new Error("Context must be either an object or a string");if(this.isCompacted(e,t))try{let[i,r]=Object.entries(t).find(([s,o])=>e.startsWith(s));return e.replace(`${i}:`,r)}catch{return e}else return e;default:throw new Error("Context must be either an object or a string")}}static isCompacted(e,t){let i=!0;return Object.values(t).forEach(r=>{e.startsWith(r)&&(i=!1)}),i}},yd=class{static expandStructure(c){return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.expandType(c,t);break;default:this.expandValue(c,e,t);break}}),c}static expandType(c,e){typeof e=="string"?c["@type"]=[e]:c["@type"]=e}static expandValue(c,e,t){switch(typeof t){case"string":case"number":case"boolean":c[e]=[{"@value":t}];break;case"object":Array.isArray(t)?t.map(r=>{switch(typeof r){case"string":case"number":case"boolean":return[{"@value":t}];default:return r}}):c[e]=[t]}}static compactStructure(c){if(Array.isArray(c)){let[e]=c;return this.compactStructure(e)}else return Object.entries(c).forEach(([e,t])=>{switch(e){case"@id":break;case"@type":this.compactType(c,t);break;default:this.compactValue(c,e,t);break}}),c}static compactType(c,e){Array.isArray(e)&&e.length===1&&(c["@type"]=e[0])}static compactValue(c,e,t){if(t.length===1){let[i]=t;this.isWrappedScalar(i)?c[e]=i["@value"]:c[e]=i}else t.map(i=>this.isWrappedScalar(i)?i["@value"]:i)}static isWrappedScalar(c){return c["@value"]!==void 0}},yi=class{static process(c,e){let t=this.getGraph(c),i=this.getContext(c),r=Pm.empty().withNodes(t);t.forEach(o=>{e.embeddedLinks&&Rm.embedNodeLinks(o,r,e.linkEmbeddingFilter),i!==void 0&&(e.expandedIris?gd.expandIris(o,i):e.compactedIris&&gd.compactIris(o,i)),e.expandedStructure?yd.expandStructure(o):e.compactedStructure&&yd.compactStructure(o)});let s=e.rootNodeId===void 0?{"@graph":t}:this.findNode(t,e.rootNodeId);return i!==void 0&&(s["@context"]=i),e.expandedStructure?[s]:s}static getContext(c){return c["@context"]}static getGraph(c){return c["@graph"]}static findNode(c,e){return c.find(t=>t["@id"]===e)}static stringify(c,e=!1){return JSON.stringify(c,null,e?2:0)}},vd=class wd{expandedIris;expandedStructure;embeddedLinks;compactedIris;compactedStructure;rootNodeId;linkEmbeddingFilter;static apply(){return new wd}withCompactedStructure(){return this.expandedStructure=!1,this.compactedStructure=!0,this}withRootNode(e){return this.rootNodeId=e,this}withExpandedStructure(){return this.expandedStructure=!0,this.compactedStructure=!1,this}withExpandedIris(){return this.expandedIris=!0,this.compactedIris=!1,this}withCompactedIris(){return this.expandedIris=!1,this.compactedIris=!0,this}withEmbeddedLinks(e){return this.linkEmbeddingFilter=e,this.embeddedLinks=!0,this}},$m=class{static expand(c){if(this.isInExpandedForm(c))return c;{let e=(r,s)=>!r.endsWith("fixPoint");this.preprocessLegacyRootNodeId(c);let t=this.resolveRootNodeId(c),i=vd.apply().withEmbeddedLinks(e).withCompactedIris().withExpandedStructure().withRootNode(t);return yi.process(c,i)}}static isInExpandedForm(c){return c["@graph"]===void 0}static preprocessLegacyRootNodeId(c){let e=yi.getGraph(c);if(e!=null){let t=yi.findNode(e,"./");t!=null&&(t["@id"]="")}}static resolveRootNodeId(c){let e=yi.getGraph(c);if(e==null||yi.findNode(e,"")!=null)return"";let t=yi.getContext(c);if(t!=null&&t["@base"]!=null){let r=t["@base"];if(yi.findNode(e,r)!=null)return r}let i=e.find(r=>Object.entries(r).some(([s,o])=>(s==="doc:root"||s==="http://a.ml/vocabularies/document#root")&&o===!0));return i!=null?i["@id"]:""}}});import ch from"update-notifier";import{Command as lh}from"commander";var kt={name:"@api-now/cli",description:"API Now! CLI",version:"1.17.2",private:!1,publishConfig:{registry:"https://registry.npmjs.org/","@api-now:registry":"https://registry.npmjs.org/",access:"public"},files:["dist"],engines:{node:">=22.0.0"},type:"module",bin:{apinow:"dist/index.js"},scripts:{build:"node esbuild.config.js",postbuild:"node dist/index.js --help",dev:"tsx src/index.ts",typecheck:"tsc --noEmit",lint:'eslint "src/**/*.ts"',format:'prettier --write "src/**/*.ts"',test:"tsx --test tests/**/*.test.ts",prepare:"husky",prepublishOnly:"npm run build",knip:"knip"},dependencies:{"@inquirer/prompts":"^8.5.0",commander:"^15.0.0",dompurify:"^3.4.11",jsdom:"^30.0.1",nanoid:"^6.0.1",open:"^11.0.0",tslib:"^2.8.1","update-notifier":"^7.3.1",winston:"^3.19.0"},devDependencies:{"@api-now/core":"^1.55.1","@api-now/json":"^1.0.0","@commitlint/cli":"^21.0.1","@commitlint/config-conventional":"^21.0.1","@eslint/js":"^10.0.1","@semantic-release/changelog":"^7.0.0","@semantic-release/git":"^11.0.1","@types/node":"^26.2.0","@types/update-notifier":"^6.0.8",esbuild:"^0.28.0",eslint:"^10.4.0","eslint-config-prettier":"^10.1.8","eslint-plugin-prettier":"^5.5.6",globals:"^17.6.0",husky:"^9.1.7",knip:"^6.14.2",prettier:"^3.8.3","semantic-release":"^25.0.3",tsx:"^4.7.1",typescript:"^6.0.3","typescript-eslint":"^8.60.0"}};import Jn from"node:os";import Jt from"node:path";import Be from"node:fs";var _r="https://api.apinow.app",Wn="apinow-cli",Ap="config.json",Hn=class{_resolved=null;get resolved(){this._resolved||this.load();let e=this._resolved;if(!e)throw new Error("Configuration could not be loaded.");return e}configDir=this.#t();configPath=Jt.join(this.configDir,Ap);#e(e,t){if(!e.profiles&&(e.token||e.org||e.apiUrl)){let i={profiles:{default:{token:e.token||"",org:e.org,apiUrl:e.apiUrl||_r}},activeProfile:"default"};return t&&this.#o(i),i}return e}load(){let t=this.#r()??this.#s(),i=t.activeProfile,r=i&&t.profiles?t.profiles[i]:void 0,s=process.env.APINOW_API_TOKEN||process.env.APINOW_TOKEN||r?.token,o=process.env.APINOW_API_URL||r?.apiUrl||_r,a=r?.org||"";this._resolved={token:s,apiUrl:o,org:a,activeProfile:i,format:"text"}}saturate(e){this._resolved||this.load();let t=this._resolved;if(!t)throw new Error("Configuration could not be loaded.");this._resolved={token:t.token,apiUrl:t.apiUrl,org:t.org,activeProfile:t.activeProfile,format:e.format==="json"?"json":"text"}}listProfiles(){let e=this.#s();return e.profiles?{...e.profiles}:{}}getActiveProfile(){return this.#s().activeProfile}setActiveProfile(e){let t=this.#s();t.activeProfile=e,this.#o(t),this.load()}upsertProfile(e,t){let i=this.#s(),r=i.profiles?{...i.profiles}:{},s=r[e]||{token:""};r[e]={token:t.token!==void 0?t.token:s.token,org:t.org!==void 0?t.org:s.org,apiUrl:t.apiUrl!==void 0?t.apiUrl:s.apiUrl||_r},i.profiles=r,this.#o(i),this.load()}deleteProfile(e){let t=this.#s();if(t.profiles&&e in t.profiles){let i={...t.profiles};delete i[e],t.profiles=i,t.activeProfile===e&&delete t.activeProfile,this.#o(t),this.load()}}writeTokenToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,token:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}writeOrgToActiveProfile(e){let t=this.#s(),i=t.activeProfile||"default",r=t.profiles?{...t.profiles}:{},s=r[i]||{token:""};r[i]={...s,org:e},t.profiles=r,t.activeProfile=i,this.#o(t),this.load()}#t(){if(process.platform==="win32"){let e=process.env.APPDATA||Jt.join(Jn.homedir(),"AppData","Roaming");if(!e)throw new Error("Could not determine the configuration directory.");return Jt.join(e,Wn)}return process.platform==="darwin"?Jt.join(Jn.homedir(),"Library","Preferences",Wn):Jt.join(process.env.XDG_CONFIG_HOME||Jt.join(Jn.homedir(),".config"),Wn)}#i(){let e=process.cwd();for(;;){let t=Jt.join(e,"apinow.json");if(Be.existsSync(t))try{if(Be.statSync(t).isFile())return t}catch{}let i=Jt.join(e,".apinowrc.json");if(Be.existsSync(i))try{if(Be.statSync(i).isFile())return i}catch{}let r=Jt.dirname(e);if(r===e)break;e=r}return null}#r(){let e=this.#i();if(!e)return null;try{let t=Be.readFileSync(e,"utf8"),i=JSON.parse(t);return this.#e(i,!1)}catch{return null}}#s(){try{if(!Be.existsSync(this.configPath))return{};let e=Be.readFileSync(this.configPath,"utf8"),t=JSON.parse(e);return this.#e(t,!0)}catch{return{}}}writeProperty(e,t){let i=this.#s();e==="activeProfile"&&(i.activeProfile=t),this.#o(i),this.load()}#o(e){try{Be.existsSync(this.configDir)||Be.mkdirSync(this.configDir,{recursive:!0}),Be.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf8")}catch(t){console.error("Failed to write configuration:",t)}}clearConfigKey(e){try{let t=this.#s();delete t[e],this.#o(t),this.load()}catch(t){console.error(`Failed to clear key ${e} from configuration:`,t)}}reset(){try{Be.existsSync(this.configPath)&&Be.unlinkSync(this.configPath),Be.existsSync(this.configDir)&&Be.readdirSync(this.configDir).length===0&&Be.rmdirSync(this.configDir),this._resolved=null}catch(e){console.error("Failed to reset configuration:",e)}}},N=new Hn;import{styleText as Wi}from"node:util";import Ep from"node:path";import _p from"node:os";import xp from"node:crypto";import vt from"winston";var Ip=xp.randomBytes(4).toString("hex"),Pp=Date.now(),Ds=Ep.join(_p.tmpdir(),`apinow-cli-${Pp}-${Ip}.log`),dl=new vt.transports.Console({stderrLevels:Object.keys(vt.config.cli.levels),level:"info",format:vt.format.combine(vt.format.colorize(),vt.format.simple())}),Rp=new vt.transports.File({filename:Ds,level:"debug",format:vt.format.combine(vt.format.timestamp(),vt.format.printf(({timestamp:c,level:e,message:t})=>{let i=typeof t=="string"?t.replace(/\u001b\[\d+m/g,""):t;return`${c} [${e.toUpperCase()}]: ${i}`}))}),y=vt.createLogger({levels:vt.config.cli.levels,level:"debug",transports:[dl,Rp]});function pl(c){dl.level=c}var Yn=kt.version;var ie={green:c=>Wi("green",c),red:c=>Wi("red",c),yellow:c=>Wi("yellow",c),cyan:c=>Wi("cyan",c),dim:c=>Wi("dim",c),bold:c=>Wi("bold",c)};function $p(c,e,t){if(c.length===0)return"No data available.";let i={},r=t||e;for(let n=0;n<e.length;n++){let l=e[n],d=r[n]||l;i[l]=d.length}for(let n of c)for(let l of e){let d=typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"");d.length>(i[l]||0)&&(i[l]=d.length)}let s=e.map((n,l)=>(r[l]||n).toUpperCase().padEnd(i[n])).join(" "),o=e.map(n=>"-".repeat(i[n])).join(" "),a=c.map(n=>e.map(l=>(typeof n[l]=="object"&&n[l]!==null?JSON.stringify(n[l]):String(n[l]??"")).padEnd(i[l])).join(" "));return[s,o,...a].join(`
3
3
  `)}var K=class{format;constructor(e={}){this.format=e.format||"text"}success(e,t){this.format==="json"?console.log(JSON.stringify({success:!0,message:e,data:t},null,2)):(console.log(ie.green(`\u2714 ${e}`)),t!==void 0&&(typeof t=="object"&&t!==null?this.object(t):console.log(t)))}error(e){let t=e.code||"CLI_ERR_UNKNOWN";if(this.format==="json")console.error(JSON.stringify({success:!1,code:t,cliVersion:Yn,logFile:Ds,...e},null,2));else{if(console.error(ie.red(`\u2716 Error [${t}]: ${e.message}`)),e.detail&&console.error(ie.dim(e.detail)),e.errors&&e.errors.length>0){console.error(`
4
4
  Validation errors:`);for(let i of e.errors)console.error(` - ${ie.yellow(i.field)}: ${i.message}`)}if(console.error(ie.dim(`(cli v${Yn})`)),console.error(ie.dim(`Log file: ${Ds}`)),t==="CLI_ERR_UNKNOWN"){let i="https://github.com/api-now/cli",r=encodeURIComponent(`[BUG] CLI Crash: ${e.message}`),s=encodeURIComponent(`**CLI Version:** ${Yn}
5
5
  **Error Code:** ${t}
@@ -485,7 +485,7 @@ Active records only are clustered; soft-deleted records are automatically exclud
485
485
  ${s.join(`
486
486
  `)}`}emitActionValidator(e,t,i,r,s){let o=s??(i==="create"?"CreateInput":i==="update"?"UpdateInput":"PatchInput"),a=this.getAllowedProperties(e,i),n=this.getAllowedAssociations(e),l=[...a.map(p=>rt(p)),...n.map(p=>$t(p))],d=[];d.push("/**"),d.push(` * Validates data as ${r}. Throws SdkValidationError if invalid.`),d.push(" */"),d.push(`export function assert${o}(data: unknown): asserts data is ${r} {`),d.push(` const result = validate${o}(data)`),d.push(" if (!result.valid) {"),d.push(" throw new SdkValidationError(result.errors)"),d.push(" }"),d.push("}"),d.push(""),d.push("/**"),d.push(` * Validates data against the ${r} schema without throwing.`),d.push(" */"),d.push(`export function validate${o}(data: unknown): ValidationResult {`),d.push(" if (!data || typeof data !== 'object' || Array.isArray(data)) {"),d.push(" return {"),d.push(" valid: false,"),d.push(" errors: [{ field: '', message: 'Payload must be a non-null object', code: 'E_INVALID_PAYLOAD' }],"),d.push(" }"),d.push(" }"),d.push(""),d.push(" const record = data as Record<string, unknown>"),d.push(" const errors: ValidationErrorItem[] = []"),d.push(""),d.push(` const allowedFields = new Set<string>(${JSON.stringify(l)})`),d.push(" for (const key of Object.keys(record)) {"),d.push(" if (!allowedFields.has(key)) {"),d.push(" errors.push({ field: key, message: `Unknown field \"${key}\" is not allowed`, code: 'E_UNKNOWN_FIELD' })"),d.push(" }"),d.push(" }"),d.push("");for(let p of a){let m=rt(p),h=this.emitPropertyChecks(p,m,i);h.length>0&&(d.push(h.join(`
487
487
  `)),d.push(""))}if(i!=="patch"){for(let p of n)if(p.required){let m=$t(p);d.push(` if (record['${m}'] === undefined || record['${m}'] === null) {`),d.push(` errors.push({ field: '${m}', message: 'Required association is missing', code: 'E_REQUIRED_FIELD' })`),d.push(" }")}d.push("")}return d.push(" return { valid: errors.length === 0, errors }"),d.push("}"),d.join(`
488
- `)}emitPropertyChecks(e,t,i){let r=[],s=this.isRequiredOnAction(e,i),o=i==="patch";s&&(r.push(` if (record['${t}'] === undefined || record['${t}'] === null) {`),r.push(` errors.push({ field: '${t}', message: 'Field is required', code: 'E_REQUIRED_FIELD' })`),r.push(" }"));let a=[];if(a.push(...this.emitTypeCheck(e,t)),Array.isArray(e.schema?.enum)&&e.schema.enum.length>0){let n=JSON.stringify(e.schema.enum);a.push(` const allowedEnum = ${n}`),a.push(" if (!allowedEnum.includes(val as never)) {"),a.push(` errors.push({ field: '${t}', message: \`Value must be one of: \${allowedEnum.join(', ')}\`, code: 'E_INVALID_ENUM' })`),a.push(" }")}if(e.schema?.minimum!==void 0){let n=e.schema.minimum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must be at least ${n}', code: 'E_MIN_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must be at least ${n}', code: 'E_MIN_VALUE' })`),a.push(" }"))}if(e.schema?.maximum!==void 0){let n=e.schema.maximum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must not exceed ${n}', code: 'E_MAX_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must not exceed ${n}', code: 'E_MAX_VALUE' })`),a.push(" }"))}if(e.schema?.pattern){let n=JSON.stringify(e.schema.pattern);a.push(` if (typeof val === 'string' && !new RegExp(${n}).test(val)) {`),a.push(` errors.push({ field: '${t}', message: 'Value does not match required pattern', code: 'E_PATTERN_MISMATCH' })`),a.push(" }")}return a.length>0&&(r.push(` if (record['${t}'] !== undefined) {`),r.push(` const val = record['${t}']`),o?(r.push(" if (val !== null) {"),r.push(...a.map(n=>` ${n}`)),r.push(" }")):r.push(...a),r.push(" }")),r}emitTypeCheck(e,t){let i=[];if(e.multiple===!0)return i.push(" if (!Array.isArray(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an array', code: 'E_INVALID_TYPE' })`),i.push(" }"),i;switch(e.type){case"string":case"date":case"time":i.push(" if (typeof val !== 'string') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a string', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"number":i.push(" if (typeof val !== 'number' || Number.isNaN(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a valid number', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"boolean":i.push(" if (typeof val !== 'boolean') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a boolean', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"datetime":i.push(" if (typeof val !== 'string' && !(val instanceof Date)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an ISO date string or Date instance', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"json":i.push(" if (typeof val !== 'object' || val === null) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an object', code: 'E_INVALID_TYPE' })`),i.push(" }");break}return i}isRequiredOnAction(e,t){return!(t==="patch"||!e.required||e.schema?.defaultValue?.value!==void 0||t==="create"&&e.hasSemantic(g.PublicUniqueName))}getAllowedProperties(e,t){return Array.from(e.properties).filter(i=>!(i.readBinding("web")?.hidden||this.schemaGen.isSystemProperty(i)||i.readOnly===!0||t!=="create"&&i.immutable===!0))}getAllowedAssociations(e){return Array.from(e.associations).filter(t=>t.readBinding("web")?.hidden||this.schemaGen.isSystemAssociation(t)||t.readOnly===!0?!1:Array.from(t.listTargets()).length>0)}supportsPatchAction(e){return(Array.isArray(e)?e:[e]).some(i=>{let r=i.actions.find(s=>s.kind==="update");return!!(Array.isArray(r?.allowedMethods)&&r?.allowedMethods.includes("PATCH"))})}supportsUpdateAction(e){return(Array.isArray(e)?e:[e]).some(i=>i.actions.some(r=>r.kind==="update"))}};var tn=class{emitClient(e,t){let i=t?.baseUrl,r=!!i,s=this.resolveRootExposures(e),o=this.hasFileUpload(e),a=this.hasVerification(e),n=[];if(n.push("import { HttpTransport } from './transport.js'"),n.push("import { AuthManager } from './auth.js'"),s.length>0){let d=s.map(({resourceClassName:p})=>p).sort().join(", ");n.push(`import { ${d} } from './resources/index.js'`)}o&&n.push("import { FileUploadHelper } from './files.js'"),a&&n.push("import { VerificationHelper } from './verification.js'"),n.push(""),n.push("/**"),n.push(" * Options for configuring the ApiClient instance."),n.push(" */"),n.push("export interface ApiClientOptions {"),n.push(" /**"),n.push(" * Base URL for all API requests."),r&&n.push(` * @default '${i}'`),n.push(" */"),n.push(` baseUrl${r?"?":""}: string`),n.push(" /** Logging verbosity for network activity. */"),n.push(" logLevel?: 'error' | 'warn' | 'info' | 'debug'"),n.push(" /** Retry configuration for transient network errors. */"),n.push(" retry?: {"),n.push(" maxRetries?: number"),n.push(" backoffMs?: number"),n.push(" statusCodes?: number[]"),n.push(" retryNonIdempotent?: boolean"),n.push(" }"),n.push(" /** Custom headers to apply to every outgoing HTTP request. */"),n.push(" headers?: Record<string, string>"),n.push(" /** Initial authentication bearer token. */"),n.push(" token?: string"),n.push(" /** Custom fetch implementation (e.g. for testing or Node environments without global fetch). */"),n.push(" fetch?: typeof fetch"),n.push("}"),n.push(""),n.push("/**"),n.push(" * Main API Client providing typed resource accessors and session management."),n.push(" *"),n.push(" * ### Use when:"),n.push(" * - Initializing the API SDK in your application."),n.push(" * - Accessing REST resources, authenticating, or uploading files."),n.push(" *"),n.push(" * ### Don't use when:"),n.push(" * - Performing direct unformatted HTTP requests."),n.push(" */"),n.push("export class ApiClient {"),n.push(" public readonly transport: HttpTransport"),n.push(" public readonly auth: AuthManager");for(let{propName:d,resourceClassName:p}of s)n.push(` public readonly ${d}: ${p}`);o&&n.push(" public readonly files: FileUploadHelper"),a&&n.push(" public readonly verification: VerificationHelper"),n.push("");let l=r?"options: ApiClientOptions = {}":"options: ApiClientOptions";n.push(` constructor(${l}) {`),n.push(" const transportOptions = {"),n.push(" ...options,"),r&&n.push(` baseUrl: options.baseUrl ?? '${i}',`),n.push(" }"),n.push(" this.transport = new HttpTransport(transportOptions)"),n.push(" this.auth = new AuthManager(this.transport)"),n.push(" this.transport.setAuthManager(this.auth)"),n.push(" if (options.token) {"),n.push(" this.auth.setToken(options.token)"),n.push(" }");for(let{propName:d,resourceClassName:p}of s)n.push(` this.${d} = new ${p}(this.transport)`);return o&&n.push(" this.files = new FileUploadHelper(this.transport)"),a&&n.push(" this.verification = new VerificationHelper(this.transport)"),n.push(" }"),n.push("}"),n.push(""),n.join(`
488
+ `)}emitPropertyChecks(e,t,i){let r=[],s=this.isRequiredOnAction(e,i),o=i==="patch";s&&(r.push(` if (record['${t}'] === undefined || record['${t}'] === null) {`),r.push(` errors.push({ field: '${t}', message: 'Field is required', code: 'E_REQUIRED_FIELD' })`),r.push(" }"));let a=[];if(a.push(...this.emitTypeCheck(e,t)),Array.isArray(e.schema?.enum)&&e.schema.enum.length>0){let n=JSON.stringify(e.schema.enum);a.push(` const allowedEnum = ${n}`),a.push(" if (!allowedEnum.includes(val as never)) {"),a.push(` errors.push({ field: '${t}', message: \`Value must be one of: \${allowedEnum.join(', ')}\`, code: 'E_INVALID_ENUM' })`),a.push(" }")}if(e.schema?.minimum!==void 0){let n=e.schema.minimum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must be at least ${n}', code: 'E_MIN_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val < ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must be at least ${n}', code: 'E_MIN_VALUE' })`),a.push(" }"))}if(e.schema?.maximum!==void 0){let n=e.schema.maximum;e.type==="string"?(a.push(` if (typeof val === 'string' && val.length > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Length must not exceed ${n}', code: 'E_MAX_LENGTH' })`),a.push(" }")):e.type==="number"&&(a.push(` if (typeof val === 'number' && val > ${n}) {`),a.push(` errors.push({ field: '${t}', message: 'Value must not exceed ${n}', code: 'E_MAX_VALUE' })`),a.push(" }"))}if(e.schema?.pattern){let n=JSON.stringify(e.schema.pattern);a.push(` if (typeof val === 'string' && !new RegExp(${n}).test(val)) {`),a.push(` errors.push({ field: '${t}', message: 'Value does not match required pattern', code: 'E_PATTERN_MISMATCH' })`),a.push(" }")}return a.length>0&&(r.push(` if (record['${t}'] !== undefined) {`),r.push(` const val = record['${t}']`),o?(r.push(" if (val !== null) {"),r.push(...a.map(n=>` ${n}`)),r.push(" }")):r.push(...a),r.push(" }")),r}emitTypeCheck(e,t){let i=[];if(e.multiple===!0)return i.push(" if (!Array.isArray(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an array', code: 'E_INVALID_TYPE' })`),i.push(" }"),i;switch(e.type){case"string":case"date":case"time":i.push(" if (typeof val !== 'string') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a string', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"number":i.push(" if (typeof val !== 'number' || Number.isNaN(val)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a valid number', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"boolean":i.push(" if (typeof val !== 'boolean') {"),i.push(` errors.push({ field: '${t}', message: 'Value must be a boolean', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"datetime":i.push(" if (typeof val !== 'string' && !(val instanceof Date)) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an ISO date string or Date instance', code: 'E_INVALID_TYPE' })`),i.push(" }");break;case"json":i.push(" if (typeof val !== 'object' || val === null) {"),i.push(` errors.push({ field: '${t}', message: 'Value must be an object', code: 'E_INVALID_TYPE' })`),i.push(" }");break}return i}isRequiredOnAction(e,t){return!(t==="patch"||!e.required||e.schema?.defaultValue?.value!==void 0||t==="create"&&e.hasSemantic(g.PublicUniqueName))}getAllowedProperties(e,t){return Array.from(e.properties).filter(i=>!(i.readBinding("web")?.hidden||this.schemaGen.isSystemProperty(i)||i.readOnly===!0||t!=="create"&&i.immutable===!0))}getAllowedAssociations(e){return Array.from(e.associations).filter(t=>t.readBinding("web")?.hidden||this.schemaGen.isSystemAssociation(t)||t.readOnly===!0?!1:Array.from(t.listTargets()).length>0)}supportsPatchAction(e){return(Array.isArray(e)?e:[e]).some(i=>{let r=i.actions.find(s=>s.kind==="update");return!!(Array.isArray(r?.allowedMethods)&&r?.allowedMethods.includes("PATCH"))})}supportsUpdateAction(e){return(Array.isArray(e)?e:[e]).some(i=>i.actions.some(r=>r.kind==="update"))}};var tn=class{emitClient(e,t){let i=t?.baseUrl,r=!!i,s=this.resolveRootExposures(e),o=this.hasFileUpload(e),a=this.hasVerification(e),n=[];if(n.push("import { HttpTransport } from './transport.js'"),n.push("import { AuthManager } from './auth.js'"),s.length>0){let d=s.map(({resourceClassName:p})=>p).sort().join(", ");n.push(`import { ${d} } from './resources/index.js'`)}o&&n.push("import { FileUploadHelper } from './files.js'"),a&&n.push("import { VerificationHelper } from './verification.js'"),n.push(""),n.push("/**"),n.push(" * Options for configuring the ApiClient instance."),n.push(" */"),n.push("export interface ApiClientOptions {"),n.push(" /**"),n.push(" * Base URL for all API requests."),r&&n.push(` * @default '${i}'`),n.push(" */"),n.push(` baseUrl${r?"?":""}: string`),n.push(" /** Logging verbosity for network activity. */"),n.push(" logLevel?: 'silent' | 'error' | 'warn' | 'info' | 'debug'"),n.push(" /** Retry configuration for transient network errors. */"),n.push(" retry?: {"),n.push(" maxRetries?: number"),n.push(" backoffMs?: number"),n.push(" statusCodes?: number[]"),n.push(" retryNonIdempotent?: boolean"),n.push(" }"),n.push(" /** Custom headers to apply to every outgoing HTTP request. */"),n.push(" headers?: Record<string, string>"),n.push(" /** Initial authentication bearer token. */"),n.push(" token?: string"),n.push(" /** Custom fetch implementation (e.g. for testing or Node environments without global fetch). */"),n.push(" fetch?: typeof fetch"),n.push("}"),n.push(""),n.push("/**"),n.push(" * Main API Client providing typed resource accessors and session management."),n.push(" *"),n.push(" * ### Use when:"),n.push(" * - Initializing the API SDK in your application."),n.push(" * - Accessing REST resources, authenticating, or uploading files."),n.push(" *"),n.push(" * ### Don't use when:"),n.push(" * - Performing direct unformatted HTTP requests."),n.push(" */"),n.push("export class ApiClient {"),n.push(" public readonly transport: HttpTransport"),n.push(" public readonly auth: AuthManager");for(let{propName:d,resourceClassName:p}of s)n.push(` public readonly ${d}: ${p}`);o&&n.push(" public readonly files: FileUploadHelper"),a&&n.push(" public readonly verification: VerificationHelper"),n.push("");let l=r?"options: ApiClientOptions = {}":"options: ApiClientOptions";n.push(` constructor(${l}) {`),n.push(" const transportOptions = {"),n.push(" ...options,"),r&&n.push(` baseUrl: options.baseUrl ?? '${i}',`),n.push(" }"),n.push(" this.transport = new HttpTransport(transportOptions)"),n.push(" this.auth = new AuthManager(this.transport)"),n.push(" this.transport.setAuthManager(this.auth)"),n.push(" if (options.token) {"),n.push(" this.auth.setToken(options.token)"),n.push(" }");for(let{propName:d,resourceClassName:p}of s)n.push(` this.${d} = new ${p}(this.transport)`);return o&&n.push(" this.files = new FileUploadHelper(this.transport)"),a&&n.push(" this.verification = new VerificationHelper(this.transport)"),n.push(" }"),n.push("}"),n.push(""),n.join(`
489
489
  `)}hasFileUpload(e){if(!e.domain)return!1;for(let t of e.exposes.values()){let i=e.domain.findEntity(t.entity.key);if(i){for(let r of i.properties)if(r.semantics.some(s=>s.id===g.FileURL||s.id===g.ImageURL))return!0}}return!1}hasVerification(e){if(!e.domain)return!1;for(let t of e.exposes.values()){let i=e.domain.findEntity(t.entity.key);if(i)for(let r of i.properties){let s=r.semantics.find(a=>a.id===g.Email);if(s&&((s.config||{}).requireVerification??!0))return!0;let o=r.semantics.find(a=>a.id===g.Phone);if(o&&((o.config||{}).requireVerification??!1))return!0}}return!1}resolveRootExposures(e){let t=[];for(let i of e.exposes.values()){if(i.parent)continue;let r=e.domain?.findEntity(i.entity.key);if(!r)continue;let o=`${ce(r.getExposedName())}Resource`,a=this.getClientPropertyName(i,r);t.push({expose:i,entity:r,propName:a,resourceClassName:o})}return t.sort((i,r)=>i.propName.localeCompare(r.propName))}getClientPropertyName(e,t){if(e.collectionPath){let i=e.collectionPath.split("/").filter(Boolean);if(i.length>0)return ht(i[i.length-1])}return ht(t.getExposedName())}};var rn=class{emitAuthManager(e){let t=e.authentication?.strategy==="UsernamePassword",{usernameField:i,passwordField:r}=this.resolveCredentialFields(e),s=[];return s.push("import { HttpTransport } from './transport.js'"),s.push(""),t&&(s.push("/**"),s.push(" * Credentials required to authenticate via username/password."),s.push(" */"),s.push("export interface LoginCredentials {"),s.push(" /** The user identifier. */"),s.push(` ${i}: string`),s.push(" /** The account password. */"),s.push(` ${r}: string`),s.push("}"),s.push("")),s.push("/**"),s.push(" * Response data returned from a successful authentication call."),s.push(" */"),s.push("export interface LoginResponse {"),s.push(" success: boolean"),s.push(" token?: string"),s.push("}"),s.push(""),s.push("/**"),s.push(" * Manages authentication lifecycle, bearer tokens, and session headers for the API client."),s.push(" *"),s.push(" * ### Use when:"),s.push(" * - Logging in, logging out, or inspecting authentication status."),s.push(" * - Providing authorization headers for HTTP requests."),s.push(" * - Restoring existing session tokens from persistent client storage."),s.push(" * ### Don't use when:"),s.push(" * - Managing database user records or hashing passwords."),s.push(" */"),s.push("export class AuthManager {"),s.push(" private token: string | null = null"),s.push(""),s.push(" constructor(private readonly transport: HttpTransport) {}"),s.push(""),t&&(s.push(" /**"),s.push(" * Authenticates with the API and stores the returned session token."),s.push(" *"),s.push(" * @param credentials Login credentials."),s.push(" * @returns Login response payload."),s.push(" */"),s.push(" public async login(credentials: LoginCredentials): Promise<LoginResponse> {"),s.push(" const response = await this.transport.request<{ data: LoginResponse }>("),s.push(" '/auth/login',"),s.push(" {"),s.push(" method: 'POST',"),s.push(" body: JSON.stringify(credentials),"),s.push(" }"),s.push(" )"),s.push(" const data = response?.data ?? { success: true }"),s.push(" if (data.token) {"),s.push(" this.token = data.token"),s.push(" }"),s.push(" return data"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Logs out of the API and removes the stored session token."),s.push(" */"),s.push(" public async logout(): Promise<void> {"),s.push(" try {"),s.push(" await this.transport.request('/auth/logout', { method: 'POST' })"),s.push(" } finally {"),s.push(" this.token = null"),s.push(" }"),s.push(" }"),s.push("")),s.push(" /**"),s.push(" * Checks whether an active authentication token is currently present."),s.push(" */"),s.push(" public isAuthenticated(): boolean {"),s.push(" return Boolean(this.token)"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Returns the current session token or null if not authenticated."),s.push(" */"),s.push(" public getToken(): string | null {"),s.push(" return this.token"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Manually sets or clears the active session token."),s.push(" */"),s.push(" public setToken(token: string | null): void {"),s.push(" this.token = token"),s.push(" }"),s.push(""),s.push(" /**"),s.push(" * Returns authentication headers to include with outgoing requests."),s.push(" */"),s.push(" public getAuthHeaders(): Record<string, string> {"),s.push(" if (!this.token) {"),s.push(" return {}"),s.push(" }"),s.push(" return {"),s.push(" Authorization: `Bearer ${this.token}`,"),s.push(" }"),s.push(" }"),s.push("}"),s.push(""),s.join(`
490
490
  `)}resolveCredentialFields(e){let t="username",i="password";if(e.user&&e.domain){let r=e.domain.findEntity(e.user.key);if(r){let s=Array.from(r.properties),o=s.find(n=>n.semantics.some(l=>l.id===g.Username||l.id===g.Email)),a=s.find(n=>n.semantics.some(l=>l.id===g.Password));o&&(t=rt(o)),a&&(i=rt(a))}}return{usernameField:t,passwordField:i}}};var sn=class{emitPagination(e){return(e&&typeof e=="object"&&"pagination"in e?e.pagination:e)?.kind==="offset"?this.emitOffsetPagination():this.emitCursorPagination()}emitOffsetPagination(){return`/**
491
491
  * Envelope for offset/page-number based pagination responses.
@@ -733,9 +733,9 @@ export interface HttpTransportOptions {
733
733
  baseUrl?: string
734
734
  /**
735
735
  * Logging verbosity level.
736
- * @default 'info'
736
+ * @default 'silent'
737
737
  */
738
- logLevel?: 'error' | 'warn' | 'info' | 'debug'
738
+ logLevel?: 'silent' | 'error' | 'warn' | 'info' | 'debug'
739
739
  /**
740
740
  * Retry configuration for transient network errors.
741
741
  */
@@ -825,7 +825,7 @@ export interface AuthHeaderProvider {
825
825
  */
826
826
  export class HttpTransport {
827
827
  private readonly baseUrl: string
828
- private readonly logLevel: 'error' | 'warn' | 'info' | 'debug'
828
+ private readonly logLevel: 'silent' | 'error' | 'warn' | 'info' | 'debug'
829
829
  private readonly retryOptions: Required<RetryOptions>
830
830
  private readonly customHeaders: Record<string, string>
831
831
  private readonly fetchFn: typeof fetch
@@ -834,7 +834,7 @@ export class HttpTransport {
834
834
 
835
835
  constructor(options: HttpTransportOptions = {}) {
836
836
  this.baseUrl = (options.baseUrl || '').replace(/\\/+$/, '')
837
- this.logLevel = options.logLevel || 'info'
837
+ this.logLevel = options.logLevel ?? 'silent'
838
838
  this.retryOptions = {
839
839
  maxRetries: options.retry?.maxRetries ?? 3,
840
840
  backoffMs: options.retry?.backoffMs ?? 250,
@@ -1279,8 +1279,21 @@ export class HttpTransport {
1279
1279
  * Emits internal log entries according to configured log level.
1280
1280
  */
1281
1281
  private log(method: string, url: string, status: number, durationMs: number): void {
1282
- if (this.logLevel === 'debug' || (this.logLevel === 'info' && status >= 400)) {
1283
- // Internal telemetry hook - no console spam in default configurations
1282
+ if (this.logLevel === 'silent') {
1283
+ return
1284
+ }
1285
+
1286
+ const formatted = \`[SDK HTTP] \${method.toUpperCase()} \${url} \${status} (\${durationMs}ms)\`
1287
+ if (status >= 500) {
1288
+ console.error(formatted)
1289
+ } else if (status >= 400) {
1290
+ if (this.logLevel === 'warn' || this.logLevel === 'info' || this.logLevel === 'debug') {
1291
+ console.warn(formatted)
1292
+ }
1293
+ } else if (this.logLevel === 'info') {
1294
+ console.info(formatted)
1295
+ } else if (this.logLevel === 'debug') {
1296
+ console.debug(formatted)
1284
1297
  }
1285
1298
  }
1286
1299
  }
@@ -1692,7 +1705,7 @@ export interface SearchWhereOperatorMap {
1692
1705
  * Recursive boolean AST query node.
1693
1706
  */
1694
1707
  export type SearchWhereNode =
1695
- | { [field: string]: SearchWhereOperatorMap }
1708
+ | Record<string, SearchWhereOperatorMap>
1696
1709
  | { and: SearchWhereNode[] }
1697
1710
  | { or: SearchWhereNode[] }
1698
1711
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@api-now/cli",
3
3
  "description": "API Now! CLI",
4
- "version": "1.17.1",
4
+ "version": "1.17.2",
5
5
  "private": false,
6
6
  "publishConfig": {
7
7
  "registry": "https://registry.npmjs.org/",