@api-now/cli 1.0.4 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/index.js +129 -79
- package/package.json +7 -3
- package/dist/commands/auth.js +0 -314
- package/dist/commands/catalog.js +0 -289
- package/dist/commands/config.js +0 -59
- package/dist/commands/files.js +0 -293
- package/dist/commands/orgs.js +0 -104
- package/dist/commands/tokens.js +0 -145
- package/dist/utils/api.js +0 -54
- package/dist/utils/config.js +0 -202
- package/dist/utils/formatter.js +0 -195
- package/dist/utils/org-setup.js +0 -96
- package/dist/utils/prompt.js +0 -41
package/README.md
CHANGED
|
@@ -127,7 +127,17 @@ apinow catalog list --scope <all|public|organization|private> [--key <domain_key
|
|
|
127
127
|
## Development
|
|
128
128
|
|
|
129
129
|
### Local Setup & Building
|
|
130
|
-
|
|
130
|
+
|
|
131
|
+
> [!NOTE]
|
|
132
|
+
> This project depends on private workspace packages (such as `@api-now/core`) during development and local testing. Before running `npm install`, ensure you have configured a local `.npmrc` file at the root of the workspace with access to the private registry.
|
|
133
|
+
>
|
|
134
|
+
> Example `.npmrc`:
|
|
135
|
+
> ```ini
|
|
136
|
+
> @api-now:registry=https://registry.npmjs.org/
|
|
137
|
+
> //registry.npmjs.org/:_authToken=YOUR_NPM_TOKEN
|
|
138
|
+
> ```
|
|
139
|
+
|
|
140
|
+
1. Clone the repository, set up your `.npmrc`, and install dependencies:
|
|
131
141
|
```bash
|
|
132
142
|
npm install
|
|
133
143
|
```
|
package/dist/index.js
CHANGED
|
@@ -1,83 +1,133 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
// Guard Node.js version >= 22
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
process.exit(1);
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
2
|
+
import ze from"update-notifier";import{Command as Be}from"commander";var ot={name:"@api-now/cli",description:"API Now! CLI",version:"1.1.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",nanoid:"^5.1.6",open:"^11.0.0",tslib:"^2.8.1","update-notifier":"^7.3.1"},devDependencies:{"@api-now/core":"^1.0.0","@commitlint/cli":"^21.0.1","@commitlint/config-conventional":"^21.0.1","@eslint/js":"^10.0.1","@semantic-release/changelog":"^6.0.3","@semantic-release/git":"^10.0.1","@types/node":"^25.9.1","@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 Ft from"node:os";import H from"node:path";import x from"node:fs";var Et="http://localhost:8080",jt="apinow-cli",Ne="config.json",zt=class{_resolved=null;get resolved(){this._resolved||this.load();let t=this._resolved;if(!t)throw new Error("Configuration could not be loaded.");return t}configDir=this.#t();configPath=H.join(this.configDir,Ne);load(){let t=this.#e(),e=process.env.APINOW_API_TOKEN||process.env.APINOW_TOKEN||t.token,o=process.env.APINOW_API_URL||t.apiUrl||Et,n=t.org||"";this._resolved={token:e,apiUrl:o,org:n,format:"text"}}saturate(t){this._resolved||this.load();let e=this._resolved;if(!e)throw new Error("Configuration could not be loaded.");this._resolved={token:e.token,apiUrl:t.apiUrl||e.apiUrl,org:e.org,format:t.format==="json"?"json":"text"}}#t(){if(process.platform==="win32"){let t=process.env.APPDATA||H.join(Ft.homedir(),"AppData","Roaming");if(!t)throw new Error("Could not determine the configuration directory.");return H.join(t,jt)}return process.platform==="darwin"?H.join(Ft.homedir(),"Library","Preferences",jt):H.join(process.env.XDG_CONFIG_HOME||H.join(Ft.homedir(),".config"),jt)}#e(){try{if(!x.existsSync(this.configPath))return{apiUrl:Et};let t=x.readFileSync(this.configPath,"utf8"),e=JSON.parse(t);return{apiUrl:Et,...e}}catch{return{apiUrl:Et}}}writeProperty(t,e){let o=this.#e();o[t]=e,this.#s(o)}#s(t){try{let o={...this.#e(),...t};x.existsSync(this.configDir)||x.mkdirSync(this.configDir,{recursive:!0}),x.writeFileSync(this.configPath,JSON.stringify(o,null,2),"utf8")}catch(e){console.error("Failed to write configuration:",e)}}clearConfigKey(t){try{let e=this.#e();delete e[t],x.existsSync(this.configDir)||x.mkdirSync(this.configDir,{recursive:!0}),x.writeFileSync(this.configPath,JSON.stringify(e,null,2),"utf8")}catch(e){console.error(`Failed to clear key ${t} from configuration:`,e)}}reset(){try{x.existsSync(this.configPath)&&x.unlinkSync(this.configPath),x.existsSync(this.configDir)&&x.readdirSync(this.configDir).length===0&&x.rmdirSync(this.configDir),this._resolved=null}catch(t){console.error("Failed to reset configuration:",t)}}},w=new zt;import{styleText as Y}from"node:util";var Bt=ot.version;var v={green:d=>Y("green",d),red:d=>Y("red",d),yellow:d=>Y("yellow",d),cyan:d=>Y("cyan",d),dim:d=>Y("dim",d),bold:d=>Y("bold",d)};function Q(d,t){(process.argv.includes("--debug")||process.argv.includes("--verbose")||typeof process<"u"&&process.env.DEBUG&&(process.env.DEBUG==="*"||process.env.DEBUG.includes("apinow")))&&console.error(v.dim(`[debug][${d}] ${t}`))}function be(d,t,e){if(d.length===0)return"No data available.";let o={},n=e||t;for(let a=0;a<t.length;a++){let c=t[a],u=n[a]||c;o[c]=u.length}for(let a of d)for(let c of t){let u=typeof a[c]=="object"&&a[c]!==null?JSON.stringify(a[c]):String(a[c]??"");u.length>(o[c]||0)&&(o[c]=u.length)}let r=t.map((a,c)=>(n[c]||a).toUpperCase().padEnd(o[a])).join(" "),s=t.map(a=>"-".repeat(o[a])).join(" "),i=d.map(a=>t.map(c=>(typeof a[c]=="object"&&a[c]!==null?JSON.stringify(a[c]):String(a[c]??"")).padEnd(o[c])).join(" "));return[r,s,...i].join(`
|
|
3
|
+
`)}var $=class{format;constructor(t={}){this.format=t.format||"text"}success(t,e){this.format==="json"?console.log(JSON.stringify({success:!0,message:t,data:e},null,2)):(console.log(v.green(`\u2714 ${t}`)),e!==void 0&&(typeof e=="object"&&e!==null?this.object(e):console.log(e)))}error(t){let e=t.code||"CLI_ERR_UNKNOWN";if(this.format==="json")console.error(JSON.stringify({success:!1,code:e,cliVersion:Bt,...t},null,2));else{if(console.error(v.red(`\u2716 Error [${e}]: ${t.message}`)),t.detail&&console.error(v.dim(t.detail)),t.errors&&t.errors.length>0){console.error(`
|
|
4
|
+
Validation errors:`);for(let o of t.errors)console.error(` - ${v.yellow(o.field)}: ${o.message}`)}if(console.error(v.dim(`(cli v${Bt})`)),e==="CLI_ERR_UNKNOWN"){let o="https://github.com/api-now/cli",n=encodeURIComponent(`[BUG] CLI Crash: ${t.message}`),r=encodeURIComponent(`**CLI Version:** ${Bt}
|
|
5
|
+
**Error Code:** ${e}
|
|
6
|
+
|
|
7
|
+
**Error Message:**
|
|
8
|
+
${t.message}
|
|
9
|
+
|
|
10
|
+
**Error Details / Stack:**
|
|
11
|
+
\`\`\`
|
|
12
|
+
${t.detail||"No stack trace available"}
|
|
13
|
+
\`\`\`
|
|
14
|
+
`),s=`${o}/issues/new?title=${n}&body=${r}`;console.error(`
|
|
15
|
+
Please report this bug: ${s}`)}}}list(t,e,o={}){if(this.format==="json")console.log(JSON.stringify(t,null,2));else{if(t.length===0){console.log("No records found.");return}console.log(be(t,e,o.headers))}}object(t){let e=t;if(this.format==="json")console.log(JSON.stringify(e,null,2));else for(let[o,n]of Object.entries(e)){let r=typeof n=="object"&&n!==null?JSON.stringify(n):String(n);console.log(`${v.bold(o)}: ${r}`)}}};function re(d){let t=d.command("config").description("Manage CLI configuration settings");t.command("get <key>").description("Get a configuration value").action(e=>{let o=new $({format:w.resolved.format}),n=w.resolved;if(e in n){let r=n[e];w.resolved.format==="json"?o.object({[e]:r}):console.log(r)}else o.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Configuration key '${e}' not found.`,detail:`Run \`apinow config set ${e} <value>\` to define it.`}),process.exit(1)}),t.command("set <key> <value>").description("Set a configuration value").action((e,o)=>{let n=new $({format:w.resolved.format}),r=["apiUrl","token","org"];r.includes(e)||(n.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid configuration key '${e}'.`,detail:`Allowed keys: ${r.join(", ")}`}),process.exit(1)),w.writeProperty(e,o),n.success(`Configuration '${e}' set to '${o}'.`)}),t.command("reset").description("Reset all configuration settings and remove stored files").action(()=>{let e=new $({format:w.resolved.format});w.reset(),e.success("Configuration has been reset successfully.")})}import{Argument as Ce}from"commander";import Ue from"node:http";import Pe from"open";import ae from"http";import de from"https";function rt(d){return typeof d!="string"&&(d=String(d)),d.toLowerCase()}function ne(d){return typeof d!="string"&&(d=String(d)),d}function*Ae(d){if(!d||d.trim()==="")return[];let t=d.split(/\n(?=[^ \t]+)/gim);for(let e=0,o=t.length;e<o;e++){let n=t[e].trim();if(n==="")continue;let r=n.startsWith("#");r&&(n=n.replace("#","").trim());let s=n.indexOf(":");if(s===-1)yield{name:n,value:"",enabled:!r};else{let i=n.substring(0,s),a=n.substring(s+1).trim();yield{name:i,value:a,enabled:!r}}}}var nt=class d{_map={};constructor(t){if(t instanceof d)t.forEach((e,o)=>this.append(o,e));else if(typeof t=="string")for(let e of Ae(t))this.append(e.name,e.value,e.enabled);else t&&Object.keys(t).forEach(e=>this.append(e,t[e]))}append(t,e,o=!0){if(Array.isArray(e)){e.forEach(s=>this.append(t,s));return}let n=rt(t);e=e?ne(e):"";let r=this._map[n];if(r){let s=r.value;r.value=s?`${s},${e}`:e}else r={name:t,value:e,enabled:o};this._map[n]=r}delete(t){delete this._map[rt(t)]}get(t){if(t=rt(t),!!this.has(t)&&this._map[t].enabled)return this._map[t].value}has(t){let e=rt(t);return Object.prototype.hasOwnProperty.call(this._map,e)&&this._map[e].enabled}set(t,e,o=!0){let n=rt(t);this._map[n]={value:ne(e),name:t,enabled:o}}forEach(t,e){Object.keys(this._map).forEach(n=>{let r=this._map[n];t.call(e,r.value,r.name,r.enabled,this)})}map(t,e){let o=Object.keys(this._map),n=[];for(let r of o){let s=this._map[r],i=t.call(e,s.value,s.name,s.enabled);n.push(i)}return n}toString(){return this._generateString()}toRawString(){return this._generateString(!0)}toJSON(){let t={};for(let[e,o]of this.entries())t[e]=o;return t}_generateString(t=!1){let e=[],o=Object.keys(this._map);for(let n of o){let r=this._map[n],s="";if(!r.enabled)if(t)s+="# ";else continue;s+=`${r.name}: `,r.value&&(s+=r.value),e.push(s)}return e.join(`
|
|
16
|
+
`)}*keys(){let t=Object.keys(this._map);for(let e of t)this._map[e].enabled&&(yield this._map[e].name)}*values(){let t=Object.keys(this._map);for(let e of t)this._map[e].enabled&&(yield this._map[e].value)}*entries(){let t=Object.keys(this._map);for(let e of t)this._map[e].enabled&&(yield[this._map[e].name,this._map[e].value])}*[Symbol.iterator](){let t=Object.keys(this._map);for(let e of t)this._map[e].enabled&&(yield[this._map[e].name,this._map[e].value])}};var l=class extends Error{name;status;static fromRawException(t,e){let o=t,n={};if(o.code!==void 0&&(n.code=String(o.code)),o.status!==void 0){let i=Number(o.status);isNaN(i)||(n.status=i)}o.help!==void 0&&(n.help=String(o.help));let r=o.message!==void 0?String(o.message):e,s=new this(r,n);return o.name!==void 0&&(s.name=String(o.name)),s}constructor(t,e){super(t,e);let o=this.constructor;this.name=o.name,this.message=t??o.message??"",this.status=e?.status??o.status??500;let n=e?.code??o.code;n!==void 0&&(this.code=n);let r=e?.help??o.help;r!==void 0&&(this.help=r),Error.captureStackTrace(this,o)}setHelp(t){return this.help=t,this}setCode(t){return this.code=t,this}setStatus(t){return this.status=t,this}get[Symbol.toStringTag](){return this.constructor.name}toString(){return this.code?`${this.name} [${this.code}]: ${this.message}`:`${this.name}: ${this.message}`}toJSON(){let t={name:this.name,message:this.message};return this.status&&(t.status=this.status),this.code&&(t.code=this.code),this.help&&(t.help=this.help),t}};var S="Invalid JSON response.",k="The response has no value.",f="Invalid response status: ",N="Unknown response from the server.";var _=class{sdk;constructor(t){this.sdk=t}logInvalidResponse(t){if(!this.sdk.silent&&t.body)try{let e=JSON.parse(t.body);e.message&&console.warn(`[Store message]: ${e.message}`)}catch{}}inspectCommonStatusCodes(t){let{status:e,body:o}=t;if(e===404){let n=this.createApiError("Not found",o);throw n.status!==404&&n.setStatus(404),n.code!=="E_NOT_FOUND"&&n.setCode("E_NOT_FOUND"),n}if(e===403){let n=this.createApiError("You have no access to this resource",o);throw n.status!==403&&n.setStatus(403),n.code!=="E_FORBIDDEN"&&n.setCode("E_FORBIDDEN"),n}if(e===401){let n=this.createApiError("Not authorized",o);throw n.status!==401&&n.setStatus(401),n.code!=="E_UNAUTHORIZED"&&n.setCode("E_UNAUTHORIZED"),n}}createApiError(t,e){if(!e)return new l(t);let o;try{o=JSON.parse(e)}catch{return new l(t)}return!o||typeof o!="object"||!o.message?new l(t):l.fromRawException(o,t)}async genericBatchDelete(t,e,o={}){let{token:n}=o,r=await this.sdk.http.post(t.toString(),{token:n,body:JSON.stringify(e)});this.inspectCommonStatusCodes(r);let s="Unable to delete in batch. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);if(!r.body)throw new l(`${s}${k}`,{code:"E_RESPONSE_NO_VALUE",status:r.status});let i;try{i=JSON.parse(r.body)}catch{throw new l(`${s}${S}`,{code:"E_INVALID_JSON",status:r.status})}if(!Array.isArray(i.data))throw new l(`${s}${N}`,{code:"E_RESPONSE_UNKNOWN",status:r.status});return i}async genericDelete(t,e={}){let{token:o}=e,n=await this.sdk.http.delete(t.toString(),{token:o});this.inspectCommonStatusCodes(n);let r="Unable to delete the object. ";if(n.status!==204)throw this.logInvalidResponse(n),this.createApiError(`${r}${f}${n.status}`,n.body)}async genericList(t,e,o={}){let{token:n}=o;this.sdk.appendListOptions(t,e);let r=await this.sdk.http.get(t.toString(),{token:n});this.inspectCommonStatusCodes(r);let s="Unable to list revisions for a file. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);if(!r.body)throw new l(`${s}${k}`,{code:"E_RESPONSE_NO_VALUE",status:r.status});let i;try{i=JSON.parse(r.body)}catch{throw new l(`${s}${S}`,{code:"E_INVALID_JSON",status:r.status})}if(!Array.isArray(i.data))throw new l(`${s}${N}`,{code:"E_RESPONSE_UNKNOWN",status:r.status});return i}readResponseBody(t,e){if(![200,202].includes(t.status))throw this.logInvalidResponse(t),this.createApiError(`${e}${f}${t.status}`,t.body);if(!t.body)throw new l(`${e}${k}`,{code:"E_RESPONSE_NO_VALUE",status:t.status});return t.body}readResponseJSON(t,e){let o=this.readResponseBody(t,e),n;try{n=JSON.parse(o)}catch{throw new l(`${e}${S}`,{code:"E_INVALID_JSON",status:t.status})}return n}processListResponse(t,e){this.inspectCommonStatusCodes(t);let o=this.readResponseJSON(t,e);if(!Array.isArray(o.data))throw new l(`${e}${N}`,{code:"E_RESPONSE_UNKNOWN",status:t.status});return o}assertObjectKind(t,e,o){if(e!==o)throw new l(`${t}${N}`,{code:"E_RESPONSE_UNKNOWN",status:500})}};var St=class extends _{};var kt=class extends St{async get(t,e={}){let o=await this._get(t,e);if([301,302,308,307].includes(o.status)){let n=o.headers.get("location");if(!n)throw new Error('Expected redirection but no "location" header.');let r=new URL(n,t);return this.get(r.toString(),e)}return o}_get(t,e={}){return new Promise((o,n)=>{let{method:r="GET",headers:s={},token:i}=e,a={...s};i&&(a.authorization=`Bearer ${i}`);let p=(t.startsWith("https:")?de:ae).request(t,{method:r,headers:a,rejectUnauthorized:!1});p.on("response",m=>{let b={status:m.statusCode,headers:new nt(m.headers),body:""};m.on("data",y=>{b.body+=y}),m.on("end",()=>o(b))}),p.on("error",m=>n(m)),p.end()})}post(t,e={}){return new Promise((o,n)=>{let{method:r="POST",headers:s={},token:i}=e,a={...s};i&&(a.authorization=`Bearer ${i}`);let p=(t.startsWith("https:")?de:ae).request(t,{method:r,headers:a});p.on("response",m=>{let b={status:m.statusCode,headers:new nt(m.headers),body:""};m.on("data",y=>{b.body+=y}),m.on("end",()=>o(b))}),p.on("error",m=>n(m)),e.body&&p.write(e.body),p.end()})}patch(t,e={}){let o={...e,method:"PATCH"};return this.post(t,o)}put(t,e={}){let o={...e,method:"PUT"};return this.post(t,o)}delete(t,e={}){let o={...e,method:"DELETE"};return this.post(t,o)}};var wt=class extends _{oauthRedirect(t,e={}){let{redirect:o,token:n,type:r="redirect"}=e,s=new URL(this.sdk.baseUri);if(!["google","github","linkedin"].includes(t))throw new Error(`Invalid provider: ${t}`);let i=new URL(`/auth/${t}/redirect`,s);return o&&i.searchParams.set("r",o),n&&i.searchParams.set("token",n),r==="redirect"?(window.location.href=i.toString(),null):window.open(i.toString(),"_blank")}};var h=class d{static folders(t){return`/v1/orgs/${t}/folders`}static files(t){return`/v1/orgs/${t}/files`}static filesAccess(t,e){return`${d.file(t,e)}/access`}static filesBatch(t){return`${d.files(t)}/batch/read-meta`}static file(t,e){return`${d.files(t)}/${e}`}static fileMedia(t,e){return`${d.file(t,e)}/media`}static fileUsers(t,e){return`${d.file(t,e)}/users`}static fileRevisions(t,e){return`${d.file(t,e)}/revisions`}static fileBreadcrumbs(t,e){return`${d.file(t,e)}/breadcrumbs`}static history(){return"/history"}static historyBatchCreate(){return"/history/batch/create"}static historyBatchDelete(){return"/history/batch/delete"}static historyItem(t){return`/history/${t}`}static historyClear(t,...e){return`/history/clear/${t}/${e.join("/")}`}static shared(t){return`/v1/orgs/${t}/shared`}static trash(t){return`/v1/orgs/${t}/trash`}static trashItem(t,e){return`${d.trash(t)}/${e}`}static trashRestore(t,e){return`${d.trashItem(t,e)}/restore`}static trashEmpty(t){return`${d.trash(t)}/empty`}static trashBatchRestore(t){return`${d.trash(t)}/restore`}static trashBatchDelete(t){return`${d.trash(t)}/delete`}static projectExecutions(){return"/project/execution"}static projectExecution(t){return`/project/execution/${t}`}static projectExecutionBulkDelete(){return"/project/execution/delete"}static projectExecutionClear(t){return`/project/execution/clear/${t}`}static organizations(){return"/v1/orgs"}static organization(t){return`/v1/orgs/${t}`}static organizationUsers(t){return`${this.organization(t)}/users`}static organizationUserBatch(t){return`${this.organization(t)}/users/batch/read`}static organizationUser(t,e){return`${this.organization(t)}/users/${e}`}static organizationUserDeactivate(t,e){return`${this.organization(t)}/users/${e}/deactivate`}static organizationUserActivate(t,e){return`${this.organization(t)}/users/${e}/activate`}static invitations(t){return`${this.organization(t)}/invitations`}static invitation(t,e){return`${this.invitations(t)}/${e}`}static findInvitation(){return`${this.organizations()}/find-invitation`}static declineInvitation(t,e){return`${this.invitation(t,e)}/decline`}static resendInvitation(t,e){return`${this.invitation(t,e)}/resend`}static authGoogle(){return"/auth/google"}static authRenew(){return"/auth/renew"}static usersMe(){return"/v1/users/me"}static usersMeTokens(){return`${d.usersMe()}/tokens`}static usersMeToken(t){return`${d.usersMeTokens()}/${t}`}static dataCatalog(){return"/v1/datacatalog"}static dataCatalogStatus(t){return`${d.dataCatalog()}/status/${t}`}static dataCatalogEntry(t){return`${d.dataCatalog()}/${t}`}static dataCatalogEntryVersions(t){return`${d.dataCatalogEntry(t)}/versions`}static dataCatalogDependencies(){return`${d.dataCatalog()}/dependencies`}static dataCatalogUpdates(){return`${d.dataCatalog()}/updates`}static dataCatalogVersion(t,e){return`${d.dataCatalogEntry(t)}/${e}`}static dataCatalogDeprecate(t){return`${d.dataCatalogEntry(t)}/deprecate`}static dataCatalogUnpublish(t){return`${d.dataCatalogEntry(t)}/unpublish`}static dataCatalogVersionDeprecate(t,e){return`${d.dataCatalogVersion(t,e)}/deprecate`}static dataCatalogVersionUnpublish(t,e){return`${d.dataCatalogVersion(t,e)}/unpublish`}static groups(t){return`/v1/orgs/${t}/groups`}static group(t,e){return`/v1/orgs/${t}/groups/${e}`}static groupUsers(t,e){return`/v1/orgs/${t}/groups/${e}/users`}static aiModifyDomain(t,e){return`${this.organization(t)}/ai/domains/${e}/modify/stream`}static aiModifyApi(t,e){return`${this.organization(t)}/ai/apis/${e}/modify/stream`}static aiSessions(t,e){return`${this.organization(t)}/ai/sessions/${e}`}static aiSession(t,e,o){return`${d.aiSessions(t,e)}/${o}`}static aiMessages(t,e){return`${this.organization(t)}/ai/messages/${e}`}static aiMessage(t,e,o){return`${d.aiMessages(t,e)}/${o}`}static orgSlugGenerate(){return"/v1/orgs/slugs/generate"}static orgSlugValidate(){return"/v1/orgs/slugs/validate"}static deployments(t){return`/v1/orgs/${t}/deployments`}static deploymentsApis(t){return`${d.deployments(t)}/apis`}static deployment(t,e){return`${d.deployments(t)}/${e}`}static deploymentsApisByEnvLatest(t,e){return`${d.deploymentsApis(t)}/${e}/environments/latest`}static rollback(t,e){return`${d.deployment(t,e)}/rollback`}static job(t,e){return`/v1/orgs/${t}/jobs/${e}`}};import{customAlphabet as Ie}from"nanoid";var R=Ie("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_",21);var J="Core#Permission",V=["reader","commenter","writer","owner"],B=class d{kind=J;key="";type="user";granteeId="";role="reader";displayName;expirationTime;addingUser="";itemId="";depth=0;sourceRule="direct_user_grant";static fromUserRole(t,e,o,n){let r={key:R(),kind:J,itemId:e,granteeId:o,role:t,type:"user",addingUser:n,depth:0,sourceRule:"direct_user_grant"};return new d(r)}static fromGroupRole(t,e,o,n){let r={key:R(),kind:J,itemId:e,granteeId:o,role:t,type:"group",addingUser:n,depth:0,sourceRule:"direct_user_grant"};return new d(r)}static fromOrganizationRole(t,e,o,n){let r={key:R(),kind:J,itemId:e,granteeId:o,role:t,type:"organization",addingUser:n,depth:0,sourceRule:"direct_user_grant"};return new d(r)}static fromValues(t){return new d({...t,key:R(),kind:J})}constructor(t){let e;typeof t=="string"?e=JSON.parse(t):typeof t=="object"?e=t:e={kind:J,key:R(),granteeId:"",itemId:"",role:"reader",type:"user",addingUser:"",depth:0,sourceRule:"direct_user_grant"},this.new(e)}new(t){if(!d.isPermission(t))throw new Error("Not a permission.");let{key:e=R(),granteeId:o,role:n,type:r,displayName:s,expirationTime:i,addingUser:a,itemId:c,depth:u,sourceRule:p}=t;this.kind=J,this.key=e,this.granteeId=o,this.itemId=c,this.role=n,this.type=r,this.addingUser=a,this.depth=u||0,this.sourceRule=p||"direct_user_grant",s?this.displayName=s:this.displayName=void 0,typeof i=="number"?this.expirationTime=i:this.expirationTime=void 0}static isPermission(t){return!(!t||t.kind!==J)}static hasRole(t,e){if(!e)return!1;let o=V.indexOf(e),n=V.indexOf(t);return o>=n}static isHigherRole(t,e){let o=V.indexOf(t),n=V.indexOf(e);return o>n}hasRole(t){return d.hasRole(t,this.role)}static hasRoleIn(t,e){if(!e||!e.length)return!1;let o=[...e].sort((a,c)=>a.depth-c.depth),n=o[0].depth,r=o.filter(a=>a.depth===n),s,i=r.filter(a=>a.type==="user");if(i.length)s=i.sort((a,c)=>V.indexOf(c.role)-V.indexOf(a.role))[0];else{let a=r.filter(c=>c.type==="group");if(a.length)s=a.sort((c,u)=>V.indexOf(u.role)-V.indexOf(c.role))[0];else{let c=r.filter(u=>u.type==="organization");c.length&&(s=c.sort((u,p)=>V.indexOf(p.role)-V.indexOf(u.role))[0])}}return s?d.hasRole(t,s.role):!1}toJSON(){let t={kind:J,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&&(t.displayName=this.displayName),this.expirationTime&&(t.expirationTime=this.expirationTime),t}};import{__esDecorate as bt,__runInitializers as X}from"tslib";var W="Core#Thing",T="Core#Folder";var at="Core#User",Nt="Data#DomainFile";var K="Core#DataCatalog",F="Core#DataCatalogVersion";var tt="Core#Deployment";var ce="Core#ApiFile";var dt="Core#AiSession",Wt="Core#AiMessage",Xt="Core#Job";var ct=Symbol("reactive"),Gt=Symbol("proxy"),Oe=Symbol("raw");function lt(d={}){return(t,e)=>{let{kind:o}=e,{deep:n}=d;function r(s,i){if(typeof s!="object"||s===null)return s;let a=Reflect.get(this,Gt);if(a||(a=new Map,Reflect.set(this,Gt,a)),a.has(s))return a.get(s);let c=this,u=new Proxy(s,{get(p,m){if(m===Gt)return Reflect.get(p,m);if(m===Oe)return p;let b=Reflect.get(p,m);if(typeof b=="function"){if(p instanceof Map||p instanceof Set)return["set","add","delete","clear"].includes(m)?(...y)=>{if(m==="set"&&p.get(y[0])===y[1])return p;if(m==="delete"&&!p.has(y[0]))return!1;if(m==="clear"&&p.size===0)return;let E=b.apply(p,y);return i(),E}:m==="get"?(...y)=>{let E=b.apply(p,y);return r.bind(c)(E,i)}:m==="values"||m==="keys"||m==="entries"?(...y)=>{let E=b.apply(p,y);return{[Symbol.iterator](){return this},next(){let A=E.next();return A.done?A:m==="entries"?{done:!1,value:[A.value[0],r.bind(c)(A.value[1],i)]}:m==="keys"?A:{done:!1,value:r.bind(c)(A.value,i)}}}}:m==="forEach"?(y,E)=>{b.call(p,(A,P,L)=>{y.call(E,r.bind(c)(A,i),P,L)})}:b.bind(p);if(p instanceof WeakMap||p instanceof WeakSet||p instanceof Date||p instanceof RegExp)return b.bind(p)}return r.bind(c)(b,i)},set(p,m,b){return Reflect.get(p,m)!==b&&(Reflect.set(p,m,b),i()),!0},deleteProperty(p,m){return Reflect.deleteProperty(p,m),i(),!0}});return a.set(s,u),u}if(o==="accessor")return{init(s){let i=Reflect.get(this,ct);i||(i={},Reflect.set(this,ct,i));let a=()=>{this.domain?this.domain.notifyChange():this.notifyChange&&this.notifyChange()},c=s;return n&&(c=r.bind(this)(s,a)),c!==void 0&&(i[e.name]=c),c},set(s){let i=Reflect.get(this,ct);if(i||(i={},Reflect.set(this,ct,i)),i[e.name]===s)return;let a=()=>{this.domain?this.domain.notifyChange():this.notifyChange&&this.notifyChange()};n&&(s=r.bind(this)(s,a)),s===void 0?delete i[e.name]:i[e.name]=s,a()},get(){return(Reflect.get(this,ct)||{})[e.name]}};if(o==="setter"){let{name:s}=e;return function(i){let a=this[s];if(i===a)return;let c=()=>{this.domain?this.domain.notifyChange():this.notifyChange&&this.notifyChange()};t.call(this,i),c()}}throw new Error(`Unsupported decorator location: ${o}`)}}var ut=(()=>{let d=EventTarget,t,e=[],o=[],n,r=[],s=[],i,a=[],c=[],u,p=[],m=[];return class At extends d{static{let y=typeof Symbol=="function"&&Symbol.metadata?Object.create(d[Symbol.metadata]??null):void 0;t=[lt()],n=[lt()],i=[lt()],u=[lt()],bt(this,null,t,{kind:"accessor",name:"name",static:!1,private:!1,access:{has:E=>"name"in E,get:E=>E.name,set:(E,A)=>{E.name=A}},metadata:y},e,o),bt(this,null,n,{kind:"accessor",name:"displayName",static:!1,private:!1,access:{has:E=>"displayName"in E,get:E=>E.displayName,set:(E,A)=>{E.displayName=A}},metadata:y},r,s),bt(this,null,i,{kind:"accessor",name:"description",static:!1,private:!1,access:{has:E=>"description"in E,get:E=>E.description,set:(E,A)=>{E.description=A}},metadata:y},a,c),bt(this,null,u,{kind:"accessor",name:"version",static:!1,private:!1,access:{has:E=>"version"in E,get:E=>E.version,set:(E,A)=>{E.version=A}},metadata:y},p,m),y&&Object.defineProperty(this,Symbol.metadata,{enumerable:!0,configurable:!0,writable:!0,value:y})}kind=W;#t=X(this,e,void 0);get name(){return this.#t}set name(y){this.#t=y}#e=(X(this,o),X(this,r,void 0));get displayName(){return this.#e}set displayName(y){this.#e=y}#s=(X(this,s),X(this,a,void 0));get description(){return this.#s}set description(y){this.#s=y}#i=(X(this,c),X(this,p,void 0));get version(){return this.#i}set version(y){this.#i=y}static fromName(y){return new At({name:y,kind:W})}static fromJSON(y={},E={}){let A=new At,{name:P,displayName:L,description:mt,version:D}=y||{};return typeof P=="string"?A.name=P:typeof E.name=="string"&&(A.name=E.name),typeof L=="string"?A.displayName=L:typeof E.displayName=="string"&&(A.displayName=E.displayName),mt?A.description=mt:typeof E.description=="string"&&(A.description=E.description),D?A.version=D:typeof E.version=="string"&&(A.version=E.version),A}constructor(y){super(),X(this,m);let E;typeof y=="string"?E=JSON.parse(y):typeof y=="object"?E=y:E={kind:W},this.new(E)}new(y){if(!At.isThing(y))throw new Error("Not a thing.");let{description:E,name:A,version:P,displayName:L}=y;this.kind=W,this.name=A,this.displayName=L,this.description=E,this.version=P}notifyChange(){this.dispatchEvent(new Event("change"))}static validate(y,E={}){let{strict:A}=E;return y&&typeof y=="object"?!(A&&y.kind!==W):!1}static isThing(y){return!!(y&&y.kind===W)}toJSON(){let y={kind:W};return typeof this.name=="string"&&(y.name=this.name),typeof this.displayName=="string"&&(y.displayName=this.displayName),this.description&&(y.description=this.description),this.version&&(y.version=this.version),y}getLabel(y){return this.displayName||this.name||y||"Unnamed object"}}})();var qt=Symbol("parents"),It=Symbol("deleted"),Ot=Symbol("deletedInfo"),$t=Symbol("lastModified"),Ht=Symbol("capabilities"),Yt=Symbol("permissions"),Qt=Symbol("permissionIds"),Zt=Symbol("shortcutTarget"),pt=class{kind="";key="";info=ut.fromName("");iconColor;get isShortcut(){return!!this.shortcutTarget}[Zt];get shortcutTarget(){return this[Zt]}set shortcutTarget(t){this[Zt]=t}static createSchema(t={}){let{key:e=R(),kind:o,iconColor:n,shortcutTarget:r}=t,s={key:e,kind:o||"",info:ut.fromJSON(t.info,{name:"Unnamed file"}).toJSON()};return n&&(s.iconColor=n),r&&(s.isShortcut=!0,s.shortcutTarget=r),s}constructor(t){this.kind=t.kind,this.key=t.key,this.info=new ut(t.info),t.iconColor&&(this.iconColor=t.iconColor),t.shortcutTarget&&(this.shortcutTarget=t.shortcutTarget)}toJSON(){let t={key:this.key,kind:this.kind,info:this.info.toJSON()};return this.iconColor&&(t.iconColor=this.iconColor),this.shortcutTarget&&(t.isShortcut=!0,t.shortcutTarget=this.shortcutTarget),t}static createFileCapabilities(t,e){let o=B.hasRole("commenter",e),n=B.hasRole("owner",e),r=B.hasRole("reader",e),s=B.hasRole("writer",e),i=t.kind===T;return{canReadMedia:!i&&r,canListChildren:i&&r,canComment:!i&&o,canEditMedia:!i&&s,canEditMeta:s,canReadRevisions:s,canAddChildren:i&&s,canDelete:n,canTrash:n,canUntrash:n,canShare:s,canMove:s}}createFileCapabilities(t){return j.createFileCapabilities(this,t)}static updateByMeMeta(t,e){t.deletedInfo&&(t.deletedInfo.byMe=t.deletedInfo.user===e),t.lastModified&&(t.lastModified.byMe=t.lastModified.user===e)}static setLastModified(t,e){if(!t)throw new Error("The file is required.");if(!e)throw new Error("The user is required.");if(e.kind!==at)throw new Error('Invalid value for the user when setting "lastModified".');return t.lastModified={byMe:!1,time:Date.now(),user:e.key,name:e.name},t}static setDeleted(t,e){if(!t)throw new Error("The file is required.");if(!e)throw new Error("The user is required.");if(e.kind!==at)throw new Error('Invalid value for the user when setting "deletedInfo".');return t.deleted=!0,t.deletedInfo={byMe:!1,time:Date.now(),user:e.key,name:e.name},t}},j=class d extends pt{[qt]=[];get parents(){return this[qt]}[Qt]=[];get permissionIds(){return this[Qt]}[It];get deleted(){return this[It]||!1}[Ot];get deletedInfo(){return this[Ot]}[$t]={user:"",time:0,byMe:!1};get lastModified(){return this[$t]}labels;[Ht];get capabilities(){return this[Ht]}[Yt]=[];get permissions(){return this[Yt]}static createSchema(t={}){let e=pt.createSchema(t);return Array.isArray(t.parents)?e.parents=[...t.parents]:e.parents=[],Array.isArray(t.permissionIds)?e.permissionIds=[...t.permissionIds]:e.permissionIds=[],Array.isArray(t.permissions)?e.permissions=t.permissions.map(o=>({...o})):e.permissions=[],t.capabilities&&(e.capabilities={...t.capabilities}),t.lastModified?e.lastModified={...t.lastModified}:e.lastModified={user:"",time:0,byMe:!1},typeof t.deleted=="boolean"&&(e.deleted=t.deleted,e.deletedInfo=t.deletedInfo?{...t.deletedInfo}:void 0),Array.isArray(t.labels)&&(e.labels=[...t.labels]),typeof t.shortcutTarget=="string"&&(e.shortcutTarget=t.shortcutTarget),e}constructor(t){let e=d.createSchema(t);super(e),this[qt]=[...e.parents],this[Qt]=[...e.permissionIds],this[Yt]=e.permissions.map(o=>({...o})),this[Ht]=e.capabilities?{...e.capabilities}:void 0,this[$t]=Object.freeze({...e.lastModified}),typeof e.deleted=="boolean"&&(this[It]=e.deleted,this[Ot]=e.deletedInfo?Object.freeze({...e.deletedInfo}):void 0),Array.isArray(e.labels)&&(this.labels=[...e.labels])}toJSON(){let t={...super.toJSON(),parents:[...this.parents],permissionIds:[...this.permissionIds],lastModified:{...this.lastModified},permissions:[...this.permissions]};return this.deleted&&(t.deleted=this.deleted,t.deletedInfo={...this.deletedInfo}),Array.isArray(this.labels)&&(t.labels=[...this.labels]),t}static fromName(t,e){return new d({kind:e,info:{name:t}})}shortcutTo(t){return this.shortcutTarget=t,this}setLastModified(t){if(!t)throw new Error("The user is required.");if(t.kind!==at)throw new Error('Invalid value for the user when setting "lastModified".');this[$t]={byMe:!1,time:Date.now(),user:t.key,name:t.name}}addLabel(t){if(typeof t!="string")throw new Error("The label must be a string.");if(!t.trim())throw new Error("The label is required.");Array.isArray(this.labels)||(this.labels=[]),!this.labels.includes(t)&&this.labels.push(t)}setDeleted(t){if(!t)throw new Error("The user is required.");if(t.kind!==at)throw new Error('Invalid value for the user when setting "deletedInfo".');this[It]=!0,this[Ot]={byMe:!1,time:Date.now(),user:t.key,name:t.name}}isFile(){return this.kind!==T}isFolder(){return this.kind===T}};var ht=class extends j{kind=T;static fromName(t){return super.fromName(t,T)}constructor(t){let e=j.createSchema(t);e.kind=T,super(e)}static isFolder(t){return!(!t||t.kind!==T)}toJSON(){return{...super.toJSON(),kind:T}}};var _t=class extends _{async list(t,e={},o={}){let{token:n}=o,r={...e},s=this.sdk.getUrl(h.files(t));this.sdk.appendListOptions(s,r);let i=await this.sdk.http.get(s.toString(),{token:n});this.inspectCommonStatusCodes(i);let a="Unable to list files. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body)}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!Array.isArray(c.data))throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c}async create(t,e,o,n={},r={}){let s=await this.createMeta(t,o,n,r);return await this.createMedia(e,o,s.key,n,r),s}async createMeta(t,e,o={},n={}){let{token:r}=n,s=this.sdk.getUrl(h.files(e));o.parent&&s.searchParams.set("parent",o.parent);let i=JSON.stringify(t),a=await this.sdk.http.post(s.toString(),{token:r,body:i,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let c="Unable to create a file. ";if(a.status!==201)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(!u.key)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u}async createMedia(t,e,o,n={},r={}){let{token:s}=r,i=h.fileMedia(e,o),a=this.sdk.getUrl(i),c=n.mime||"application/json",u;c.includes("json")?u=JSON.stringify(t):u=String(t);let p=await this.sdk.http.put(a.toString(),{token:s,body:u,headers:{"content-type":c}});this.inspectCommonStatusCodes(p);let m="Unable to create a file. ";if(p.status!==200)throw this.logInvalidResponse(p),this.createApiError(`${m}${f}${p.status}`,p.body)}async createFolder(t,e,o={},n={}){let r=ht.fromName(t),{token:s}=n,i=this.sdk.getUrl(h.files(e));o.parent&&i.searchParams.set("parent",o.parent);let a=JSON.stringify(r),c=await this.sdk.http.post(i.toString(),{token:s,body:a,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(c);let u="Unable to create a file. ";if(c.status!==201)throw this.logInvalidResponse(c),this.createApiError(`${u}${f}${c.status}`,c.body);if(!c.body)throw new l(`${u}${k}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let p;try{p=JSON.parse(c.body).data}catch{throw new l(`${u}${S}`,{code:"E_INVALID_JSON",status:c.status})}if(!p.key)throw new l(`${u}${N}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return p}async read(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.file(t,e)),s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to read a file. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!a.kind)throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async readMedia(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.fileMedia(t,e)),s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to read a file media. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}let c=s.headers.get("x-version");if(!c)throw new l(`${i}The file media version was not sent by the server.`,{status:s.status,code:"E_RESPONSE_NO_VERSION"});let u=Number(c);if(isNaN(u))throw new l(`${i}The file media version is not a number.`,{status:s.status,code:"E_RESPONSE_INVALID_VERSION"});return{media:a,version:u}}async readBulk(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.filesBatch(t)),s=JSON.stringify({ids:e}),i=await this.sdk.http.post(r.toString(),{token:n,body:s});this.inspectCommonStatusCodes(i);let a="Unable to read files in bulk. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body)}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!Array.isArray(c.data))throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c}async patch(t,e,o,n={}){let{token:r}=n,s=h.file(t,e),i=this.sdk.getUrl(s),a=JSON.stringify(o),c=await this.sdk.http.patch(i.toString(),{token:r,body:a});this.inspectCommonStatusCodes(c);let u="Unable to patch a file. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${u}${f}${c.status}`,c.body);if(!c.body)throw new l(`${u}${k}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let p;try{p=JSON.parse(c.body).data}catch{throw new l(`${u}${S}`,{code:"E_INVALID_JSON",status:c.status})}if(!p.kind)throw new l(`${u}${N}`,{code:"E_RESPONSE_UNKNOWN",status:c.status});return p}async patchMedia(t,e,o,n={}){let{token:r}=n,s=h.fileMedia(t,e),i=this.sdk.getUrl(s),a=JSON.stringify(o),c=await this.sdk.http.patch(i.toString(),{token:r,body:a});this.inspectCommonStatusCodes(c);let u="Unable to patch a file contents. ";if(c.status!==200)throw this.logInvalidResponse(c),this.createApiError(`${u}${f}${c.status}`,c.body);if(!c.body)throw new l(`${u}${k}`,{code:"E_RESPONSE_NO_VALUE",status:c.status});let p;try{p=JSON.parse(c.body).data}catch{throw new l(`${u}${S}`,{code:"E_INVALID_JSON",status:c.status})}return p}async delete(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.file(t,e)),s=await this.sdk.http.delete(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to trash a file. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body)}async deleteBulk(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.files(t)),s=await this.sdk.http.delete(r.toString(),{token:n,body:JSON.stringify({ids:e})});this.inspectCommonStatusCodes(s);let i="Unable to trash files. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body)}async patchUsers(t,e,o,n={}){let{token:r}=n,s=this.sdk.getUrl(h.filesAccess(t,e)),i=JSON.stringify(o),a=await this.sdk.http.patch(s.toString(),{token:r,body:i});this.inspectCommonStatusCodes(a);let c="Unable to patch the file. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(!u.key)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u}async addUser(t,e,o,n,r,s){let i={op:"add",type:"user",value:n,id:o};typeof r=="number"&&(i.expirationTime=r);let a={patch:[i],id:R()};return this.patchUsers(t,e,a,s)}async removeUser(t,e,o,n){let s={patch:[{op:"remove",type:"user",id:o}],id:R()};return this.patchUsers(t,e,s,n)}async listUsers(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.fileUsers(t,e)),s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to list users in the file. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async breadcrumbs(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.fileBreadcrumbs(t,e)),s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to read breadcrumbs. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}};var vt=class extends _{async me(t={}){let{token:e}=t,o=this.sdk.getUrl(h.usersMe()),n=await this.sdk.http.get(o.toString(),{token:e});this.inspectCommonStatusCodes(n);let r="Unable to read a user. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${r}${f}${n.status}`,n.body);if(!n.body)throw new l(`${r}${k}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let s;try{s=JSON.parse(n.body).data}catch{throw new l(`${r}${S}`,{code:"E_INVALID_JSON",status:n.status})}if(!s.key)throw new l(`${r}${N}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return s}async listTokens(t={}){let{token:e}=t,o=this.sdk.getUrl(h.usersMeTokens()),n=await this.sdk.http.get(o.toString(),{token:e});this.inspectCommonStatusCodes(n);let r="Unable to list tokens. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${r}${f}${n.status}`,n.body);if(!n.body)throw new l(`${r}${k}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let s;try{s=JSON.parse(n.body).data}catch{throw new l(`${r}${S}`,{code:"E_INVALID_JSON",status:n.status})}return s}async createToken(t={},e={}){let{token:o}=e,n=this.sdk.getUrl(h.usersMeTokens()),r=JSON.stringify(t),s=await this.sdk.http.post(n.toString(),{token:o,body:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(s);let i="Unable to create a token. ";if(s.status!==200&&s.status!==201)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}return a}async deleteToken(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.usersMeToken(t)),r=await this.sdk.http.delete(n.toString(),{token:o});this.inspectCommonStatusCodes(r);let s="Unable to delete a token. ";if(r.status!==204)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body)}};var Rt=class extends _{async list(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.shared(t));this.sdk.appendListOptions(r,e);let s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to list shared files. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}};var Ct=class extends _{async list(t,e,o,n={}){let{token:r}=n,s=this.sdk.getUrl(h.fileRevisions(t,e));this.sdk.appendListOptions(s,o);let i=await this.sdk.http.get(s.toString(),{token:r});this.inspectCommonStatusCodes(i);let a="Unable to list revisions for a file. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body)}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!Array.isArray(c.data))throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c}};var Ut=class extends _{async list(t,e={},o={}){let{token:n}=o,r=this.sdk.getUrl(h.trash(t));this.sdk.appendListOptions(r,e);let s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to list trash. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}async delete(t,e,o={}){let n=h.trashBatchDelete(t),r=this.sdk.getUrl(n),{token:s}=o,i=await this.sdk.http.delete(r.toString(),{token:s,body:JSON.stringify({ids:e})});this.inspectCommonStatusCodes(i);let a="Unable to delete trash. ";if(i.status!==204)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body)}async restore(t,e,o={}){let n=this.sdk.getUrl(h.trashBatchRestore(t)),{token:r}=o,s=await this.sdk.http.post(n.toString(),{token:r,body:JSON.stringify({ids:e})});this.inspectCommonStatusCodes(s);let i="Unable to restore from trash. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body)}async empty(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.trashEmpty(t)),r=await this.sdk.http.delete(n.toString(),{token:o});this.inspectCommonStatusCodes(r);let s="Unable to empty trash. ";if(r.status!==204)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body)}};var Pt=class extends _{async list(t={}){let{token:e}=t,o=this.sdk.getUrl(h.organizations()),n=await this.sdk.http.get(o.toString(),{token:e});this.inspectCommonStatusCodes(n);let r="Unable to list your organizations. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${r}${f}${n.status}`,n.body);if(!n.body)throw new l(`${r}${k}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let s;try{s=JSON.parse(n.body)}catch{throw new l(`${r}${S}`,{code:"E_INVALID_JSON",status:n.status})}if(!Array.isArray(s.data))throw new l(`${r}${N}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return s}async create(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.organizations()),s={name:t,slug:e},i=await this.sdk.http.post(r.toString(),{body:JSON.stringify(s),token:n,headers:{"Content-Type":"application/json"}});this.inspectCommonStatusCodes(i);let a="Unable to create an organization. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body).data}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!c.kind)throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c}invitations={list:async(t,e={})=>{let{token:o}=e,n=this.sdk.getUrl(h.invitations(t)),r=await this.sdk.http.get(n.toString(),{token:o});this.inspectCommonStatusCodes(r);let s="Unable to list organization invitations. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);if(!r.body)throw new l(`${s}${k}`,{code:"E_RESPONSE_NO_VALUE",status:r.status});let i;try{i=JSON.parse(r.body)}catch{throw new l(`${s}${S}`,{code:"E_INVALID_JSON",status:r.status})}if(!Array.isArray(i.data))throw new l(`${s}${N}`,{code:"E_RESPONSE_UNKNOWN",status:r.status});return i},create:async(t,e,o,n,r={})=>{let s=this.sdk.getUrl(h.invitations(t)),i={email:e,name:n,grant_type:o},a=await this.sdk.http.post(s.toString(),{body:JSON.stringify(i),token:r.token,headers:{"Content-Type":"application/json"}});this.inspectCommonStatusCodes(a);let c="Unable to create an invitation. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(!u.kind)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u},findByToken:async(t,e={})=>{let o=this.sdk.getUrl(h.findInvitation());o.searchParams.append("token",t);let n=await this.sdk.http.get(o.toString(),e);this.inspectCommonStatusCodes(n);let r="Unable to find invitation by token. ";if(n.status!==200)throw this.logInvalidResponse(n),this.createApiError(`${r}${f}${n.status}`,n.body);if(!n.body)throw new l(`${r}${k}`,{code:"E_RESPONSE_NO_VALUE",status:n.status});let s;try{s=JSON.parse(n.body).data}catch{throw new l(`${r}${S}`,{code:"E_INVALID_JSON",status:n.status})}if(!s.kind)throw new l(`${r}${N}`,{code:"E_RESPONSE_UNKNOWN",status:n.status});return s},decline:async(t,e,o={})=>{let n=this.sdk.getUrl(h.declineInvitation(t,e)),r=await this.sdk.http.post(n.toString(),o);this.inspectCommonStatusCodes(r);let s="Unable to decline invitation. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);if(!r.body)throw new l(`${s}${k}`,{code:"E_RESPONSE_NO_VALUE",status:r.status});let i;try{i=JSON.parse(r.body).data}catch{throw new l(`${s}${S}`,{code:"E_INVALID_JSON",status:r.status})}if(!i.kind)throw new l(`${s}${N}`,{code:"E_RESPONSE_UNKNOWN",status:r.status});return i},delete:async(t,e,o={})=>{let n=this.sdk.getUrl(h.invitation(t,e)),r=await this.sdk.http.delete(n.toString(),o);this.inspectCommonStatusCodes(r);let s="Unable to delete invitation. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);if(!r.body)throw new l(`${s}${k}`,{code:"E_RESPONSE_NO_VALUE",status:r.status});let i;try{i=JSON.parse(r.body).data}catch{throw new l(`${s}${S}`,{code:"E_INVALID_JSON",status:r.status})}if(!i.kind)throw new l(`${s}${N}`,{code:"E_RESPONSE_UNKNOWN",status:r.status});return i},patch:async(t,e,o,n={})=>{let r=this.sdk.getUrl(h.invitation(t,e)),s=await this.sdk.http.patch(r.toString(),{body:JSON.stringify(o),token:n.token,headers:{"Content-Type":"application/json"}});this.inspectCommonStatusCodes(s);let i="Unable to update invitation. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!a.kind)throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a},resend:async(t,e,o={})=>{let n=this.sdk.getUrl(h.resendInvitation(t,e)),r=await this.sdk.http.put(n.toString(),o);this.inspectCommonStatusCodes(r);let s="Unable to resend invitation. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);if(!r.body)throw new l(`${s}${k}`,{code:"E_RESPONSE_NO_VALUE",status:r.status});let i;try{i=JSON.parse(r.body).data}catch{throw new l(`${s}${S}`,{code:"E_INVALID_JSON",status:r.status})}if(!i.kind)throw new l(`${s}${N}`,{code:"E_RESPONSE_UNKNOWN",status:r.status});return i}};users={list:async(t,e,o={})=>{let{token:n}=o,r=this.sdk.getUrl(h.organizationUsers(t));this.sdk.appendListOptions(r,e);let s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to list projects. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!Array.isArray(a.data))throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a},read:async(t,e,o={})=>{let{token:n}=o,r=this.sdk.getUrl(h.organizationUser(t,e)),s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to read the user info. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}return a},readBatch:async(t,e,o={})=>{let{token:n}=o,r=this.sdk.getUrl(h.organizationUserBatch(t)),s={ids:e},i=await this.sdk.http.post(r.toString(),{body:JSON.stringify(s),token:n});this.inspectCommonStatusCodes(i);let a="Unable to read the user batch info. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body)}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!Array.isArray(c.data))throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c},activate:async(t,e,o={})=>{let{token:n}=o,r=this.sdk.getUrl(h.organizationUserActivate(t,e)),s=await this.sdk.http.post(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to activate the user. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}return a},deactivate:async(t,e,o={})=>{let{token:n}=o,r=this.sdk.getUrl(h.organizationUserDeactivate(t,e)),s=await this.sdk.http.post(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to deactivate the user. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}return a},delete:async(t,e,o={})=>{let{token:n}=o,r=this.sdk.getUrl(h.organizationUser(t,e)),s=await this.sdk.http.delete(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to delete the user. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body)}};slugs={generate:async(t,e={})=>{let{token:o}=e,n=this.sdk.getUrl(h.orgSlugGenerate()).toString(),r={name:t},s=await this.sdk.http.post(n,{body:JSON.stringify(r),token:o});this.inspectCommonStatusCodes(s);let i="Unable to generate the slug. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(!a.slug)throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a.slug},validate:async(t,e={})=>{let{token:o}=e,n=this.sdk.getUrl(h.orgSlugValidate()).toString(),r={slug:t},s=await this.sdk.http.post(n,{body:JSON.stringify(r),token:o});this.inspectCommonStatusCodes(s);let i="Unable to validate the slug. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);if(!s.body)throw new l(`${i}${k}`,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body).data}catch{throw new l(`${i}${S}`,{code:"E_INVALID_JSON",status:s.status})}if(typeof a.valid!="boolean")throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a}}};var xt=class extends _{async list(t={},e={}){let{token:o}=e,n={...t},r=this.sdk.getUrl(h.dataCatalog());this.sdk.appendListOptions(r,n),n.scope&&r.searchParams.set("scope",n.scope);let s=await this.sdk.http.get(r.toString(),{token:o});return this.processListResponse(s,"Unable to list data domains. ")}async listVersions(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.dataCatalogEntryVersions(t)),r=await this.sdk.http.get(n.toString(),{token:o});return this.processListResponse(r,"Unable to list data domain versions. ")}async publish(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.dataCatalog()),r=JSON.stringify(t),s=await this.sdk.http.post(n.toString(),{token:o,body:r,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(s);let i="Unable to publish data domain. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,K,a.kind),a}async read(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.dataCatalogEntry(t)),r=await this.sdk.http.get(n.toString(),{token:o});this.inspectCommonStatusCodes(r);let s="Unable to read data domain. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);let i=this.readResponseJSON(r,s).data;return this.assertObjectKind(s,K,i.kind),i}async deprecate(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.dataCatalogDeprecate(t)),s=JSON.stringify({reason:e}),i=await this.sdk.http.put(r.toString(),{token:n,body:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(i);let a="Unable to deprecate data domain. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);let c=this.readResponseJSON(i,a).data;return this.assertObjectKind(a,K,c.kind),c}async unpublish(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.dataCatalogUnpublish(t)),r=await this.sdk.http.put(n.toString(),{token:o});this.inspectCommonStatusCodes(r);let s="Unable to unpublish data domain. ";if(r.status!==200)throw this.logInvalidResponse(r),this.createApiError(`${s}${f}${r.status}`,r.body);let i=this.readResponseJSON(r,s).data;return this.assertObjectKind(s,K,i.kind),i}async publishVersion(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.dataCatalogEntryVersions(t)),s=JSON.stringify(e),i=await this.sdk.http.post(r.toString(),{token:n,body:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(i);let a="Unable to publish data domain version. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);let c=this.readResponseJSON(i,a).data;return this.assertObjectKind(a,F,c.kind),c}async readVersion(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.dataCatalogVersion(t,e)),s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to read data domain version. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,F,a.kind),a}async listDependencies(t,e={}){let{token:o}=e,n=this.sdk.getUrl(h.dataCatalogDependencies()),r=JSON.stringify({items:t}),s=await this.sdk.http.post(n.toString(),{token:o,body:r,headers:{"content-type":"application/json"}});return this.processListResponse(s,"Unable to list data domain dependencies. ")}async checkUpdates(t,e={}){let{token:o}=e,n=t.map(a=>({fid:a.key,version:a.version})),r=this.sdk.getUrl(h.dataCatalogUpdates()),s=JSON.stringify({dependencies:n}),i=await this.sdk.http.post(r.toString(),{token:o,body:s,headers:{"content-type":"application/json"}});return this.processListResponse(i,"Unable to check for data domain updates. ")}async deprecateVersion(t,e,o,n={}){let{token:r}=n,s=this.sdk.getUrl(h.dataCatalogVersionDeprecate(t,e)),i=JSON.stringify({reason:o}),a=await this.sdk.http.put(s.toString(),{token:r,body:i,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let c="Unable to deprecate data domain version. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);let u=this.readResponseJSON(a,c).data;return this.assertObjectKind(c,F,u.kind),u}async unpublishVersion(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.dataCatalogVersionUnpublish(t,e)),s=await this.sdk.http.put(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to unpublish data domain version. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,F,a.kind),a}async checkPublicationStatus(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.dataCatalogStatus(t));e&&r.searchParams.set("oid",e);let s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to check data domain publication status. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,K,a.kind),a}};var Dt=class extends _{async create(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.groups(t)),s=JSON.stringify(e),i=await this.sdk.http.post(r.toString(),{token:n,body:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(i);let a="Unable to create a group. ";if(i.status!==201)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body).data}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!c.key)throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c}async list(t,e={},o={}){let{token:n}=o,r=this.sdk.getUrl(h.groups(t));this.sdk.appendListOptions(r,e);let s=await this.sdk.http.get(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to create a group. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(i+f+s.status,s.body);if(!s.body)throw new l(i+k,{code:"E_RESPONSE_NO_VALUE",status:s.status});let a;try{a=JSON.parse(s.body)}catch{throw new l(i+S,{code:"E_INVALID_JSON",status:s.status})}return a}async update(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.group(t,e.key)),s=JSON.stringify(e),i=await this.sdk.http.put(r.toString(),{token:n,body:s,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(i);let a="Unable to update a group. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body).data}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!c.key)throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c}async delete(t,e,o={}){let{token:n}=o,r=this.sdk.getUrl(h.group(t,e)),s=await this.sdk.http.delete(r.toString(),{token:n});this.inspectCommonStatusCodes(s);let i="Unable to delete a group. ";if(s.status!==204)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body)}async addUsers(t,e,o,n={}){let{token:r}=n,s=this.sdk.getUrl(h.groupUsers(t,e)),i=JSON.stringify({ids:o}),a=await this.sdk.http.post(s.toString(),{token:r,body:i,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let c="Unable to add users to a group. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(!u.key)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u}async removeUsers(t,e,o,n={}){let{token:r}=n,s=this.sdk.getUrl(h.groupUsers(t,e)),i=JSON.stringify({ids:o}),a=await this.sdk.http.delete(s.toString(),{token:r,body:i,headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(a);let c="Unable to remove users from a group. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(!u.key)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u}};var Tt=class extends _{async*modifyDomain(t,e,o,n,r={}){let{token:s=this.sdk.token,signal:i}=r,a=this.sdk.getUrl(h.aiModifyDomain(t,e)),c=JSON.stringify({goal:o,sid:n}),u={method:"POST",headers:{"content-type":"application/json",accept:"text/event-stream",authorization:`Bearer ${s}`},redirect:"follow",credentials:"include",body:c,signal:i},p=await fetch(a,u);if(!p.ok){let E=await p.text();throw new l(`Failed to modify domain: ${p.status} ${E}`)}let m=p.body?.getReader();if(!m)throw new l("Failed to get reader from response");let b=new TextDecoder,y="";for(;;){let{done:E,value:A}=await m.read();if(E)return;y+=b.decode(A,{stream:!0});let P;for(;(P=y.indexOf(`
|
|
17
|
+
|
|
18
|
+
`))>=0;){let L=y.slice(0,P);if(y=y.slice(P+2),!L.trim())continue;let mt=L.split(`
|
|
19
|
+
`),D="message",gt="";for(let yt of mt)yt.startsWith("event:")?D=yt.substring(6).trim():yt.startsWith("data:")&&(gt+=yt.substring(5).trim());if(!gt)continue;let q;try{q=JSON.parse(gt)}catch{console.error("Failed to parse SSE JSON data:",gt);continue}switch(D){case"user-message":yield{event:D,data:q};break;case"agent-message":yield{event:D,data:q};break;case"thought-chunk":case"text-chunk":yield{event:D,data:q};break;case"done":yield{event:D,data:q};return;case"error":yield{event:D,data:l.fromRawException(q,"Failed to generate results")};break;case"session-updated":yield{event:D,data:q};break;default:console.warn(`Unknown SSE event: ${D}`)}}}}sessions={list:async(t,e,o={},n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiSessions(t,e));this.sdk.appendListOptions(s,o);let i=await this.sdk.http.get(s.toString(),{token:r});this.inspectCommonStatusCodes(i);let a="Unable to list sessions. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body)}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!Array.isArray(c.data))throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c},read:async(t,e,o,n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiSession(t,e,o)),i=await this.sdk.http.get(s.toString(),{token:r});this.inspectCommonStatusCodes(i);let a="Unable to read session. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body).data}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(c.kind!==dt)throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c},create:async(t,e,o,n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiSessions(t,e)),i=JSON.stringify(o),a=await this.sdk.http.post(s.toString(),{token:r,body:i});this.inspectCommonStatusCodes(a);let c="Unable to create session. ";if(a.status!==201)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(u.kind!==dt)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u},delete:async(t,e,o,n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiSession(t,e,o)),i=await this.sdk.http.delete(s.toString(),{token:r});this.inspectCommonStatusCodes(i);let a="Unable to delete session. ";if(i.status!==204)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body)},update:async(t,e,o,n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiSession(t,e,o.key)),i=JSON.stringify(o),a=await this.sdk.http.put(s.toString(),{token:r,body:i});this.inspectCommonStatusCodes(a);let c="Unable to update session. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(u.kind!==dt)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u}};messages={list:async(t,e,o={},n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiMessages(t,e));this.sdk.appendListOptions(s,o);let i=await this.sdk.http.get(s.toString(),{token:r});this.inspectCommonStatusCodes(i);let a="Unable to list messages. ";if(i.status!==200)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body);if(!i.body)throw new l(`${a}${k}`,{code:"E_RESPONSE_NO_VALUE",status:i.status});let c;try{c=JSON.parse(i.body)}catch{throw new l(`${a}${S}`,{code:"E_INVALID_JSON",status:i.status})}if(!Array.isArray(c.data))throw new l(`${a}${N}`,{code:"E_RESPONSE_UNKNOWN",status:i.status});return c},delete:async(t,e,o,n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiMessage(t,e,o)),i=await this.sdk.http.delete(s.toString(),{token:r});this.inspectCommonStatusCodes(i);let a="Unable to delete message. ";if(i.status!==204)throw this.logInvalidResponse(i),this.createApiError(`${a}${f}${i.status}`,i.body)},update:async(t,e,o,n={})=>{let{token:r=this.sdk.token}=n,s=this.sdk.getUrl(h.aiMessage(t,e,o.key)),i=JSON.stringify(o),a=await this.sdk.http.put(s.toString(),{token:r,body:i});this.inspectCommonStatusCodes(a);let c="Unable to update message. ";if(a.status!==200)throw this.logInvalidResponse(a),this.createApiError(`${c}${f}${a.status}`,a.body);if(!a.body)throw new l(`${c}${k}`,{code:"E_RESPONSE_NO_VALUE",status:a.status});let u;try{u=JSON.parse(a.body).data}catch{throw new l(`${c}${S}`,{code:"E_INVALID_JSON",status:a.status})}if(u.kind!==Wt)throw new l(`${c}${N}`,{code:"E_RESPONSE_UNKNOWN",status:a.status});return u}}};var te;(function(d){d.Pending="pending",d.Active="active",d.Inactive="inactive",d.Failed="failed"})(te||(te={}));var et;(function(d){d.PROD="prod",d.STAGING="staging",d.DEV="dev"})(et||(et={}));var Lt=class extends _{async list(t,e={},o={}){let{token:n=this.sdk.token}=o,r=this.sdk.getUrl(h.deployments(t));this.sdk.appendListOptions(r,e);let s=await this.sdk.http.get(r.toString(),{token:n});return this.processListResponse(s,"Unable to list deployments. ")}async create(t,e,o={}){if(e.env===et.PROD&&!e.version)throw new l(`Version must not be empty for production environment: ${e.env}`,{code:"INVALID_DEPLOYMENT_VERSION",help:"Please provide a version for production environment",status:400});if(e.env!==et.PROD&&e.version)throw new l(`Version must not be present for non-production environment: ${e.env}`,{code:"INVALID_DEPLOYMENT_VERSION",help:"Please remove the version for non-production environment",status:400});let n=this.sdk.getUrl(h.deployments(t)),{token:r=this.sdk.token}=o,s=await this.sdk.http.post(n.toString(),{token:r,body:JSON.stringify(e),headers:{"content-type":"application/json"}});this.inspectCommonStatusCodes(s);let i="Unable to create a deployment. ";if(s.status!==202)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,tt,a.kind),a}async read(t,e,o={}){let n=this.sdk.getUrl(h.deployment(t,e)),{token:r=this.sdk.token}=o,s=await this.sdk.http.get(n.toString(),{token:r});this.inspectCommonStatusCodes(s);let i="Unable to read a deployment. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,tt,a.kind),a}async deactivate(t,e,o={}){let n=this.sdk.getUrl(h.deployment(t,e)),{token:r=this.sdk.token}=o,s=await this.sdk.http.delete(n.toString(),{token:r});this.inspectCommonStatusCodes(s);let i="Unable to deactivate a deployment. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,tt,a.kind),a}async rollback(t,e,o={}){let n=this.sdk.getUrl(h.rollback(t,e)),{token:r=this.sdk.token}=o,s=await this.sdk.http.post(n.toString(),{token:r});this.inspectCommonStatusCodes(s);let i="Unable to rollback a deployment. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,tt,a.kind),a}apis={getLatestPerEnvironment:async(t,e,o={})=>{let n=this.sdk.getUrl(h.deploymentsApisByEnvLatest(t,e)),{token:r=this.sdk.token}=o,s=await this.sdk.http.get(n.toString(),{token:r});this.inspectCommonStatusCodes(s);let i="Unable to list latest deployments for an API. ",a=this.readResponseJSON(s,i);if(!a.data)throw new l(`${i}${N}`,{code:"E_RESPONSE_UNKNOWN",status:s.status});return a},list:async(t,e={})=>{let o=this.sdk.getUrl(h.deploymentsApis(t)),{token:n=this.sdk.token}=e,r=await this.sdk.http.get(o.toString(),{token:n});return this.processListResponse(r,"Unable to list APIs. ")}}};var ee;(function(d){d.Pending="pending",d.Running="running",d.Completed="completed",d.Failed="failed"})(ee||(ee={}));var Vt=class extends _{async checkStatus(t,e,o={}){let n=this.sdk.getUrl(h.job(t,e)),{token:r=this.sdk.token}=o,s=await this.sdk.http.get(n.toString(),{token:r});this.inspectCommonStatusCodes(s);let i="Unable to check job status. ";if(s.status!==200)throw this.logInvalidResponse(s),this.createApiError(`${i}${f}${s.status}`,s.body);let a=this.readResponseJSON(s,i).data;return this.assertObjectKind(i,Xt,a.kind),a}};var se=Symbol("baseUri"),Jt=class{basePath;#t;get token(){return this.#t}set token(t){this.#t=t}auth=new wt(this);files=new _t(this);users=new vt(this);shared=new Rt(this);revisions=new Ct(this);trash=new Ut(this);organizations=new Pt(this);dataCatalog=new xt(this);groups=new Dt(this);ai=new Tt(this);deployments=new Lt(this);jobs=new Vt(this);silent=!1;[se]="";get baseUri(){return this[se]}set baseUri(t){if(!t)throw new Error("Invalid value for the baseUri");let e;try{e=new URL(t)}catch{throw new Error("Invalid baseUri: Not an URL")}this[se]=e.origin;let{pathname:o}=e;o&&o!=="/"?this.basePath=o:this.basePath=void 0}constructor(t,e){this.basePath=e,this.baseUri=t}getUrl(t="/"){if(t.startsWith("http:")||t.startsWith("https:"))return new URL(t);let{baseUri:e,basePath:o=""}=this,n=t;return o&&n.startsWith(o)&&(n=n.substring(o.length)),new URL(`${o}${n}`,e)}appendListOptions(t,e={}){let{searchParams:o}=t;if(e.cursor&&o.set("cursor",e.cursor),typeof e.limit=="number"&&o.set("limit",String(e.limit)),e.parent&&o.set("parent",e.parent),e.since&&o.set("since",String(e.since)),e.sort&&o.set("sort",String(e.sort)),e.order&&o.set("order",String(e.order)),e.oid&&o.set("oid",String(e.oid)),e.uid&&o.set("uid",String(e.uid)),e.filter){let n=new TextEncoder().encode(JSON.stringify(e.filter)),r=Array.from(n,s=>String.fromCodePoint(s)).join("");o.set("filter",btoa(r))}}};var Mt=class extends Jt{http=new kt(this)};function C(d={}){let t=w.resolved,e=d.apiUrl||t.apiUrl,o=new Mt(e);return t.token&&(o.token=t.token),o}function U(d){if(d&&typeof d=="object"){let e=d,o=e.status,n=e.code,r=e.message||"An unknown error occurred.",s=e.help;return o===401?(r="Unauthorized. Please login using `auth login`.",{message:r,status:o,code:"CLI_ERR_UNAUTHORIZED",help:s}):{message:r,status:o,code:n||"CLI_ERR_API_FAILURE",help:s}}return{message:d?.message||"An unknown error occurred.",code:"CLI_ERR_UNKNOWN"}}import{input as $e,confirm as _e,select as ve}from"@inquirer/prompts";async function z(d,t){return(await $e({message:d,default:t})).trim()}async function le(d,t=!0){return _e({message:d,default:t})}async function st(d,t){return ve({message:d,choices:t})}async function ie(d,t){let e;try{e=(await d.organizations.list({token:d.token})).data||[]}catch{return}if(e.length>0){if(!w.resolved.org){let s=e[0],i=s.key;w.writeProperty("org",i),t.format!=="json"&&console.log(`
|
|
20
|
+
`+v.cyan(`\u2139 Automatically set default organization to "${s.name}" (${i}).`))}return}if(t.format==="json")return;console.log(`
|
|
21
|
+
`+v.yellow("\u26A0 It looks like you do not have any organizations yet.")),console.log("Let's set up your first organization now.");let o="";for(;!o;)o=await z("Enter organization name:"),o||console.log(v.red("Error: Organization name cannot be empty."));let n;try{n=await d.organizations.slugs.generate(o,{token:d.token})}catch{n=o.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")}if(!await le(`Use suggested organization slug "${n}"?`,!0)){let s=!1;for(;!s;){let i=await z("Enter organization slug:");if(!i){console.log(v.red("Error: Slug cannot be empty."));continue}try{let a=await d.organizations.slugs.validate(i,{token:d.token});a.valid?(n=i,s=!0):console.log(v.red(`Error: ${a.reason||"Invalid slug"}`))}catch{console.log(v.red("Error validating slug with server. Please try another slug."))}}}console.log(`
|
|
22
|
+
Creating organization "${o}" with slug "${n}"...`);try{let i=(await d.organizations.create(o,n,{token:d.token})).key;w.writeProperty("org",i),console.log(`
|
|
23
|
+
`+v.green(`\u2714 Organization "${o}" created successfully!`)),console.log(`Set as default organization: ${v.cyan(i)}`)}catch(s){let i=U(s);console.log(v.red(`Error creating organization: ${i.message}`))}}function Re(){let d=w.resolved.token;if(!d)return null;try{let t=d.split(".");if(t.length===3){let e=t[1],o=Buffer.from(e,"base64url").toString("utf8"),n=JSON.parse(o);if(n&&typeof n=="object")return n.jti||n.id||null}}catch{}return null}function ue(d){let t=d.command("tokens").description("Manage personal access tokens");t.command("list").description("List all personal access tokens").action(async()=>{let e=new $({format:w.resolved.format});try{let o=C();o.token||(e.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1));let n=await o.users.listTokens({token:o.token}),r=Re(),s=n.map(i=>({id:i.id,name:i.name||"N/A",lastUsedAt:i.lastUsedAt||"Never",expiresAt:i.expiresAt||"Never",active:i.id===r?"Yes":"No"}));e.list(s,["id","name","lastUsedAt","expiresAt","active"],{headers:["ID","NAME","LAST USED","EXPIRES","ACTIVE"]})}catch(o){let n=U(o);e.error(n),process.exit(1)}}),t.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 e=>{let o=new $({format:w.resolved.format});try{let n=C();n.token||(o.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1));let r={};e.name&&(r.name=e.name),e.expiresAt&&(/^\d+$/.test(e.expiresAt)?r.expiresAt=parseInt(e.expiresAt,10):r.expiresAt=e.expiresAt);let s=await n.users.createToken(r,{token:n.token});w.resolved.format==="json"?o.success("Token created successfully!",s):(o.success("Token created successfully!"),console.log(`
|
|
24
|
+
`+v.yellow("\u26A0 WARNING: Make sure to copy your personal access token now. You will NOT be able to see it again!")+`
|
|
25
|
+
`),console.log(`${v.bold("Raw Token")}: ${v.cyan(s.token)}`),console.log(`${v.bold("ID")}: ${s.id}`),console.log(`${v.bold("Name")}: ${s.name||"N/A"}`),console.log(`${v.bold("Type")}: ${s.type}`),console.log(`${v.bold("Expires At")}: ${s.expiresAt||"Never"}
|
|
26
|
+
`))}catch(n){let r=U(n);o.error(r),process.exit(1)}}),t.command("delete <id>").description("Delete a personal access token by ID").action(async e=>{let o=new $({format:w.resolved.format});try{let n=C();n.token||(o.error({code:"CLI_ERR_UNAUTHORIZED",message:"Not logged in.",detail:"Use `apinow auth login <provider>` to authenticate."}),process.exit(1)),await n.users.deleteToken(e,{token:n.token}),o.success(`Token '${e}' deleted successfully.`)}catch(n){let r=U(n);o.error(r),process.exit(1)}})}function pe(d){let t=d.command("auth").description("Manage CLI authentication");ue(t),t.command("login").description("Authenticate with the API platform using OAuth2 (google, github, or linkedin)").addArgument(new Ce("provider","Authentication provider").choices(["google","github","linkedin"])).action(async e=>{let o=new $({format:w.resolved.format}),n=["google","github","linkedin"];n.includes(e)||(o.error({message:`Invalid provider '${e}'. Allowed: ${n.join(", ")}`}),process.exit(1));let r=w.resolved.apiUrl;w.resolved.format!=="json"&&console.log(`Starting authentication flow using provider '${e}'...`);try{await xe(r,e,o),o.success("Successfully authenticated!");let s=C();await ie(s,o)}catch(s){s instanceof Error?o.error({message:s.message}):o.error({message:"Authentication failed."}),process.exit(1)}}),t.command("logout").description("Log out and clear the stored token").action(()=>{let e=new $({format:w.resolved.format});w.clearConfigKey("token"),e.success("Logged out successfully.")}),t.command("status").description("Check current authentication status").action(async()=>{let e=new $({format:w.resolved.format}),o=w.resolved;o.token||(e.error({message:"Not logged in. Use `auth login <provider>` to authenticate."}),process.exit(1));try{let n=C(),r=await n.users.me({token:n.token});o.format==="json"?e.object({authenticated:!0,user:r}):(console.log(v.green("\u2714 Authenticated successfully!")),console.log(`User: ${r.name} (${r.email})`),console.log(`Default Org: ${o.org||"None"}`)),await ie(n,e)}catch(n){let r=U(n);e.error({message:"Authentication token is invalid or expired.",detail:r.message}),process.exit(1)}})}function xe(d,t,e){return new Promise((o,n)=>{let r=Ue.createServer((c,u)=>{if(c.method==="GET"&&c.url?.startsWith("/callback")){Q("auth",`Received request for callback: ${c.url}`),u.writeHead(200,{"Content-Type":"text/html"});let p=`
|
|
27
|
+
<!DOCTYPE html>
|
|
28
|
+
<html>
|
|
29
|
+
<head>
|
|
30
|
+
<title>API NOW! CLI Login</title>
|
|
31
|
+
<style>
|
|
32
|
+
body {
|
|
33
|
+
font-family: system-ui, -apple-system, sans-serif;
|
|
34
|
+
display: flex;
|
|
35
|
+
align-items: center;
|
|
36
|
+
justify-content: center;
|
|
37
|
+
height: 100vh;
|
|
38
|
+
margin: 0;
|
|
39
|
+
background: #121214;
|
|
40
|
+
color: #e1e1e6;
|
|
27
41
|
}
|
|
28
|
-
|
|
29
|
-
|
|
42
|
+
.card {
|
|
43
|
+
background: #202024;
|
|
44
|
+
padding: 2rem;
|
|
45
|
+
border-radius: 8px;
|
|
46
|
+
box-shadow: 0 4px 12px rgba(0,0,0,0.5);
|
|
47
|
+
text-align: center;
|
|
48
|
+
max-width: 450px;
|
|
49
|
+
width: 100%;
|
|
30
50
|
}
|
|
31
|
-
|
|
32
|
-
|
|
51
|
+
h1 { color: #04d361; margin-top: 0; }
|
|
52
|
+
.status { font-weight: bold; margin: 1rem 0; line-height: 1.4; }
|
|
53
|
+
.diagnostics {
|
|
54
|
+
display: none;
|
|
55
|
+
text-align: left;
|
|
56
|
+
margin-top: 1.5rem;
|
|
57
|
+
padding: 1rem;
|
|
58
|
+
background: #2f2f33;
|
|
59
|
+
border-radius: 4px;
|
|
60
|
+
font-size: 0.8rem;
|
|
61
|
+
font-family: monospace;
|
|
62
|
+
white-space: pre-wrap;
|
|
63
|
+
word-break: break-all;
|
|
64
|
+
border-left: 4px solid #f75a68;
|
|
33
65
|
}
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
66
|
+
</style>
|
|
67
|
+
</head>
|
|
68
|
+
<body>
|
|
69
|
+
<div class="card">
|
|
70
|
+
<h1>API NOW!</h1>
|
|
71
|
+
<p class="status" id="status">Retrieving token from server...</p>
|
|
72
|
+
<div class="diagnostics" id="diagnostics">
|
|
73
|
+
<strong>Diagnostic Details:</strong>
|
|
74
|
+
<div id="diagnostics-content" style="margin-top: 0.5rem;"></div>
|
|
75
|
+
</div>
|
|
76
|
+
</div>
|
|
77
|
+
<script>
|
|
78
|
+
fetch('${d}/auth/token', { credentials: 'include' })
|
|
79
|
+
.then(r => {
|
|
80
|
+
if (!r.ok) {
|
|
81
|
+
throw new Error('Token request failed: ' + r.statusText + ' (status: ' + r.status + ')');
|
|
82
|
+
}
|
|
83
|
+
return r.json();
|
|
84
|
+
})
|
|
85
|
+
.then(data => {
|
|
86
|
+
console.log("[DEBUG] Parse response JSON:", data);
|
|
87
|
+
const token = data.token || data.data?.token || data.data;
|
|
88
|
+
if (!token) {
|
|
89
|
+
throw new Error('Token not found in API response structure');
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
console.log("[DEBUG] POSTing token to local server callback...");
|
|
93
|
+
return fetch('/token', {
|
|
94
|
+
method: 'POST',
|
|
95
|
+
headers: { 'Content-Type': 'application/json' },
|
|
96
|
+
body: JSON.stringify({ token })
|
|
97
|
+
});
|
|
98
|
+
})
|
|
99
|
+
.then(r => {
|
|
100
|
+
if (!r.ok) {
|
|
101
|
+
throw new Error('Failed to save token in CLI server (status: ' + r.status + ')');
|
|
102
|
+
}
|
|
103
|
+
document.getElementById('status').innerText = 'Authentication successful! You can close this tab now.';
|
|
104
|
+
document.getElementById('status').style.color = '#04d361';
|
|
105
|
+
})
|
|
106
|
+
.catch(err => {
|
|
107
|
+
console.error("[ERROR]", err);
|
|
108
|
+
document.getElementById('status').innerText = 'Authentication failed.';
|
|
109
|
+
document.getElementById('status').style.color = '#f75a68';
|
|
110
|
+
|
|
111
|
+
const diag = document.getElementById('diagnostics');
|
|
112
|
+
const content = document.getElementById('diagnostics-content');
|
|
113
|
+
diag.style.display = 'block';
|
|
114
|
+
content.innerText =
|
|
115
|
+
'Error Message: ' + err.message + '\\n\\n' +
|
|
116
|
+
'Originating URL: ' + window.location.href + '\\n' +
|
|
117
|
+
'Target API URL: ${d}/auth/token\\n\\n' +
|
|
118
|
+
'TIP: If you get "Unauthorized (status: 401)", make sure that:\\n' +
|
|
119
|
+
'1. You completed the login flow on the browser window that opened.\\n' +
|
|
120
|
+
'2. The host of the page you are on (' + window.location.hostname + ') matches the host of the API (' + new URL('${d}').hostname + ') to satisfy SameSite cookie policy.\\n' +
|
|
121
|
+
'3. Check browser developer console (F12) for detailed CORS/Network errors.';
|
|
122
|
+
|
|
123
|
+
fetch('/error', {
|
|
124
|
+
method: 'POST',
|
|
125
|
+
headers: { 'Content-Type': 'application/json' },
|
|
126
|
+
body: JSON.stringify({ message: err.message })
|
|
127
|
+
}).catch(console.error);
|
|
128
|
+
});
|
|
129
|
+
</script>
|
|
130
|
+
</body>
|
|
131
|
+
</html>
|
|
132
|
+
`;u.end(p);return}if(c.method==="POST"&&c.url==="/token"){let p="";c.on("data",m=>{p+=m}),c.on("end",()=>{try{let m=JSON.parse(p);m.token?(Q("auth","Storing retrieved token to CLI configuration..."),w.writeProperty("token",m.token),u.writeHead(200,{"Content-Type":"application/json"}),u.end(JSON.stringify({success:!0})),o(m.token)):(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:"Token missing"})),n(new Error("Token missing from browser callback.")))}catch(m){m instanceof Error?(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:m.message})),n(new Error("Invalid body received: "+m.message))):(u.writeHead(400,{"Content-Type":"application/json"}),u.end(JSON.stringify({error:"Invalid body received"})),n(new Error("Invalid body received")))}finally{a()}});return}if(c.method==="POST"&&c.url==="/error"){let p="";c.on("data",m=>{p+=m}),c.on("end",()=>{try{let m=JSON.parse(p);Q("auth",`Received login error from browser callback: ${m.message}`),n(new Error(m.message||"Browser login failed"))}catch{n(new Error("Browser login failed"))}finally{a()}});return}u.writeHead(404),u.end()}),s=()=>{a(),process.exit(130)};process.on("SIGINT",s),process.on("SIGTERM",s);let i=setTimeout(()=>{n(new Error("Authentication timed out.")),a()},3e5);function a(){clearTimeout(i),process.off("SIGINT",s),process.off("SIGTERM",s),r.close()}r.listen(0,"127.0.0.1",async()=>{let c=r.address().port,p=new URL(d).hostname==="localhost"?"localhost":"127.0.0.1",m=`${d}/auth/${t}/redirect?r=http://${p}:${c}/callback`;Q("auth",`Ephemeral loopback server listening on http://127.0.0.1:${c}`),Q("auth",`Browser callback origin configured to http://${p}:${c}`),e.format!=="json"&&(console.log("Opening browser to log in..."),console.log(`If it doesn't open automatically, navigate to:
|
|
133
|
+
${m}`));try{await Pe(m)}catch{}})})}function he(d){let t=d.command("orgs").description("Manage organization configurations");t.command("list").description("List all organizations you belong to").action(async()=>{let e=new $({format:w.resolved.format});try{let o=C(),r=(await o.organizations.list({token:o.token})).data||[],s=w.resolved,i=r.map(a=>({id:a.key,name:a.name,slug:a.slug,isDefault:a.key===s.org?"Yes":"No"}));e.list(i,["id","name","slug","isDefault"],{headers:["ID","NAME","SLUG","DEFAULT"]})}catch(o){let n=U(o);e.error(n),process.exit(1)}}),t.command("set-default <oid>").description("Set your default organization ID").action(async e=>{let o=new $({format:w.resolved.format});try{let n=C();((await n.organizations.list({token:n.token})).data||[]).some(a=>a.key===e)||(o.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Organization ID '${e}' not found in your authorized list.`,detail:"Run `apinow orgs list` to see all authorized organizations and their IDs."}),process.exit(1)),w.writeProperty("org",e),o.success(`Default organization ID set to '${e}'.`)}catch(n){let r=U(n);o.error(r),process.exit(1)}}),t.command("default").alias("get-default").description("Get the default configured organization").action(async()=>{let e=new $({format:w.resolved.format});try{let o=w.resolved;o.org||(e.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));let n=C(),i=((await n.organizations.list({token:n.token})).data||[]).find(a=>a.key===o.org);i||(e.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Default organization ID '${o.org}' not found in your authorized list.`,detail:"Run `apinow orgs set-default <oid>` to configure a valid default organization."}),process.exit(1)),e.object({id:i.key,name:i.name,slug:i.slug})}catch(o){let n=U(o);e.error(n),process.exit(1)}})}import ge from"node:fs";import Fe from"node:path";var ft=class d{key;get kind(){return F}catalogKey;scope;lifecycle;version;publishedBy;unpublishedAt;deprecated;deprecatedAt;deprecatedBy;deprecationReason;createdAt;updatedAt;changelog;static createSchema(t){let{key:e="",scope:o="private",publishedBy:n="",createdAt:r=0,updatedAt:s=0,catalogKey:i="",lifecycle:a="stable",version:c=""}=t;if(["public","private","organization"].indexOf(o)===-1)throw new Error(`Invalid scope: ${o}`);let u={key:e,kind:F,scope:o,publishedBy:n,createdAt:r,updatedAt:s,catalogKey:i,lifecycle:a,version:c};return typeof t.deprecated=="boolean"&&(u.deprecated=t.deprecated),typeof t.deprecatedAt=="number"&&(u.deprecatedAt=t.deprecatedAt),typeof t.deprecatedBy=="string"&&(u.deprecatedBy=t.deprecatedBy),typeof t.changelog=="string"&&(u.changelog=t.changelog),typeof t.deprecationReason=="string"&&(u.deprecationReason=t.deprecationReason),typeof t.unpublishedAt=="number"&&(u.unpublishedAt=t.unpublishedAt),u}constructor(t={}){let e=d.createSchema(t);this.key=e.key,this.catalogKey=e.catalogKey,this.lifecycle=e.lifecycle,this.scope=e.scope,this.version=e.version,this.publishedBy=e.publishedBy,this.createdAt=e.createdAt,this.updatedAt=e.updatedAt,typeof e.changelog=="string"&&(this.changelog=e.changelog),typeof e.deprecated=="boolean"&&(this.deprecated=e.deprecated),typeof e.deprecatedAt=="number"&&(this.deprecatedAt=e.deprecatedAt),typeof e.deprecatedBy=="string"&&(this.deprecatedBy=e.deprecatedBy),typeof e.deprecationReason=="string"&&(this.deprecationReason=e.deprecationReason),typeof e.unpublishedAt=="number"&&(this.unpublishedAt=e.unpublishedAt)}toJSON(){let t={key:this.key,kind:F,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"&&(t.deprecated=this.deprecated),typeof this.deprecatedAt=="number"&&(t.deprecatedAt=this.deprecatedAt),typeof this.deprecatedBy=="string"&&(t.deprecatedBy=this.deprecatedBy),typeof this.deprecationReason=="string"&&(t.deprecationReason=this.deprecationReason),typeof this.unpublishedAt=="number"&&(t.unpublishedAt=this.unpublishedAt),typeof this.changelog=="string"&&this.changelog&&(t.changelog=this.changelog),t}};var g;(function(d){d.User="Semantic#User",d.Address="Semantic#Address",d.Password="Semantic#Password",d.Username="Semantic#Username",d.CreatedTimestamp="Semantic#CreatedTimestamp",d.UpdatedTimestamp="Semantic#UpdatedTimestamp",d.DeletedTimestamp="Semantic#DeletedTimestamp",d.DeletedFlag="Semantic#DeletedFlag",d.PublicUniqueName="Semantic#PublicUniqueName",d.Title="Semantic#Title",d.Name="Semantic#Name",d.UserRole="Semantic#UserRole",d.Status="Semantic#Status",d.Version="Semantic#Version",d.ImageURL="Semantic#ImageURL",d.FileURL="Semantic#FileURL",d.Markdown="Semantic#Markdown",d.HTML="Semantic#HTML",d.GeospatialCoordinates="Semantic#GeospatialCoordinates",d.Email="Semantic#Email",d.Phone="Semantic#Phone",d.Currency="Semantic#Currency",d.URL="Semantic#URL",d.SKU="Semantic#SKU",d.Description="Semantic#Description",d.Summary="Semantic#Summary",d.Calculated="Semantic#Calculated",d.Derived="Semantic#Derived",d.ClientIPAddress="Semantic#ClientIPAddress",d.StreetAddress="Semantic#StreetAddress",d.StreetAddressSupplemental="Semantic#StreetAddressSupplemental",d.City="Semantic#City",d.PostalCode="Semantic#PostalCode",d.Country="Semantic#Country",d.Region="Semantic#Region",d.ResourceOwnerIdentifier="Semantic#ResourceOwnerIdentifier",d.Tags="Semantic#Tags",d.Categories="Semantic#Categories"})(g||(g={}));var I;(function(d){d.Entity="Entity",d.Property="Property",d.Association="Association"})(I||(I={}));var O;(function(d){d.Identity="Identity & Authentication",d.Lifecycle="Timestamps & Versioning",d.Content="Content & Media",d.Business="Business Data",d.Organization="Classification & Organization",d.Location="Location & Geography",d.Contact="Contact Information",d.Computed="Computed Values"})(O||(O={}));var De={[g.User]:{id:g.User,displayName:"User Entity",scope:I.Entity,description:"System users and accounts",category:O.Identity,hasConfig:!1},[g.Password]:{id:g.Password,displayName:"User Password",scope:I.Property,description:"Secure password field",category:O.Identity,applicableDataTypes:["string"],hasConfig:!0},[g.Username]:{id:g.Username,displayName:"Username",scope:I.Property,description:"User authentication identifier",category:O.Identity,applicableDataTypes:["string"],hasConfig:!1},[g.UserRole]:{id:g.UserRole,displayName:"User Role Field",scope:I.Property,description:"User permissions and access level",category:O.Identity,applicableDataTypes:["string"],hasConfig:!0},[g.ResourceOwnerIdentifier]:{id:g.ResourceOwnerIdentifier,displayName:"Resource Owner Identifier",scope:I.Association,description:"Links record to owner user",category:O.Identity,hasConfig:!1},[g.CreatedTimestamp]:{id:g.CreatedTimestamp,displayName:"Creation Timestamp",scope:I.Property,description:"When record was created",category:O.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.UpdatedTimestamp]:{id:g.UpdatedTimestamp,displayName:"Update Timestamp",scope:I.Property,description:"When record was last modified",category:O.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.DeletedTimestamp]:{id:g.DeletedTimestamp,displayName:"Soft Delete Timestamp",scope:I.Property,description:"When record was marked deleted",category:O.Lifecycle,applicableDataTypes:["datetime"],hasConfig:!1},[g.DeletedFlag]:{id:g.DeletedFlag,displayName:"Soft Delete Flag",scope:I.Property,description:"Mark record as deleted",category:O.Lifecycle,applicableDataTypes:["boolean"],hasConfig:!1},[g.Address]:{id:g.Address,displayName:"Address Entity",scope:I.Entity,description:"Physical address entity",category:O.Contact,hasConfig:!1},[g.StreetAddress]:{id:g.StreetAddress,displayName:"Street Address",scope:I.Property,description:"Street address line",category:O.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.StreetAddressSupplemental]:{id:g.StreetAddressSupplemental,displayName:"Street Address Supplemental",scope:I.Property,description:"Supplemental street address line (e.g., Unit, Suite, Apartment, Floor)",category:O.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.City]:{id:g.City,displayName:"City",scope:I.Property,description:"City or locality",category:O.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.PostalCode]:{id:g.PostalCode,displayName:"Postal Code",scope:I.Property,description:"Postal or zip code",category:O.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Country]:{id:g.Country,displayName:"Country",scope:I.Property,description:"Country name or code",category:O.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Region]:{id:g.Region,displayName:"Region",scope:I.Property,description:"State, province, or region",category:O.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.Version]:{id:g.Version,displayName:"Version Number",scope:I.Property,description:"Auto-incrementing version counter",category:O.Lifecycle,applicableDataTypes:["number"],hasConfig:!1},[g.Title]:{id:g.Title,displayName:"Record Title",scope:I.Property,description:"Main title or heading",category:O.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Name]:{id:g.Name,displayName:"Name",scope:I.Property,description:"A person or pet name",category:O.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Description]:{id:g.Description,displayName:"Description",scope:I.Property,description:"Detailed description text",category:O.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Summary]:{id:g.Summary,displayName:"Summary",scope:I.Property,description:"Brief summary text",category:O.Content,applicableDataTypes:["string"],hasConfig:!1},[g.Markdown]:{id:g.Markdown,displayName:"Markdown Content",scope:I.Property,description:"Formatted text content",category:O.Content,applicableDataTypes:["string"],hasConfig:!0},[g.HTML]:{id:g.HTML,displayName:"HTML Content",scope:I.Property,description:"Rich HTML content",category:O.Content,applicableDataTypes:["string"],hasConfig:!0},[g.ImageURL]:{id:g.ImageURL,displayName:"Image URL",scope:I.Property,description:"Link to image file",category:O.Content,applicableDataTypes:["string"],hasConfig:!0},[g.FileURL]:{id:g.FileURL,displayName:"File URL",scope:I.Property,description:"Link to file attachment",category:O.Content,applicableDataTypes:["string"],hasConfig:!0},[g.Status]:{id:g.Status,displayName:"Record Status",scope:I.Property,description:"Current state of record",category:O.Business,applicableDataTypes:["string"],hasConfig:!0},[g.Currency]:{id:g.Currency,displayName:"Currency",scope:I.Property,description:"Monetary value with currency",category:O.Business,applicableDataTypes:["number","string"],hasConfig:!0},[g.SKU]:{id:g.SKU,displayName:"SKU",scope:I.Property,description:"Product identification code",category:O.Business,applicableDataTypes:["string"],hasConfig:!0},[g.Email]:{id:g.Email,displayName:"Email",scope:I.Property,description:"Email address",category:O.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.Phone]:{id:g.Phone,displayName:"Phone",scope:I.Property,description:"Phone number",category:O.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.URL]:{id:g.URL,displayName:"URL",scope:I.Property,description:"Web address or link",category:O.Contact,applicableDataTypes:["string"],hasConfig:!0},[g.ClientIPAddress]:{id:g.ClientIPAddress,displayName:"Client IP Address",scope:I.Property,description:"Automatically populated client IP address",category:O.Contact,applicableDataTypes:["string"],hasConfig:!1},[g.PublicUniqueName]:{id:g.PublicUniqueName,displayName:"Public Unique Name (Slug)",scope:I.Property,description:"URL-friendly unique identifier",category:O.Organization,applicableDataTypes:["string"],hasConfig:!0},[g.Tags]:{id:g.Tags,displayName:"Tags",scope:I.Association,description:"Enable tagging functionality",category:O.Organization,hasConfig:!0},[g.Categories]:{id:g.Categories,displayName:"Categories",scope:I.Association,description:"Enable categorization functionality",category:O.Organization,hasConfig:!0},[g.GeospatialCoordinates]:{id:g.GeospatialCoordinates,displayName:"Geospatial Coordinates",scope:I.Property,description:"Location coordinates",category:O.Location,applicableDataTypes:["string"],hasConfig:!0},[g.Calculated]:{id:g.Calculated,displayName:"Calculated",scope:I.Property,description:"Auto-calculated field value",category:O.Computed,applicableDataTypes:["string","number","boolean","date","datetime","time","binary"],hasConfig:!0},[g.Derived]:{id:g.Derived,displayName:"Derived",scope:I.Property,description:"Value derived from other fields",category:O.Computed,applicableDataTypes:["string"],hasConfig:!0}};var oe;(function(d){d[d.Initializing=0]="Initializing",d[d.PendingDns=1]="PendingDns",d[d.Issuing=2]="Issuing",d[d.Active=3]="Active",d[d.Error=4]="Error"})(oe||(oe={}));function Ee(d){let t=d.command("files").description("Manage files and metadata");t.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 e=>{let o=new $({format:w.resolved.format}),n=w.resolved,r=e.org||n.org;r||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Organization ID is required.",detail:"Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."}),process.exit(1));try{let s=C(),i={};if(e.parent&&(i.parent=e.parent),e.kind){let p=ye(e.kind);i.filter={field:"kind",operator:"eq",value:p}}let u=((await s.files.list(r,i,{token:s.token})).data||[]).map(p=>({id:p.key,name:p.info?.name||"",kind:p.kind,isShortcut:p.isShortcut?"Yes":"No"}));o.list(u,["id","name","kind","isShortcut"],{headers:["ID","NAME","KIND","SHORTCUT"]})}catch(s){let i=U(s);o.error(i),process.exit(1)}}),t.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 e=>{let o=new $({format:w.resolved.format}),n=w.resolved,r=e.org||n.org;r||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Organization ID is required.",detail:"Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."}),process.exit(1)),e.media&&e.stdin&&(o.error({code:"CLI_ERR_INVALID_ARGUMENT",message:"Cannot specify both --media <path> and --stdin"}),process.exit(1));let s=e.name;!s&&process.stdout.isTTY&&(s=await z("Enter file name:")),s||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));let i=e.kind;!i&&process.stdout.isTTY&&(i=await st("Select file kind:",[{name:"API Domain / Schema (domain)",value:"domain"},{name:"API Schema (api)",value:"api"},{name:"Folder (folder)",value:"folder"}])),i||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Kind is required.",detail:"Specify --kind <kind> (allowed: api, domain, folder)."}),process.exit(1));try{let a;if(e.media){let A=Fe.resolve(e.media);ge.existsSync(A)||(o.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Media file not found at path: ${A}`}),process.exit(1)),a=ge.readFileSync(A,"utf8")}else e.stdin&&(a=await je());let c,u;if(a!==void 0){try{u=JSON.parse(a)}catch{throw new Error("invalid API now platform file")}if(!u||typeof u!="object"||Array.isArray(u)||!("key"in u)||typeof u.key!="string"||!u.key.trim())throw new Error("invalid API now platform file");c=u.key}let p=C(),m=j.createSchema({kind:ye(i),info:{name:s},key:c}),b={};e.parent&&(b.parent=e.parent);let y=await p.files.createMeta(m,r,b,{token:p.token}),E=y.key;a!==void 0&&await p.files.createMedia(u,r,E,{},{token:p.token}),o.success("File created successfully!",y)}catch(a){let c=U(a);o.error({code:"CLI_ERR_API_FAILURE",...c}),process.exit(1)}}),t.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 e=>{let o=new $({format:w.resolved.format}),n=w.resolved,r=e.org||n.org;r||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Organization ID is required.",detail:"Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."}),process.exit(1));let s=e.id;if(!s&&process.stdout.isTTY)try{let i=C(),c=(await i.files.list(r,{},{token:i.token})).data||[];c.length>0&&(s=await st("Select a file to read:",c.map(u=>({name:`${u.info?.name||"Unnamed"} (${u.kind})`,value:u.key}))))}catch{}s||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --id <fid>."}),process.exit(1));try{let i=C();if(e.media){let c=(await i.files.readMedia(r,s,{token:i.token})).media;n.format==="json"?console.log(JSON.stringify(c,null,2)):console.log(typeof c=="object"&&c!==null?JSON.stringify(c,null,2):c)}else{let a=await i.files.read(r,s,{token:i.token});o.object(a)}}catch(i){let a=U(i);o.error(a),process.exit(1)}})}function ye(d){let t=d.toLowerCase();if(t==="api")return ce;if(t==="domain")return Nt;if(t==="folder")return T;throw new Error(`Unsupported file kind "${d}". Allowed: api, domain, folder`)}async function je(){return new Promise((d,t)=>{let e="";process.stdin.setEncoding("utf8"),process.stdin.on("data",o=>{e+=o}),process.stdin.on("end",()=>{d(e)}),process.stdin.on("error",o=>{t(o)})})}function Se(d){let t=d.command("catalog").description("Manage Data Catalog items");t.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("-v, --catalog-version <ver>","Semantic version (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 e=>{let o=new $({format:w.resolved.format}),n=w.resolved,r=e.org||n.org;r||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Organization ID is required.",detail:"Pass --org <oid> or set a default organization using `apinow orgs set-default <oid>`."}),process.exit(1));let s=e.file;if(!s&&process.stdout.isTTY)try{let b=C(),E=(await b.files.list(r,{filter:{field:"kind",operator:"eq",value:Nt}},{token:b.token})).data||[];E.length>0&&(s=await st("Select a data domain file to publish:",E.map(A=>({name:`${A.info?.name||"Unnamed"} (${A.key})`,value:A.key}))))}catch{}s||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"File ID is required.",detail:"Specify --file <fid>."}),process.exit(1));let i=e.name;!i&&process.stdout.isTTY&&(i=await z("Enter catalog entry name:")),i||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Name is required.",detail:"Specify --name <name>."}),process.exit(1));let a=e.description;!a&&process.stdout.isTTY&&(a=await z("Enter catalog entry description:")),a||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Description is required.",detail:"Specify --description <desc>."}),process.exit(1));let c=e.scope;!c&&process.stdout.isTTY&&(c=await st("Select publish scope:",[{name:"Public (public)",value:"public"},{name:"Organization (organization)",value:"organization"},{name:"Private (private)",value:"private"}])),c||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Scope is required.",detail:"Specify --scope <scope> (allowed: public, organization, private)."}),process.exit(1));let u=["public","organization","private"];u.includes(c)||(o.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid scope '${c}'.`,detail:`Allowed: ${u.join(", ")}`}),process.exit(1));let p=e.catalogVersion;!p&&process.stdout.isTTY&&(p=await z("Enter semantic version:","1.0.0")),p||(o.error({code:"CLI_ERR_MISSING_REQUIRED",message:"Version is required.",detail:"Specify --catalog-version <ver> or -v <ver>."}),process.exit(1));let m=["dev","beta","stable"];m.includes(e.lifecycle)||(o.error({code:"CLI_ERR_INVALID_ARGUMENT",message:`Invalid lifecycle '${e.lifecycle}'.`,detail:`Allowed: ${m.join(", ")}`}),process.exit(1));try{let b=C(),y=null;try{y=(await b.dataCatalog.checkPublicationStatus(s,r,{token:b.token})).key}catch(P){if(U(P).status!==404)throw P}if(y)w.resolved.format!=="json"&&console.log(`Catalog entry already exists (ID: ${y}). Publishing new version...`);else{w.resolved.format!=="json"&&console.log("Catalog entry does not exist. Creating new catalog entry...");let P={key:"",kind:K,organization:r,file:s,scope:c,name:i,description:a,publishedBy:"",publishedAt:0,createdAt:0,updatedAt:0,tags:[]};y=(await b.dataCatalog.publish(P,{token:b.token})).key}let E=ft.createSchema({scope:c,lifecycle:e.lifecycle,version:p,changelog:e.changelog||void 0}),A=await b.dataCatalog.publishVersion(y,E,{token:b.token});o.success(`Successfully published version '${p}' to the data catalog!`,A)}catch(b){let y=U(b);o.error(y),process.exit(1)}}),t.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 e=>{let o=new $({format:w.resolved.format}),n=w.resolved,r=e.org||n.org,s=["all","public","organization","private"];s.includes(e.scope)||(o.error({message:`Invalid scope '${e.scope}'. Allowed: ${s.join(", ")}`}),process.exit(1)),["organization","private"].includes(e.scope)&&!r&&(o.error({message:`Organization ID (--org <oid>) is required when filtering by scope '${e.scope}'.`}),process.exit(1));try{let i=C();if(e.key){let u=((await i.dataCatalog.listVersions(e.key,{token:i.token})).data||[]).map(p=>({key:p.key,version:p.version,published:new Date(p.published).toLocaleString()}));o.list(u,["key","version","published"],{headers:["VERSION KEY","VERSION","PUBLISHED AT"]})}else{let a=[];if(e.scope==="all"){let m=await i.dataCatalog.list({scope:"public",oid:r},{token:i.token});if(a.push(...m.data||[]),r){try{let b=await i.dataCatalog.list({scope:"organization",oid:r},{token:i.token});a.push(...b.data||[])}catch{}try{let b=await i.dataCatalog.list({scope:"private",oid:r},{token:i.token});a.push(...b.data||[])}catch{}}}else{let m=await i.dataCatalog.list({scope:e.scope,oid:r},{token:i.token});a.push(...m.data||[])}let c=new Set,p=a.filter(m=>{let b=m.key;return c.has(b)?!1:(c.add(b),!0)}).map(m=>{let b=m.versions&&m.versions[0]?m.versions[0].version:"N/A";return{key:m.key,name:m.name,scope:m.scope,lastVersion:b,organization:m.organization||"N/A"}});o.list(p,["key","name","scope","lastVersion","organization"],{headers:["KEY","NAME","SCOPE","LAST VERSION","ORGANIZATION"]})}}catch(i){let a=U(i);o.error(a),process.exit(1)}})}parseInt(process.versions.node.split(".")[0],10)<22&&(console.error("Error: apinow requires Node.js 22 or higher."),process.exit(1));function ke(){let d=process.argv.indexOf("--format");if(d!==-1&&d+1<process.argv.length&&process.argv[d+1]==="json")return"json";try{return w.resolved.format||"text"}catch{return"text"}}process.on("uncaughtException",d=>{new $({format:ke()}).error({code:"CLI_ERR_UNKNOWN",message:d.message||"An unexpected error occurred.",detail:d.stack}),process.exit(1)});process.on("unhandledRejection",d=>{let t=new $({format:ke()}),e=d instanceof Error?d.message:String(d),o=d instanceof Error?d.stack:void 0;t.error({code:"CLI_ERR_UNKNOWN",message:`Unhandled promise rejection: ${e}`,detail:o}),process.exit(1)});ze({pkg:ot}).notify();w.load();var M=new Be;M.name("apinow").description("API NOW! Platform CLI Tool").version(ot.version,"--version").option("--format <format>","Output format: text, json","text").option("--api-url <url>","Override target API server base URL").option("--debug","Enable debug/verbose logging");M.hook("preAction",()=>{w.saturate({apiUrl:M.opts().apiUrl,format:M.opts().format})});re(M);pe(M);he(M);Ee(M);Se(M);await M.parseAsync(process.argv);
|
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.0
|
|
4
|
+
"version": "1.1.0",
|
|
5
5
|
"private": false,
|
|
6
6
|
"publishConfig": {
|
|
7
7
|
"registry": "https://registry.npmjs.org/",
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
"apinow": "dist/index.js"
|
|
20
20
|
},
|
|
21
21
|
"scripts": {
|
|
22
|
-
"build": "
|
|
22
|
+
"build": "node esbuild.config.js",
|
|
23
|
+
"postbuild": "node dist/index.js --help",
|
|
23
24
|
"dev": "tsx src/index.ts",
|
|
24
25
|
"typecheck": "tsc --noEmit",
|
|
25
26
|
"lint": "eslint \"src/**/*.ts\"",
|
|
@@ -30,13 +31,15 @@
|
|
|
30
31
|
"knip": "knip"
|
|
31
32
|
},
|
|
32
33
|
"dependencies": {
|
|
33
|
-
"@api-now/core": "^1.0.0",
|
|
34
34
|
"@inquirer/prompts": "^8.5.0",
|
|
35
35
|
"commander": "^15.0.0",
|
|
36
|
+
"nanoid": "^5.1.6",
|
|
36
37
|
"open": "^11.0.0",
|
|
38
|
+
"tslib": "^2.8.1",
|
|
37
39
|
"update-notifier": "^7.3.1"
|
|
38
40
|
},
|
|
39
41
|
"devDependencies": {
|
|
42
|
+
"@api-now/core": "^1.0.0",
|
|
40
43
|
"@commitlint/cli": "^21.0.1",
|
|
41
44
|
"@commitlint/config-conventional": "^21.0.1",
|
|
42
45
|
"@eslint/js": "^10.0.1",
|
|
@@ -44,6 +47,7 @@
|
|
|
44
47
|
"@semantic-release/git": "^10.0.1",
|
|
45
48
|
"@types/node": "^25.9.1",
|
|
46
49
|
"@types/update-notifier": "^6.0.8",
|
|
50
|
+
"esbuild": "^0.28.0",
|
|
47
51
|
"eslint": "^10.4.0",
|
|
48
52
|
"eslint-config-prettier": "^10.1.8",
|
|
49
53
|
"eslint-plugin-prettier": "^5.5.6",
|