@sinch/cli 0.1.20-beta.0 → 0.1.22-beta.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/dist/index.js +75 -75
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var Xn=Object.create;var Ve=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var no=Object.getPrototypeOf,oo=Object.prototype.hasOwnProperty;var he=(o,e)=>()=>(o&&(e=o(o=0)),e);var U=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Je=(o,e)=>{for(var n in e)Ve(o,n,{get:e[n],enumerable:!0})},At=(o,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of to(e))!oo.call(o,s)&&s!==n&&Ve(o,s,{get:()=>e[s],enumerable:!(i=eo(e,s))||i.enumerable});return o};var
|
|
3
|
-
`);
|
|
4
|
-
\u26A0\uFE0F OS keychain not available (Docker/CI environment detected)`)),console.log(
|
|
5
|
-
For better security, export as environment variables instead:`)),console.log(te.default.cyan(' export SINCH_KEY_SECRET="'+s+'"')),console.log(te.default.cyan(' export SINCH_APPLICATION_SECRET="'+a+'"')),this.config.set("keySecretPlaintext",s),this.config.set("applicationSecretPlaintext",a)),this.config.set("projectId",n),this.config.set("keyId",i),this.config.set("defaultApplicationKey",r),this.config.set("credentialsStored",!0),await this.config.save()}async storeOAuthToken(e){let{access_token:n,refresh_token:i,expires_in:s,token_type:r}=e,a=new Date(Date.now()+s*1e3).toISOString(),l=await this.setPassword(`${K}-oauth-access`,n),c=!0;i&&(c=await this.setPassword(`${K}-oauth-refresh`,i)),this.config.set("oauthTokenType",r),this.config.set("oauthExpiresAt",a),this.config.set("oauthStored",l&&c),await this.config.save()}async reAuthenticateOAuth(){try{let e=await this.retrieve();if(!e)return null;let{SinchAPI:n}=(x(),F(Ie)),s=await new n({apiUrl:this.config.get("apiUrl")||"https://api.functions.dev.sinchvoice.org",projectId:e.projectId,credentials:null}).authenticateOAuth(e.keyId,e.keySecret);return await this.storeOAuthToken(s),s.access_token}catch{return null}}async getOAuthToken(){if(!this.config.get("oauthStored"))return await this.reAuthenticateOAuth();let n=this.config.get("oauthExpiresAt");if(n&&new Date(n)<new Date){console.log(te.default.gray("Token expired, re-authenticating..."));let i=await this.reAuthenticateOAuth();return i?console.log(te.default.green("\u2713 Token renewed successfully")):console.warn(te.default.yellow("Failed to renew OAuth token. Please login again.")),i}return await this.getPassword(`${K}-oauth-access`)}async storeApplicationSecret(e,n){await this.setPassword(e,n),this.config.get("defaultApplicationKey")||(this.config.set("defaultApplicationKey",e),await this.config.save())}async retrieve(){let e=process.env.SINCH_KEY_ID,n=process.env.SINCH_KEY_SECRET,i=process.env.SINCH_APPLICATION_KEY,s=process.env.SINCH_APPLICATION_SECRET;if(e&&n&&i&&s)return{projectId:process.env.SINCH_PROJECT_ID||this.config.get("projectId")||"",keyId:e,keySecret:n,applicationKey:i,applicationSecret:s};if(!this.config.get("credentialsStored"))return null;let a=this.config.get("projectId"),l=this.config.get("keyId"),c=this.config.get("defaultApplicationKey"),u=await this.getPassword(`${K}-keySecret`),g=c?await this.getPassword(c):null;return(!u||!g)&&(u=u||n||null,g=g||s||null),(!u||!g)&&(u=u||this.config.get("keySecretPlaintext"),g=g||this.config.get("applicationSecretPlaintext")),!u||!g?null:{projectId:a,keyId:l,keySecret:u,applicationKey:c,applicationSecret:g}}async getApplicationCredentials(e=null){if(e||(e=this.config.get("defaultApplicationKey")),!e)return null;let n=await this.getPassword(e);return n||(n=process.env.SINCH_APPLICATION_SECRET||null),n||(n=this.config.get("applicationSecretPlaintext")),n?{applicationKey:e,applicationSecret:n}:null}async clear(){let e=this.config.get("defaultApplicationKey");await this.deletePassword(`${K}-keySecret`),await this.deletePassword(`${K}-oauth-access`),await this.deletePassword(`${K}-oauth-refresh`),e&&await this.deletePassword(e),this.config.set("projectId",null),this.config.set("keyId",null),this.config.set("defaultApplicationKey",null),this.config.set("credentialsStored",!1),this.config.set("oauthStored",!1),this.config.set("oauthTokenType",null),this.config.set("oauthExpiresAt",null),this.config.set("keySecretPlaintext",null),this.config.set("applicationSecretPlaintext",null),await this.config.save()}async hasCredentials(){if(!!(process.env.SINCH_KEY_ID&&process.env.SINCH_KEY_SECRET&&process.env.SINCH_APPLICATION_KEY&&process.env.SINCH_APPLICATION_SECRET))return!0;if(!this.config.get("credentialsStored"))return!1;if(this.config.get("keySecretPlaintext"))return!0;let i=await this.getPassword(`${K}-keySecret`),s=this.config.get("defaultApplicationKey"),r=s?await this.getPassword(s):null;return!!(i&&r)}async hasOAuthToken(){return this.config.get("oauthStored")?!!await this.getPassword(`${K}-oauth-access`):!1}getPublicInfo(){return{projectId:this.config.get("projectId"),keyId:this.config.get("keyId"),applicationKey:this.config.get("defaultApplicationKey"),hasCredentials:this.config.get("credentialsStored",!1),hasOAuth:this.config.get("oauthStored",!1),oauthExpiresAt:this.config.get("oauthExpiresAt")}}async createSinchClient(e=null){let n=await this.getApplicationCredentials(e);if(!n)throw new Error('No credentials found. Please run "sinch auth login" first.');let{SinchClient:i}=require("@sinch/sdk-core");return new i({applicationKey:n.applicationKey,applicationSecret:n.applicationSecret,projectId:this.config.get("projectId")})}async storeBasicAuthToken(e){await this.setPassword(`${K}-basic-auth`,e)&&(this.config.set("basicAuthStored",!0),await this.config.save())}async getBasicAuthToken(){return this.config.get("basicAuthStored")?await this.getPassword(`${K}-basic-auth`):null}async clearBasicAuthToken(){await this.deletePassword(`${K}-basic-auth`),this.config.set("basicAuthStored",!1),await this.config.save()}}});var we={};Je(we,{Config:()=>Ge,config:()=>p});var G,Oe,Dt,ot,Ge,p,j=he(()=>{"use strict";G=m(require("fs-extra")),Oe=m(require("path")),Dt=m(require("os")),ot=m(require("chalk"));jt();Ge=class{configDir;configFile;projectConfigFile;_config=null;_projectConfig=null;_credentials=null;constructor(){this.configDir=Oe.join(Dt.homedir(),".sinch"),this.configFile=Oe.join(this.configDir,"config.json"),this.projectConfigFile=Oe.join(process.cwd(),"sinch.json")}async load(){try{await G.ensureDir(this.configDir),await G.pathExists(this.configFile)?this._config=await G.readJson(this.configFile):(this._config=this._getDefaultConfig(),await this.save())}catch(e){console.warn(ot.default.yellow(`Warning: Could not load config: ${e.message}`)),this._config=this._getDefaultConfig()}this._credentials=new We(this);try{await G.pathExists(this.projectConfigFile)&&(this._projectConfig=await G.readJson(this.projectConfigFile))}catch(e){console.warn(ot.default.yellow(`Warning: Could not load project config: ${e.message}`))}}async save(){try{await G.ensureDir(this.configDir),await G.writeJson(this.configFile,this._config,{spaces:2})}catch(e){throw new Error(`Could not save config: ${e.message}`)}}async saveProjectConfig(){try{if(this._projectConfig){let e=Oe.join(process.cwd(),"sinch.json");await G.writeJson(e,this._projectConfig,{spaces:2})}}catch(e){throw new Error(`Could not save project config: ${e.message}`)}}get(e,n=null){if(!this._config)throw new Error("Config not loaded. Call load() first.");return this._projectConfig&&this._projectConfig[e]!==void 0?this._projectConfig[e]:this._config[e]!==void 0?this._config[e]:n}set(e,n,i=!1){if(!this._config)throw new Error("Config not loaded. Call load() first.");i?(this._projectConfig||(this._projectConfig={}),this._projectConfig[e]=n):this._config[e]=n}getApiConfig(){return{apiUrl:this.get("apiUrl"),oauthUrl:this.get("oauthUrl","https://auth.sinch.com/oauth2/token"),projectId:this.get("projectId"),credentials:this._credentials}}async initProject(e,n="node",i={},s=null){let r={name:e,runtime:n,description:`Sinch Functions project: ${e}`,created:new Date().toISOString()};return i&&Object.keys(i).length>0&&(r.variables=i),s&&(r.applicationKey=s),this._projectConfig=r,await this.saveProjectConfig(),r}isInProject(){return this._projectConfig!==null}getProjectConfig(){return this._projectConfig}_getDefaultConfig(){return{apiUrl:"https://functions.api.sinch.com",oauthUrl:"https://auth.sinch.com/oauth2/token",projectId:"default-project",created:new Date().toISOString()}}async storeCredentials(e){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.store(e)}async getCredentials(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.retrieve()}async clearCredentials(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.clear()}async hasCredentials(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.hasCredentials()}getPublicCredentialInfo(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return this._credentials.getPublicInfo()}async createSinchClient(e=null){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return!e&&this.isInProject()&&(e=this._projectConfig?.applicationKey||null),await this._credentials.createSinchClient(e)}async getApplicationCredentials(e=null){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return!e&&this.isInProject()&&(e=this._projectConfig?.applicationKey||null),await this._credentials.getApplicationCredentials(e)}async storeApplicationSecret(e,n){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.storeApplicationSecret(e,n)}getTunnelPreference(){return this._projectConfig&&this._projectConfig.tunnel?.preference||null}async setTunnelPreference(e){if(!this._projectConfig)throw new Error("Not in a project directory");this._projectConfig.tunnel||(this._projectConfig.tunnel={}),this._projectConfig.tunnel.preference=e,this._projectConfig.tunnel.lastUpdated=new Date().toISOString(),await this.saveProjectConfig()}getTunnelSubdomain(){return this._projectConfig&&this._projectConfig.tunnel?.subdomain||null}async setTunnelSubdomain(e){if(!this._projectConfig)throw new Error("Not in a project directory");this._projectConfig.tunnel||(this._projectConfig.tunnel={}),this._projectConfig.tunnel.subdomain=e,this._projectConfig.tunnel.lastUpdated=new Date().toISOString(),await this.saveProjectConfig()}getTunnelUrl(){return this._projectConfig&&this._projectConfig.tunnel?.lastUrl||null}async setTunnelUrl(e){if(!this._projectConfig)throw new Error("Not in a project directory");this._projectConfig.tunnel||(this._projectConfig.tunnel={}),this._projectConfig.tunnel.lastUrl=e,this._projectConfig.tunnel.lastUpdated=new Date().toISOString(),await this.saveProjectConfig()}},p=new Ge});var Y,ce,it,Ft,st,t,B=he(()=>{"use strict";Y=m(require("chalk")),ce=m(require("fs")),it=m(require("path")),Ft=m(require("os")),st=class{verbose;logFile;constructor(e={}){this.verbose=e.verbose||process.env.VERBOSE==="true";let n="cli";try{let i=it.join(process.cwd(),"sinch.json");ce.existsSync(i)&&(n=JSON.parse(ce.readFileSync(i,"utf8")).name||"cli")}catch{}this.logFile=it.join(Ft.tmpdir(),`sinch-${n}.log`);try{ce.writeFileSync(this.logFile,`=== Sinch CLI Debug Log - ${new Date().toISOString()} ===
|
|
6
|
-
`,{flag:"w"})}catch{}}writeToFile(e,n,...i){try{let
|
|
7
|
-
`;ce.appendFileSync(this.logFile,
|
|
2
|
+
"use strict";var Xn=Object.create;var Ve=Object.defineProperty;var eo=Object.getOwnPropertyDescriptor;var to=Object.getOwnPropertyNames;var no=Object.getPrototypeOf,oo=Object.prototype.hasOwnProperty;var he=(o,e)=>()=>(o&&(e=o(o=0)),e);var U=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Je=(o,e)=>{for(var n in e)Ve(o,n,{get:e[n],enumerable:!0})},At=(o,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of to(e))!oo.call(o,s)&&s!==n&&Ve(o,s,{get:()=>e[s],enumerable:!(i=eo(e,s))||i.enumerable});return o};var h=(o,e,n)=>(n=o!=null?Xn(no(o)):{},At(e||!o||!o.__esModule?Ve(n,"default",{value:o,enumerable:!0}):n,o)),F=o=>At(Ve({},"__esModule",{value:!0}),o);var Ze=U((Pi,io)=>{io.exports={name:"@sinch/cli",version:"0.1.22-beta.0",description:"Official Sinch CLI - Manage all Sinch products from your terminal",main:"dist/index.js",bin:{sinch:"bin/sinch"},scripts:{start:"tsx src/index.ts",dev:"tsx watch src/index.ts",build:"tsc && node scripts/post-build.js","build:prod":"tsup src/index.ts --format cjs --dts --clean --minify",typecheck:"tsc --noEmit",test:"jest","test:e2e":"jest --config tests/e2e/jest.config.js","test:e2e:staging":"jest --config tests/e2e/jest.config.js --env=staging",prepublishOnly:"npm run build:prod"},keywords:[],author:"Sinch <support@sinch.com> (https://www.sinch.com)",license:"MIT",private:!1,publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},homepage:"https://www.sinch.com/products/apis/voice/",files:["dist/","bin/","README.md","LICENSE"],dependencies:{"@sinch/sdk-core":"^1.2.1","adm-zip":"^0.5.10",axios:"^1.7.9",blessed:"^0.1.81",chalk:"^4.1.2",chokidar:"^3.6.0","cli-spinners":"^2.9.2","cli-table3":"^0.6.3",clipboardy:"^2.3.0",commander:"^12.1.0",eventsource:"^4.0.0","form-data":"^4.0.0","fs-extra":"^11.1.1",inquirer:"8.2.6",keytar:"^7.9.0",ora:"^4.1.1"},devDependencies:{"@types/adm-zip":"^0.5.7","@types/blessed":"^0.1.25","@types/fs-extra":"^11.0.4","@types/inquirer":"^9.0.9","@types/keytar":"^4.4.0","@types/node":"^24.3.0",execa:"^5.1.1",jest:"^29.7.0",nodemon:"^3.0.1",tsup:"^8.5.0",tsx:"^4.20.4",typescript:"^5.9.2"},engines:{node:">=20.0.0",npm:">=9.0.0"}}});var Ie={};Je(Ie,{SinchAPI:()=>I});var Me,tt,Ee,I,x=he(()=>{"use strict";Me=h(require("axios")),tt=h(require("form-data")),Ee=h(require("chalk")),I=class{baseUrl;oauthUrl;projectId;timeout;credentials;client;constructor(e={}){this.baseUrl=e.apiUrl||"https://functions.api.sinch.com/",this.oauthUrl=e.oauthUrl||"https://auth.sinch.com/oauth2/token",this.projectId=e.projectId||"",this.timeout=6e4,this.credentials=e.credentials||null,this.client=Me.default.create({baseURL:this.baseUrl,timeout:this.timeout,headers:{"User-Agent":"sinch-functions-cli/1.0.0"}}),this.client.interceptors.request.use(async n=>{if(this.credentials){let i=await this.getValidToken();i&&(n.headers.Authorization=`${i.token_type} ${i.access_token}`)}return process.env.DEBUG_HTTP&&console.log(Ee.default.gray(`\u2192 ${n.method?.toUpperCase()} ${n.url}`)),n},n=>Promise.reject(n)),this.client.interceptors.response.use(n=>(process.env.DEBUG_HTTP&&console.log(Ee.default.gray(`\u2190 ${n.status} ${n.config.url}`)),n),async n=>{if(process.env.DEBUG_HTTP&&console.log(Ee.default.red(`\u2190 ${n.response?.status||"ERROR"} ${n.config?.url}`)),n.response?.status===401&&this.credentials&&n.config){let i=n.config;if(!i._retry){i._retry=!0;try{let s=await this.getValidToken();if(s)return i.headers.Authorization=`${s.token_type} ${s.access_token}`,this.client.request(i)}catch{console.error(Ee.default.yellow("Token refresh failed during retry"))}}}return Promise.reject(n)})}async listAllTemplates(e=null){try{let n=e?{category:e}:{};return(await this.client.get(`/v1/projects/${this.projectId}/templates`,{params:n})).data}catch(n){throw this._handleError(n,"Failed to list templates")}}async listRuntimeTemplates(e,n=null){try{let i=n?{category:n}:{};return(await this.client.get(`/v1/projects/${this.projectId}/templates/${e}`,{params:i})).data}catch(i){throw this._handleError(i,`Failed to list ${e} templates`)}}async getTemplateDetails(e,n){try{return(await this.client.get(`/v1/projects/${this.projectId}/templates/${e}/${n}`)).data}catch(i){throw this._handleError(i,`Failed to get template details for ${e}/${n}`)}}async downloadTemplate(e,n){try{let i=await this.client.get(`/v1/projects/${this.projectId}/templates/${e}/${n}/download`,{responseType:"arraybuffer"});return Buffer.from(i.data)}catch(i){throw this._handleError(i,`Failed to download template ${e}/${n}`)}}async listFunctions(){try{return(await this.client.get(`/v1/projects/${this.projectId}/functions`)).data}catch(e){throw this._handleError(e,"Failed to list functions")}}async getFunction(e){try{return(await this.client.get(`/v1/projects/${this.projectId}/functions/${e}`)).data}catch(n){throw this._handleError(n,`Failed to get function ${e}`)}}async deployFunction(e,n,i,s,a="public"){try{let r=new tt.default;return r.append("name",e),r.append("runtime",n),r.append("code",i,{filename:"function.zip"}),r.append("accessLevel",a),s&&r.append("configuration",JSON.stringify(s)),(await this.client.post(`/v1/projects/${this.projectId}/functions`,r,{headers:{...r.getHeaders()},maxContentLength:1/0,maxBodyLength:1/0})).data}catch(r){throw this._handleError(r,"Failed to deploy function")}}async updateFunction(e,n,i){try{let s=new tt.default;return s.append("code",n,{filename:"function.zip"}),i&&s.append("configuration",JSON.stringify(i)),(await this.client.put(`/v1/projects/${this.projectId}/functions/${e}`,s,{headers:{...s.getHeaders()},maxContentLength:1/0,maxBodyLength:1/0})).data}catch(s){throw this._handleError(s,`Failed to update function ${e}`)}}async deleteFunction(e){try{await this.client.delete(`/v1/projects/${this.projectId}/functions/${e}`)}catch(n){throw this._handleError(n,`Failed to delete function ${e}`)}}async downloadFunction(e){try{let n=await this.client.get(`/v1/projects/${this.projectId}/functions/${e}/download`,{responseType:"arraybuffer"});return Buffer.from(n.data)}catch(n){throw this._handleError(n,`Failed to download function ${e}`)}}async getFunctionLogs(e,n={}){try{return(await this.client.get(`/v1/projects/${this.projectId}/functions/${e}/logs`,{params:n})).data}catch(i){throw this._handleError(i,`Failed to get logs for function ${e}`)}}async getFunctionStatus(e){try{return(await this.client.get(`/v1/projects/${this.projectId}/functions/${e}/deployment/status`)).data}catch(n){throw this._handleError(n,`Failed to get status for function ${e}`)}}async generateDocumentationFromCode(e,n="node",i="function"){try{return(await this.client.post(`/v1/projects/${this.projectId}/test/documentation`,{Code:e,Runtime:n,Name:i})).data}catch(s){throw this._handleError(s,"Failed to generate documentation from code")}}async generateDocumentationForFunction(e,n){try{let i=n?{MarkdownOverride:n}:{};return(await this.client.post(`/v1/projects/${this.projectId}/functions/${e}/documentation`,i)).data}catch(i){throw this._handleError(i,`Failed to generate documentation for function ${e}`)}}async getDocumentationForFunction(e){try{return(await this.client.get(`/v1/projects/${this.projectId}/functions/${e}/documentation`)).data}catch(n){throw this._handleError(n,`Failed to get documentation for function ${e}`)}}async streamDeployment(e,n,i){let s=c=>c.status?"status":c.progress?"progress":c.completed?"completed":c.failed||c.error?"failed":c.connected?"connected":"message",a=new URL(`v1/projects/${this.projectId}/functions/${e}/deployment/stream`,this.baseUrl).href,r={Accept:"text/event-stream","Cache-Control":"no-cache"};if(this.credentials)try{let c=await this.credentials.retrieve();if(c&&c.keyId&&c.keySecret){let l=Buffer.from(`${c.keyId}:${c.keySecret}`).toString("base64");r.Authorization=`Basic ${l}`}}catch(c){console.error("Failed to add authentication:",c)}let u=null;try{u=new AbortController;let c=await fetch(a,{method:"GET",headers:r,signal:u.signal});if(!c.ok)throw new Error(`SSE connection failed: ${c.status} ${c.statusText}`);if(!c.body)throw new Error("Response body is null");let l=c.body.getReader(),p=new TextDecoder,m="";return(async()=>{let w="";try{for(;;){let{done:A,value:J}=await l.read();if(A)break;let W=p.decode(J,{stream:!0});m+=W;let P=m.split(`
|
|
3
|
+
`);m=P.pop()||"";for(let b of P){if(b.startsWith("event:")){w=b.substring(6).trim();continue}if(b.startsWith("data:")){let S=b.substring(5).trim();if(S)try{let y=JSON.parse(S),v=w||s(y);n({type:v,data:y}),w=""}catch{n({type:w||"message",data:S}),w=""}}b===""&&(w="")}}}catch(A){A.name!=="AbortError"&&i&&i(A)}})(),()=>{u&&u.abort()}}catch(c){throw console.error("Failed to create SSE stream:",c),i&&i(c),c}}async checkHealth(){try{return(await this.client.get("/health")).data}catch(e){throw this._handleError(e,"Health check failed")}}async getValidToken(){if(!this.credentials)return null;try{let e=await this.credentials.getOAuthToken();if(e)return{access_token:e,token_type:"Bearer",expires_in:3600};let n=await this.credentials.getBasicAuthToken();return n?{access_token:n,token_type:"Basic",expires_in:3600}:null}catch(e){return console.error(Ee.default.yellow("Failed to get authentication token:",e.message)),null}}async authenticateOAuth(e,n){try{let i=this.oauthUrl,s=new URLSearchParams;s.append("grant_type","client_credentials");let r=(await Me.default.post(i,s,{headers:{"Content-Type":"application/x-www-form-urlencoded",Authorization:"Basic "+Buffer.from(`${e}:${n}`).toString("base64")},timeout:this.timeout})).data;return this.credentials&&await this.credentials.storeOAuthToken(r),r}catch(i){throw this._handleError(i,"OAuth authentication failed")}}_handleError(e,n){if(Me.default.isAxiosError(e)){let i=e;if(i.response){let s=i.response.status,a=i.response.data,r=a?.message||a?.error||i.message;throw s===401?new Error('Authentication required. Please run "sinch auth login" first.'):s===403?new Error(`Permission denied: ${r}`):s===404?new Error(`Resource not found: ${r}`):s>=500?new Error(`Server error: ${r}`):new Error(`${n}: ${r}`)}else throw i.request?(console.error("DEBUG: Axios error details:",{code:i.code,message:i.message,url:i.config?.url,baseURL:i.config?.baseURL,method:i.config?.method}),i.code==="ECONNREFUSED"?new Error(`Cannot connect to API at ${this.baseUrl}. Is the server running?`):i.code==="ETIMEDOUT"?new Error(`Request timeout after ${this.timeout}ms`):new Error(`${n}: No response from server (${i.code||"unknown error"})`)):new Error(`${n}: ${i.message}`)}else throw new Error(`${n}: ${e.message||e}`)}}});function He(){if(!nt)try{nt=require("keytar")}catch{return null}return nt}var Tt,ne,nt,Fe,K,We,jt=he(()=>{"use strict";Tt=h(require("os")),ne=h(require("chalk")),nt=null;Fe="sinch-functions-cli",K=Tt.userInfo().username,We=class{config;keychainAvailable=null;constructor(e){this.config=e}async isKeychainAvailable(){if(this.keychainAvailable!==null)return this.keychainAvailable;if(this.config.get("keySecretPlaintext"))return this.keychainAvailable=!1,!1;try{let e=He();if(!e)return this.keychainAvailable=!1,!1;let n=`${K}-test-${Date.now()}`;return await e.setPassword(Fe,n,"test"),await e.deletePassword(Fe,n),this.keychainAvailable=!0,!0}catch{return this.keychainAvailable=!1,!1}}async setPassword(e,n){if(!await this.isKeychainAvailable())return!1;let s=He();return s?(await s.setPassword(Fe,e,n),!0):!1}async getPassword(e){if(!await this.isKeychainAvailable())return null;let i=He();return i?await i.getPassword(Fe,e):null}async deletePassword(e){if(!await this.isKeychainAvailable())return!1;try{let i=He();return i?(await i.deletePassword(Fe,e),!0):!1}catch{return!0}}async store(e){let{projectId:n,keyId:i,keySecret:s,applicationKey:a,applicationSecret:r}=e,u=await this.setPassword(`${K}-keySecret`,s),c=await this.setPassword(a,r);u&&c?(this.config.set("keySecretPlaintext",null),this.config.set("applicationSecretPlaintext",null)):(console.log(ne.default.yellow(`
|
|
4
|
+
\u26A0\uFE0F OS keychain not available (Docker/CI environment detected)`)),console.log(ne.default.yellow("\u26A0\uFE0F Storing secrets in plaintext config file")),console.log(ne.default.gray("Location: ~/.sinch/config.json")),console.log(ne.default.gray(`
|
|
5
|
+
For better security, export as environment variables instead:`)),console.log(ne.default.cyan(' export SINCH_KEY_SECRET="'+s+'"')),console.log(ne.default.cyan(' export SINCH_APPLICATION_SECRET="'+r+'"')),this.config.set("keySecretPlaintext",s),this.config.set("applicationSecretPlaintext",r)),this.config.set("projectId",n),this.config.set("keyId",i),this.config.set("defaultApplicationKey",a),this.config.set("credentialsStored",!0),await this.config.save()}async storeOAuthToken(e){let{access_token:n,refresh_token:i,expires_in:s,token_type:a}=e,r=new Date(Date.now()+s*1e3).toISOString(),u=await this.setPassword(`${K}-oauth-access`,n),c=!0;i&&(c=await this.setPassword(`${K}-oauth-refresh`,i)),this.config.set("oauthTokenType",a),this.config.set("oauthExpiresAt",r),this.config.set("oauthStored",u&&c),await this.config.save()}async reAuthenticateOAuth(){try{let e=await this.retrieve();if(!e)return null;let{SinchAPI:n}=(x(),F(Ie)),s=await new n({apiUrl:this.config.get("apiUrl")||"https://api.functions.dev.sinchvoice.org",projectId:e.projectId,credentials:null}).authenticateOAuth(e.keyId,e.keySecret);return await this.storeOAuthToken(s),s.access_token}catch{return null}}async getOAuthToken(){if(!this.config.get("oauthStored"))return await this.reAuthenticateOAuth();let n=this.config.get("oauthExpiresAt");if(n&&new Date(n)<new Date){console.log(ne.default.gray("Token expired, re-authenticating..."));let i=await this.reAuthenticateOAuth();return i?console.log(ne.default.green("\u2713 Token renewed successfully")):console.warn(ne.default.yellow("Failed to renew OAuth token. Please login again.")),i}return await this.getPassword(`${K}-oauth-access`)}async storeApplicationSecret(e,n){await this.setPassword(e,n),this.config.get("defaultApplicationKey")||(this.config.set("defaultApplicationKey",e),await this.config.save())}async retrieve(){let e=process.env.SINCH_KEY_ID,n=process.env.SINCH_KEY_SECRET,i=process.env.SINCH_APPLICATION_KEY,s=process.env.SINCH_APPLICATION_SECRET;if(e&&n&&i&&s)return{projectId:process.env.SINCH_PROJECT_ID||this.config.get("projectId")||"",keyId:e,keySecret:n,applicationKey:i,applicationSecret:s};if(!this.config.get("credentialsStored"))return null;let r=this.config.get("projectId"),u=this.config.get("keyId"),c=this.config.get("defaultApplicationKey"),l=await this.getPassword(`${K}-keySecret`),p=c?await this.getPassword(c):null;return(!l||!p)&&(l=l||n||null,p=p||s||null),(!l||!p)&&(l=l||this.config.get("keySecretPlaintext"),p=p||this.config.get("applicationSecretPlaintext")),!l||!p?null:{projectId:r,keyId:u,keySecret:l,applicationKey:c,applicationSecret:p}}async getApplicationCredentials(e=null){if(e||(e=this.config.get("defaultApplicationKey")),!e)return null;let n=await this.getPassword(e);return n||(n=process.env.SINCH_APPLICATION_SECRET||null),n||(n=this.config.get("applicationSecretPlaintext")),n?{applicationKey:e,applicationSecret:n}:null}async clear(){let e=this.config.get("defaultApplicationKey");await this.deletePassword(`${K}-keySecret`),await this.deletePassword(`${K}-oauth-access`),await this.deletePassword(`${K}-oauth-refresh`),e&&await this.deletePassword(e),this.config.set("projectId",null),this.config.set("keyId",null),this.config.set("defaultApplicationKey",null),this.config.set("credentialsStored",!1),this.config.set("oauthStored",!1),this.config.set("oauthTokenType",null),this.config.set("oauthExpiresAt",null),this.config.set("keySecretPlaintext",null),this.config.set("applicationSecretPlaintext",null),await this.config.save()}async hasCredentials(){if(!!(process.env.SINCH_KEY_ID&&process.env.SINCH_KEY_SECRET&&process.env.SINCH_APPLICATION_KEY&&process.env.SINCH_APPLICATION_SECRET))return!0;if(!this.config.get("credentialsStored"))return!1;if(this.config.get("keySecretPlaintext"))return!0;let i=await this.getPassword(`${K}-keySecret`),s=this.config.get("defaultApplicationKey"),a=s?await this.getPassword(s):null;return!!(i&&a)}async hasOAuthToken(){return this.config.get("oauthStored")?!!await this.getPassword(`${K}-oauth-access`):!1}getPublicInfo(){return{projectId:this.config.get("projectId"),keyId:this.config.get("keyId"),applicationKey:this.config.get("defaultApplicationKey"),hasCredentials:this.config.get("credentialsStored",!1),hasOAuth:this.config.get("oauthStored",!1),oauthExpiresAt:this.config.get("oauthExpiresAt")}}async createSinchClient(e=null){let n=await this.getApplicationCredentials(e);if(!n)throw new Error('No credentials found. Please run "sinch auth login" first.');let{SinchClient:i}=require("@sinch/sdk-core");return new i({applicationKey:n.applicationKey,applicationSecret:n.applicationSecret,projectId:this.config.get("projectId")})}async storeBasicAuthToken(e){await this.setPassword(`${K}-basic-auth`,e)&&(this.config.set("basicAuthStored",!0),await this.config.save())}async getBasicAuthToken(){return this.config.get("basicAuthStored")?await this.getPassword(`${K}-basic-auth`):null}async clearBasicAuthToken(){await this.deletePassword(`${K}-basic-auth`),this.config.set("basicAuthStored",!1),await this.config.save()}}});var we={};Je(we,{Config:()=>Ge,config:()=>f});var G,Oe,Dt,ot,Ge,f,j=he(()=>{"use strict";G=h(require("fs-extra")),Oe=h(require("path")),Dt=h(require("os")),ot=h(require("chalk"));jt();Ge=class{configDir;configFile;projectConfigFile;_config=null;_projectConfig=null;_credentials=null;constructor(){this.configDir=Oe.join(Dt.homedir(),".sinch"),this.configFile=Oe.join(this.configDir,"config.json"),this.projectConfigFile=Oe.join(process.cwd(),"sinch.json")}async load(){try{await G.ensureDir(this.configDir),await G.pathExists(this.configFile)?this._config=await G.readJson(this.configFile):(this._config=this._getDefaultConfig(),await this.save())}catch(e){console.warn(ot.default.yellow(`Warning: Could not load config: ${e.message}`)),this._config=this._getDefaultConfig()}this._credentials=new We(this);try{await G.pathExists(this.projectConfigFile)&&(this._projectConfig=await G.readJson(this.projectConfigFile))}catch(e){console.warn(ot.default.yellow(`Warning: Could not load project config: ${e.message}`))}}async save(){try{await G.ensureDir(this.configDir),await G.writeJson(this.configFile,this._config,{spaces:2})}catch(e){throw new Error(`Could not save config: ${e.message}`)}}async saveProjectConfig(){try{if(this._projectConfig){let e=Oe.join(process.cwd(),"sinch.json");await G.writeJson(e,this._projectConfig,{spaces:2})}}catch(e){throw new Error(`Could not save project config: ${e.message}`)}}get(e,n=null){if(!this._config)throw new Error("Config not loaded. Call load() first.");return this._projectConfig&&this._projectConfig[e]!==void 0?this._projectConfig[e]:this._config[e]!==void 0?this._config[e]:n}set(e,n,i=!1){if(!this._config)throw new Error("Config not loaded. Call load() first.");i?(this._projectConfig||(this._projectConfig={}),this._projectConfig[e]=n):this._config[e]=n}getApiConfig(){return{apiUrl:this.get("apiUrl"),oauthUrl:this.get("oauthUrl","https://auth.sinch.com/oauth2/token"),projectId:this.get("projectId"),credentials:this._credentials}}async initProject(e,n="node",i={},s=null){let a={name:e,runtime:n,description:`Sinch Functions project: ${e}`,created:new Date().toISOString()};return i&&Object.keys(i).length>0&&(a.variables=i),s&&(a.applicationKey=s),this._projectConfig=a,await this.saveProjectConfig(),a}isInProject(){return this._projectConfig!==null}getProjectConfig(){return this._projectConfig}_getDefaultConfig(){return{apiUrl:"https://functions.api.sinch.com",oauthUrl:"https://auth.sinch.com/oauth2/token",projectId:"default-project",created:new Date().toISOString()}}async storeCredentials(e){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.store(e)}async getCredentials(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.retrieve()}async clearCredentials(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.clear()}async hasCredentials(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.hasCredentials()}getPublicCredentialInfo(){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return this._credentials.getPublicInfo()}async createSinchClient(e=null){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return!e&&this.isInProject()&&(e=this._projectConfig?.applicationKey||null),await this._credentials.createSinchClient(e)}async getApplicationCredentials(e=null){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return!e&&this.isInProject()&&(e=this._projectConfig?.applicationKey||null),await this._credentials.getApplicationCredentials(e)}async storeApplicationSecret(e,n){if(!this._credentials)throw new Error("Config not loaded. Call load() first.");return await this._credentials.storeApplicationSecret(e,n)}getTunnelPreference(){return this._projectConfig&&this._projectConfig.tunnel?.preference||null}async setTunnelPreference(e){if(!this._projectConfig)throw new Error("Not in a project directory");this._projectConfig.tunnel||(this._projectConfig.tunnel={}),this._projectConfig.tunnel.preference=e,this._projectConfig.tunnel.lastUpdated=new Date().toISOString(),await this.saveProjectConfig()}getTunnelSubdomain(){return this._projectConfig&&this._projectConfig.tunnel?.subdomain||null}async setTunnelSubdomain(e){if(!this._projectConfig)throw new Error("Not in a project directory");this._projectConfig.tunnel||(this._projectConfig.tunnel={}),this._projectConfig.tunnel.subdomain=e,this._projectConfig.tunnel.lastUpdated=new Date().toISOString(),await this.saveProjectConfig()}getTunnelUrl(){return this._projectConfig&&this._projectConfig.tunnel?.lastUrl||null}async setTunnelUrl(e){if(!this._projectConfig)throw new Error("Not in a project directory");this._projectConfig.tunnel||(this._projectConfig.tunnel={}),this._projectConfig.tunnel.lastUrl=e,this._projectConfig.tunnel.lastUpdated=new Date().toISOString(),await this.saveProjectConfig()}},f=new Ge});var Y,ce,it,Ft,st,t,B=he(()=>{"use strict";Y=h(require("chalk")),ce=h(require("fs")),it=h(require("path")),Ft=h(require("os")),st=class{verbose;logFile;constructor(e={}){this.verbose=e.verbose||process.env.VERBOSE==="true";let n="cli";try{let i=it.join(process.cwd(),"sinch.json");ce.existsSync(i)&&(n=JSON.parse(ce.readFileSync(i,"utf8")).name||"cli")}catch{}this.logFile=it.join(Ft.tmpdir(),`sinch-${n}.log`);try{ce.writeFileSync(this.logFile,`=== Sinch CLI Debug Log - ${new Date().toISOString()} ===
|
|
6
|
+
`,{flag:"w"})}catch{}}writeToFile(e,n,...i){try{let a=`[${new Date().toISOString()}] ${e}: ${n} ${i.length>0?JSON.stringify(i):""}
|
|
7
|
+
`;ce.appendFileSync(this.logFile,a)}catch{}}info(e,...n){console.log(Y.default.blue("\u2139"),e,...n),this.writeToFile("INFO",e,...n)}success(e,...n){console.log(Y.default.green("\u2705"),e,...n),this.writeToFile("SUCCESS",e,...n)}warn(e,...n){console.log(Y.default.yellow("\u26A0\uFE0F "),e,...n),this.writeToFile("WARN",e,...n)}error(e,...n){console.log(Y.default.red("\u274C"),e,...n),this.writeToFile("ERROR",e,...n)}debug(e,...n){this.writeToFile("DEBUG",e,...n),(this.verbose||process.env.DEBUG)&&console.log(Y.default.gray("\u{1F41B}"),Y.default.gray(e),...n)}log(e,...n){console.log(e,...n)}title(e){console.log(Y.default.blue.bold(`
|
|
8
8
|
\u{1F3AF} ${e}`))}subtitle(e){console.log(Y.default.gray(`
|
|
9
|
-
${e}`))}list(e,n={}){let{indent:i=" ",bullet:s="\u2022"}=n;e.forEach(
|
|
9
|
+
${e}`))}list(e,n={}){let{indent:i=" ",bullet:s="\u2022"}=n;e.forEach(a=>{console.log(`${i}${Y.default.gray(s)} ${a}`)})}calculateColumnWidths(e,n){let i=e.map(s=>s.length);return n.forEach(s=>{s.forEach((a,r)=>{i[r]=Math.max(i[r]??0,String(a).length)})}),i}table(e,n){let i=this.calculateColumnWidths(e,n),s=e.map((a,r)=>a.padEnd(i[r]??0)).join(" ");console.log(Y.default.bold(s)),console.log(Y.default.gray("-".repeat(s.length))),n.forEach(a=>{let r=a.map((u,c)=>String(u).padEnd(i[c]??0)).join(" ");console.log(r)})}newline(){console.log()}},t=new st});var Ae={};Je(Ae,{Spinner:()=>Ye,spinner:()=>d});var Ot,_t,Ye,d,O=he(()=>{"use strict";Ot=h(require("ora")),_t=h(require("cli-spinners")),Ye=class{spinner=null;spinnerType=_t.default.dots;start(e){return this.spinner=(0,Ot.default)({text:e,spinner:this.spinnerType}).start(),this}succeed(e){return this.spinner&&(this.spinner.succeed(e),this.spinner=null),this}fail(e){return this.spinner&&(this.spinner.fail(e),this.spinner=null),this}info(e){return this.spinner&&(this.spinner.info(e),this.spinner=null),this}warn(e){return this.spinner&&(this.spinner.warn(e),this.spinner=null),this}stop(){return this.spinner&&(this.spinner.stop(),this.spinner=null),this}update(e){return this.spinner&&(this.spinner.text=e),this}get isSpinning(){return this.spinner?.isSpinning??!1}get text(){return this.spinner?.text??""}set text(e){this.spinner&&(this.spinner.text=e)}},d=new Ye});var Kt=U((Li,Ut)=>{"use strict";var N=h(require("fs-extra")),le=h(require("path")),q=h(require("chalk")),Ce=h(require("inquirer")),Lt=require("commander");j();B();O();x();var Re=require("child_process"),xt=h(require("adm-zip")),rt=h(require("keytar")),Nt=new Lt.Command("init");Nt.description("Initialize a new Sinch Functions project").argument("[template]","Template to use (simple-ivr, customer-lookup, smart-routing)").option("--name <name>","Function name (default: template name)").option("--runtime <runtime>","Runtime to use (node, csharp)").option("--skip-install","Skip npm install for Node.js projects").option("--non-interactive","Use default values without prompting").action(async(o,e)=>{try{await f.load();let n=process.cwd(),i=new I(f.getApiConfig()),s=e.runtime;s||(e.nonInteractive?s="node":s=(await Ce.default.prompt([{type:"list",name:"runtime",message:"Choose a runtime:",choices:[{name:"Node.js",value:"node"},{name:"C# (.NET)",value:"csharp"}],default:"node"}])).runtime),d.start(`Fetching available templates for ${s}...`);let a=await i.listRuntimeTemplates(s);if(d.stop(),!a.templates||a.templates.length===0)throw new Error(`No templates available for runtime '${s}'`);let r=o;if(!r)if(e.nonInteractive){let b=a.templates.filter(S=>S.name&&S.name.trim());if(b.length>0)r=b[0]?.name||"",t.info(`Using default template: ${r} (non-interactive mode)`);else throw new Error("No templates available")}else{let b=a.templates.filter(y=>y.name&&y.name.trim()).map(y=>({name:`${y.name} - ${(y.description||"No description available").substring(0,100)}`,value:y.name}));r=(await Ce.default.prompt([{type:"list",name:"selectedTemplate",message:"Choose a template:",choices:b,pageSize:10}])).selectedTemplate}let u=e.name;u||(e.nonInteractive?u=r:u=(await Ce.default.prompt([{type:"input",name:"name",message:"Function name:",default:r,validate:S=>!S||S.trim().length===0?"Function name is required":/^[a-z][a-z0-9-]*$/.test(S.trim())?!0:"Function name must be lowercase, start with a letter, and contain only letters, numbers, and hyphens"}])).name.trim());let c=le.default.join(n,u);if(await N.default.pathExists(c)){let b=!1;if(e.nonInteractive?(b=!0,t.info(`Directory '${u}' already exists. Overwriting (non-interactive mode)...`)):b=(await Ce.default.prompt([{type:"confirm",name:"overwrite",message:`Directory '${u}' already exists. Overwrite?`,default:!1}])).overwrite,!b){t.info("Initialization cancelled");return}await N.default.remove(c)}await N.default.ensureDir(c);let l=a.templates.find(b=>b.name===r);if(!l){let b=a.templates.map(S=>S.name).join(", ");throw new Error(`Template '${r}' not found. Available templates: ${b}`)}let p=["node","csharp"];if(!p.includes(s))throw new Error(`Runtime '${s}' not supported. Supported runtimes: ${p.join(", ")}`);d.start(`\u{1F680} Initializing ${u} with ${r} template (${s})...`);let m=await i.downloadTemplate(s,r);new xt.default(m).extractAllTo(c,!0),d.succeed("\u{1F4E6} Template extracted");let w={},A=[],J=le.default.join(c,"template.json");if(await N.default.pathExists(J)){let b=await N.default.readJson(J);if(b.variables&&Object.keys(b.variables).length>0)if(e.nonInteractive){t.info("\u{1F4DD} Using default values for template variables (non-interactive mode):");for(let[y,v]of Object.entries(b.variables)){let R;typeof v=="string"?R=v:R=v.default||"",w[y]=R,t.info(` ${y}: ${R}`)}}else{t.newline(),t.info("\u{1F4DD} Configure template variables:");for(let[y,v]of Object.entries(b.variables)){let R;typeof v=="string"?R={type:"input",name:y,message:`${y.replace(/_/g," ").toLowerCase()}:`,default:v}:(R={type:v.type==="number"?"number":"input",name:y,message:`${v.description||y.replace(/_/g," ").toLowerCase()}:`,default:v.default},v.type==="number"&&(R.validate=ae=>v.min!==void 0&&ae<v.min?`Value must be at least ${v.min}`:v.max!==void 0&&ae>v.max?`Value must be at most ${v.max}`:!0));let ge=await Ce.default.prompt([R]);w[y]=ge[y]}}let S="sinch-functions-cli";if(b.secrets&&Object.keys(b.secrets).length>0)if(A=Object.keys(b.secrets),e.nonInteractive){t.info("\u{1F4DD} Template secrets detected (non-interactive mode):");for(let y of Object.keys(b.secrets))t.info(` ${y}: [will need to be set manually]`)}else{t.newline(),t.info("\u{1F510} Configure template secrets (stored securely in OS keychain):");for(let[y,v]of Object.entries(b.secrets)){let R=v.description||y.replace(/_/g," ").toLowerCase(),ge=v.required!==!1,ae={type:"password",name:y,message:`${R}:`,validate:L=>ge&&(!L||L.trim()==="")?"This secret is required":!0},De=(await Ce.default.prompt([ae]))[y];if(De&&De.trim()!=="")try{let L=`${u}-${y}`;await rt.default.setPassword(S,L,De),t.info(` \u2705 ${y} stored securely in keychain`)}catch(L){t.warn(` \u26A0\uFE0F Could not store ${y} in keychain: ${L.message}`),t.info(` \u{1F4A1} You can add it later with: sinch secrets add ${y} <value>`)}}}await N.default.remove(J)}d.start("\u{1F527} Finalizing function configuration...");let W=le.default.join(c,"sinch.json"),P;if(await N.default.pathExists(W)){if(P=await N.default.readJson(W),P.name=u,P.description=`Sinch Functions function: ${u}`,P.functionId=null,delete P.projectId,delete P.voiceAppId,P.variables)for(let[b,S]of Object.entries(P.variables))typeof S=="string"&&(S==="your-project-id"||S==="{{PROJECT_ID}}"?P.variables[b]=f.get("projectId"):(S==="your-application-key"||S==="{{SINCH_APPLICATION_KEY}}")&&(P.variables[b]=f.get("defaultApplicationKey")));P.created=new Date().toISOString(),P.variables={},P.secrets&&delete P.secrets}else P={name:u,functionId:null,runtime:s,description:`Sinch Functions function: ${u}`,created:new Date().toISOString(),variables:{},custom:{}};if(await N.default.writeJson(W,P,{spaces:2}),s==="node"){let b=le.default.join(c,"package.json");if(await N.default.pathExists(b)){let $=await N.default.readJson(b);$.name=u,$.description=P.description,await N.default.writeJson(b,$,{spaces:2})}let S=le.default.join(c,".env"),y=`# Sinch Functions Environment Variables
|
|
10
10
|
`;y+=`# Generated by sinch functions init
|
|
11
11
|
|
|
12
12
|
`,y+=`# Template Variables
|
|
13
|
-
`,Object.keys(w).forEach(
|
|
14
|
-
`});let v=
|
|
13
|
+
`,Object.keys(w).forEach($=>{y+=`${$}=${w[$]}
|
|
14
|
+
`});let v=f.get("projectId"),R=f.get("functionId"),ge=f.get("defaultApplicationKey"),ae=f.get("keyId");y+=`
|
|
15
15
|
# Sinch Configuration
|
|
16
16
|
`,y+=`PROJECT_ID=${v||""}
|
|
17
17
|
`,y+=`FUNCTION_ID=${R||""}
|
|
@@ -24,17 +24,17 @@ ${e}`))}list(e,n={}){let{indent:i=" ",bullet:s="\u2022"}=n;e.forEach(r=>{consol
|
|
|
24
24
|
`,y+=`VOICE_APPLICATION_SECRET=
|
|
25
25
|
`,A.length>0&&(y+=`
|
|
26
26
|
# Template Secrets (stored in OS keychain - use "sinch secrets add <KEY> <VALUE>")
|
|
27
|
-
`,A.forEach(
|
|
27
|
+
`,A.forEach($=>{y+=`${$}=
|
|
28
28
|
`})),y+=`
|
|
29
29
|
# Environment
|
|
30
30
|
`,y+=`NODE_ENV=development
|
|
31
31
|
`,y+=`PORT=3000
|
|
32
32
|
`,y+=`SINCH_TUNNEL=false
|
|
33
|
-
`,await N.default.writeFile(S,y),t.info(""),t.info("\u{1F510} Secrets Management for Node.js:");try{let
|
|
33
|
+
`,await N.default.writeFile(S,y),t.info(""),t.info("\u{1F510} Secrets Management for Node.js:");try{let $=await f.getCredentials();$&&$.keySecret?(t.info(" \u2705 Sinch credentials found in secure storage"),t.info(" \u2705 F5 debugging will automatically load secrets from OS keychain"),t.info(""),t.info(" \u{1F4A1} To add custom secrets, use:"),t.info(` ${q.default.cyan("sinch functions secrets add <KEY> <VALUE>")}`)):(t.info(" \u26A0\uFE0F No Sinch credentials found in secure storage"),t.info(""),t.info(" To set up authentication:"),t.info(` ${q.default.cyan("sinch auth login")}`),t.info(""),t.info(" To add custom secrets:"),t.info(` ${q.default.cyan("sinch functions secrets add <KEY> <VALUE>")}`))}catch{t.info(" \u2139\uFE0F Set up authentication with:"),t.info(` ${q.default.cyan("sinch auth login")}`)}t.info(""),t.info(" \u{1F4DD} Note: Secrets are stored securely in your OS keychain"),t.info(" \u{1F4DD} Note: F5 debugging requires keytar (npm install keytar)")}if(s==="csharp"){let b=le.default.join(c,"appsettings.json"),S={Logging:{LogLevel:{Default:"Information","Microsoft.AspNetCore":"Warning"}},AllowedHosts:"*"};Object.keys(w).forEach($=>{S[$]=w[$]});let y=f.get("projectId"),v=f.get("defaultApplicationKey"),R=f.get("keyId");S.PROJECT_ID=y||"",S.PROJECT_ID_API_KEY=R||"",S.PROJECT_ID_API_SECRET="",S.VOICE_APPLICATION_KEY=v||"",S.VOICE_APPLICATION_SECRET="",S.PROTECT_VOICE_CALLBACKS="deploy",A.forEach($=>{S[$]=""}),await N.default.writeJson(b,S,{spaces:2});let ge=le.default.join(c,"appsettings.Development.json"),ae={Logging:{LogLevel:{Default:"Debug","Microsoft.AspNetCore":"Information"}},SinchTunnel:!1};await N.default.writeJson(ge,ae,{spaces:2});try{let $=await f.getCredentials();await new Promise((L,z)=>{let Q=(0,Re.spawn)("dotnet",["user-secrets","init"],{cwd:c,shell:!0});Q.on("close",me=>me===0?L():z(new Error("Failed to init user-secrets"))),Q.on("error",z)}),$&&$.keySecret&&await new Promise((L,z)=>{let Q=(0,Re.spawn)("dotnet",["user-secrets","set","PROJECT_ID_API_SECRET",$.keySecret],{cwd:c,shell:!0});Q.on("close",me=>me===0?L():z(new Error("Failed to set API secret"))),Q.on("error",z)}),$&&$.applicationSecret&&await new Promise((L,z)=>{let Q=(0,Re.spawn)("dotnet",["user-secrets","set","VOICE_APPLICATION_SECRET",$.applicationSecret],{cwd:c,shell:!0});Q.on("close",me=>me===0?L():z(new Error("Failed to set app secret"))),Q.on("error",z)});let De="sinch-functions-cli";for(let L of A)try{let z=`${u}-${L}`,Q=await rt.default.getPassword(De,z);Q&&await new Promise((me,Et)=>{let It=(0,Re.spawn)("dotnet",["user-secrets","set",L,Q],{cwd:c,shell:!0});It.on("close",Zn=>Zn===0?me():Et(new Error(`Failed to set ${L}`))),It.on("error",Et)})}catch{}($&&($.keySecret||$.applicationSecret)||A.length>0)&&(t.info(""),t.info("\u{1F510} Secrets Management for C#:"),t.info(" \u2705 User secrets have been configured automatically"),t.info(" You can view them with: "+q.default.cyan("dotnet user-secrets list")),A.length>0&&t.info(" \u{1F4A1} Template secrets have been added to user-secrets"))}catch{t.info(""),t.info("\u{1F510} Secrets Management for C#:"),t.info(" For local development, use dotnet user-secrets:"),t.info(` ${q.default.cyan("dotnet user-secrets init")}`),t.info(` ${q.default.cyan('dotnet user-secrets set "PROJECT_ID_API_SECRET" "your-api-secret"')}`),t.info(` ${q.default.cyan('dotnet user-secrets set "VOICE_APPLICATION_SECRET" "your-app-secret"')}`)}}if(d.succeed("\u{1F680} Function initialized successfully"),t.newline(),t.title(`Function: ${q.default.cyan(u)}`),t.info(`Template: ${q.default.yellow(r)}`),t.info(`Runtime: ${q.default.blue(s)}`),t.info(`Location: ${q.default.gray(c)}`),s==="node"&&!e.skipInstall){t.newline(),d.start("Installing npm packages...");try{await new Promise((b,S)=>{let y=(0,Re.spawn)("npm",["install"],{cwd:c,stdio:"inherit",shell:!0});y.on("close",v=>{v===0?b():S(new Error(`npm install failed with code ${v}`))}),y.on("error",v=>{S(v)})}),d.succeed("\u{1F4E6} Dependencies installed successfully")}catch(b){d.fail("\u{1F4E6} Failed to install dependencies"),b.code==="ENOENT"?t.warn("npm not found. Please ensure Node.js is installed and in your PATH."):t.debug(`npm install error: ${b.message}`)}}t.newline(),t.info("\u{1F4CB} Next steps:"),t.info(` 1. \u{1F4C1} Navigate to function: ${q.default.cyan(`cd ${u}`)}`),s==="node"?t.info(" 2. \u{1F3C3} Start development: sinch functions dev"):t.info(" 2. \u{1F3C3} Start development: dotnet run"),t.info(" 3. \u{1F680} Deploy to production: sinch functions deploy"),t.info(" 4. \u{1F4CA} View logs: sinch functions logs --follow"),t.newline(),t.info("\u{1F4A1} Template info:"),t.info(`\u2022 ${l.description}`),l.features&&l.features.length>0&&l.features.forEach(b=>{t.info(`\u2022 ${b}`)})}catch(n){d.stop(),t.error(`Failed to initialize function: ${n.message}`),process.exit(1)}});Ut.exports=Nt});var Mt=U((Bi,Jt)=>{"use strict";var E=h(require("chalk")),Bt=require("commander"),qt=h(require("cli-table3")),_e=h(require("inquirer"));x();j();B();O();var Vt=new Bt.Command("list");Vt.description("List all functions").option("--status <status>","Filter by status (Running, Failed, Pending, Building)").option("--runtime <runtime>","Filter by runtime (node, csharp, python)").option("--limit <limit>","Limit number of results","50").option("-i, --interactive","Interactive mode - select function for actions").action(async o=>{try{await f.load();let e=new I(f.getApiConfig());d.start("\u{1F4CB} Loading functions...");let n={limit:parseInt(o.limit||"50")};o.status&&(n.status=o.status),o.runtime&&(n.runtime=o.runtime);let i=await e.listFunctions();if(d.succeed(`\u{1F4CB} Found ${i.functions.length} functions`),i.functions.length===0){t.newline(),t.info("No functions found"),t.info("\u{1F4A1} Create your first function with:"),t.info(` ${E.default.cyan("sinch functions init")}`);return}t.newline(),t.title("Functions:");let s=i.functions.map(r=>{let u=new Date(r.createdAt).toLocaleDateString(),c=at(r.status),l=r.containerAppUrl?r.containerAppUrl.length>40?r.containerAppUrl.substring(0,37)+"...":r.containerAppUrl:E.default.gray("Not deployed");return[E.default.cyan(r.name),E.default.yellow(r.runtime),c,E.default.gray(u),E.default.blue(l)]}),a=new qt.default({head:["Name","Runtime","Status","Created","URL"],style:{head:["cyan"]},colWidths:[20,10,15,12,45]});if(a.push(...s),console.log(a.toString()),i.pagination){let{page:r,totalCount:u,totalPages:c}=i.pagination;t.newline(),t.info(E.default.gray(`Page ${r} of ${c} (${u} total functions)`)),r<c&&t.info(E.default.gray("\u{1F4A1} Use --limit to see more results"))}if(o.interactive&&i.functions.length>0){t.newline();let r=i.functions.map(l=>({name:`${l.name.padEnd(20)} ${l.runtime.padEnd(8)} ${at(l.status).padEnd(20)} ${l.id.substring(0,8)}`,value:l.id,short:l.name}));r.push(new _e.default.Separator),r.push({name:E.default.gray("Exit"),value:"exit",short:"Exit"});let{selectedFunction:u}=await _e.default.prompt([{type:"list",name:"selectedFunction",message:"Select a function for actions:",choices:r,pageSize:15}]);if(u==="exit")return;let c=i.functions.find(l=>l.id===u);c&&await ho(c,e)}else t.newline(),t.info("\u{1F4A1} Function commands:"),t.info(` \u2022 View details: ${E.default.cyan("sinch functions status 01HX3KC5V8G3KCNZ8S5Y9ABC")}`),t.info(` \u2022 View logs: ${E.default.cyan("sinch functions logs 01HX3KC5V8G3KCNZ8S5Y9ABC")}`),t.info(` \u2022 Download: ${E.default.cyan("sinch functions download 01HX3KC5V8G3KCNZ8S5Y9ABC")}`),t.info(` \u2022 Interactive mode: ${E.default.cyan("sinch functions list -i")}`),t.info(` \u2022 Deploy new function: ${E.default.cyan("sinch functions deploy")}`)}catch(e){d.stop(),t.error(`Failed to list functions: ${e.message}`),process.exit(1)}});function at(o){return{Running:E.default.green("\u2705 Running"),Failed:E.default.red("\u274C Failed"),Pending:E.default.yellow("\u23F3 Pending"),Building:E.default.blue("\u{1F528} Building")}[o]||E.default.gray(o)}async function ho(o,e){t.newline(),t.info(`\u{1F4CB} Selected: ${E.default.cyan(o.name)}`),t.info(` ID: ${E.default.gray(o.id)}`),t.info(` Status: ${at(o.status)}`),t.newline();let{action:n}=await _e.default.prompt([{type:"list",name:"action",message:"What would you like to do?",choices:[{name:"\u{1F4E5} Download source code",value:"download"},{name:"\u{1F4CA} View status details",value:"status"},{name:"\u{1F4DC} View logs",value:"logs"},{name:"\u{1F517} Copy URL to clipboard",value:"copy-url"},{name:"\u{1F5D1}\uFE0F Delete function",value:"delete"},new _e.default.Separator,{name:E.default.gray("Back"),value:"back"}]}]);switch(n){case"download":t.info(`
|
|
34
34
|
\u{1F4A1} To download this function, run:`),t.info(` ${E.default.cyan(`sinch functions download ${o.id}`)}`);break;case"status":t.info(`
|
|
35
35
|
\u{1F4A1} To view status, run:`),t.info(` ${E.default.cyan(`sinch functions status ${o.id}`)}`);break;case"logs":t.info(`
|
|
36
36
|
\u{1F4A1} To view logs, run:`),t.info(` ${E.default.cyan(`sinch functions logs ${o.id}`)}`);break;case"copy-url":o.containerAppUrl?(await require("clipboardy").write(o.containerAppUrl),t.success(`\u2705 URL copied to clipboard: ${o.containerAppUrl}`)):t.warn("\u26A0\uFE0F Function has no URL (not deployed)");break;case"delete":t.info(`
|
|
37
|
-
\u{1F4A1} To delete this function, run:`),t.info(` ${E.default.cyan(`sinch functions delete ${o.id}`)}`);break;case"back":return}}Jt.exports=Vt});async function lt(o){if(!await
|
|
37
|
+
\u{1F4A1} To delete this function, run:`),t.info(` ${E.default.cyan(`sinch functions delete ${o.id}`)}`);break;case"back":return}}Jt.exports=Vt});async function lt(o){if(!await f.hasCredentials())throw new Error('No Sinch credentials found. Run "sinch auth login" first.');let e=await f.getApplicationCredentials();if(!e)throw new Error('No application credentials found. Run "sinch auth login" first.');let i=`https://callingapi.sinch.com/v1/configuration/callbacks/applications/${e.applicationKey}/`,s={url:{primary:o}},a=`${e.applicationKey}:${e.applicationSecret}`,r=Buffer.from(a).toString("base64");await ct.default.post(i,s,{headers:{Authorization:`Basic ${r}`,"Content-Type":"application/json"},timeout:1e4}),await new Promise(p=>setTimeout(p,1e3));let l=(await ct.default.get(i,{headers:{Authorization:`Basic ${r}`},timeout:1e4})).data?.url?.primary;if(l!==o)throw t.debug(`Callback verification mismatch. Expected: ${o}, Got: ${l}`),new Error(`Callback URL update verification failed. Expected: ${o}, Got: ${l}`);t.debug("Voice callback URL successfully updated and verified")}var ct,Ht=he(()=>{"use strict";ct=h(require("axios"));j();B()});var zt={};Je(zt,{combineDocumentation:()=>Gt,detectRuntimeFromFile:()=>Yt,findFunctionFile:()=>Wt,generateDocsFromLocal:()=>ut,saveDocumentationToFile:()=>dt});async function ut(){let o=process.cwd(),e=await Wt(o);if(!e)throw new Error("No function file found. Make sure you're in a function directory with function.js, function.ts, index.js, index.ts, handler.js, or handler.ts");let n=await Te.readFile(e,"utf8"),i=Yt(e),s=ue.basename(o),r=await new I(f.getApiConfig()).generateDocumentationFromCode(n,i,s);return Gt(r)}async function Wt(o){let e=["function.js","function.ts","index.js","index.ts","handler.js","handler.ts","function.py","handler.py","Function.cs","Handler.cs"];for(let n of e){let i=ue.join(o,n);if(await Te.pathExists(i))return i}return null}function Gt(o){let e=o.documentation||"",n=o.diagram||o.callFlowDiagram;return n&&(e&&!e.endsWith(`
|
|
38
38
|
|
|
39
39
|
`)&&(e+=`
|
|
40
40
|
|
|
@@ -44,52 +44,52 @@ ${e}`))}list(e,n={}){let{indent:i=" ",bullet:s="\u2022"}=n;e.forEach(r=>{consol
|
|
|
44
44
|
---
|
|
45
45
|
|
|
46
46
|
`,e+=`*Documentation generated on ${new Date(o.generatedAt).toLocaleString()} using Sinch AI*
|
|
47
|
-
`),e}async function dt(o,e){let n=ue.resolve(e);await Te.writeFile(n,o,"utf8")}function Yt(o){switch(ue.extname(o).toLowerCase()){case".js":return"node";case".py":return"python";case".cs":return"csharp";default:return"node"}}var Te,ue,pt=he(()=>{"use strict";Te=
|
|
48
|
-
`);for(let C of
|
|
49
|
-
`).forEach(c=>{if(c.trim()&&!c.trim().startsWith("#")){let[
|
|
50
|
-
${
|
|
47
|
+
`),e}async function dt(o,e){let n=ue.resolve(e);await Te.writeFile(n,o,"utf8")}function Yt(o){switch(ue.extname(o).toLowerCase()){case".js":case".ts":return"node";case".py":return"python";case".cs":return"csharp";default:return"node"}}var Te,ue,pt=he(()=>{"use strict";Te=h(require("fs-extra")),ue=h(require("path"));x();j()});var sn=U((Xi,on)=>{"use strict";var Z=h(require("fs-extra")),be=h(require("path")),k=h(require("chalk")),Zt=require("commander");x();j();B();O();Ht();var Xt=h(require("adm-zip")),en=h(require("os")),ft=h(require("inquirer")),Le=require("child_process"),tn=h(require("keytar")),nn=new Zt.Command("deploy");nn.description("Deploy function to production").option("-n, --name <name>","Function name (default: current directory)").option("--no-wait","Don't wait for deployment to complete").option("--non-interactive","Use default values without prompting (auto-generates docs)").option("--no-docs","no doc generation").option("--private","Deploy to private namespace (internal access only, not publicly accessible)").action(async o=>{try{if(await f.load(),!f.isInProject())throw new Error('Not in a Sinch Functions project directory. Run "sinch functions init" first.');let e=f.getProjectConfig(),n=o.name||e.name,i=e.runtime;if(await bo(e,o),i==="csharp"){let p=await Z.default.readdir(process.cwd()).then(C=>C.filter(w=>w.endsWith(".csproj")));if(p.length===0)throw new Error("No .csproj file found. Make sure you're in a valid C# function directory.");let m=p[0];await $o(process.cwd(),m)}d.start("\u{1F4E6} Packaging function...");let s=await yo(n);d.succeed("\u{1F4E6} Function packaged"),d.start("\u{1F527} Preparing configuration...");let a=await wo(i,n);d.succeed("\u{1F527} Configuration prepared");let r=await vo(e,o);d.start("\u{1F680} Submitting deployment...");let u=new I(f.getApiConfig()),c=await Z.default.readFile(s),l=await u.deployFunction(n,i,c,a,r);if(await Z.default.remove(s),d.succeed("\u{1F680} Deployment submitted"),f.set("functionId",l.id,!0),await f.saveProjectConfig(),t.newline(),t.info(`Function ID: ${k.default.cyan(l.id)}`),t.info(`Status: ${gt(l.status)}`),o.wait===!1){t.newline(),t.info("\u{1F4A1} Check deployment progress with:"),t.info(` ${k.default.cyan(`sinch functions status ${l.id}`)}`);return}await Co(u,l.id)}catch(e){d.stop(),t.error(`Failed to deploy function: ${e.message}`),process.exit(1)}});async function yo(o){let e=new Xt.default,n=process.cwd(),i=be.default.join(en.default.tmpdir(),`${o}-${Date.now()}.zip`),s=["node_modules","bin","obj",".git",".DS_Store","*.zip",".env",".env.local","npm-debug.log*",".sinch-tmp","examples","claude.md","readme.md",".vs",".vscode",".idea",".cursor","*.user","*.suo"];async function a(r,u=""){let c=await Z.default.readdir(r);for(let l of c){let p=be.default.join(r,l),m=be.default.join(u,l).replace(/\\/g,"/");if(s.some(w=>l.match(new RegExp(w.replace("*",".*")))))continue;if((await Z.default.stat(p)).isDirectory())await a(p,m);else{let w=await Z.default.readFile(p);e.addFile(m,w)}}}return await a(n),e.writeZip(i),i}async function wo(o,e){let n={},i=null;try{i=await f.getCredentials()}catch(s){t.debug("Could not load credentials from secure storage: "+s.message)}if(o==="csharp"){let s=be.default.join(process.cwd(),"appsettings.json");if(await Z.default.pathExists(s))try{let a=await Z.default.readJson(s);for(let r of Object.keys(a)){if(r==="Logging"||r==="AllowedHosts")continue;let u=a[r];if(u===""||u===null||u===void 0){let c="",l=!1;try{let m=(0,Le.execSync)("dotnet user-secrets list",{cwd:process.cwd(),encoding:"utf8",stdio:["pipe","pipe","pipe"]}).trim().split(`
|
|
48
|
+
`);for(let C of m){let w=C.match(/^([^=]+)\s*=\s*(.+)$/);if(w&&w[1]&&w[2]&&w[1].trim()===r){c=w[2].trim(),l=!0,t.debug(`Found ${r} in dotnet user-secrets`);break}}}catch{}!c&&i&&(r==="PROJECT_ID"&&i.projectId?c=i.projectId:r==="PROJECT_ID_API_KEY"&&i.keyId?c=i.keyId:r==="PROJECT_ID_API_SECRET"&&i.keySecret?(c=i.keySecret,l=!0):r==="VOICE_APPLICATION_KEY"&&i.applicationKey?c=i.applicationKey:r==="VOICE_APPLICATION_SECRET"&&i.applicationSecret&&(c=i.applicationSecret,l=!0)),c&&(n[r]={Value:c,Secret:l})}else n[r]={Value:String(u),Secret:!1}}}catch(a){t.debug("Could not read appsettings.json: "+a.message)}}else{let s=be.default.join(process.cwd(),".env");if(await Z.default.pathExists(s))try{let a=await Z.default.readFile(s,"utf8"),r={};a.split(`
|
|
49
|
+
`).forEach(c=>{if(c.trim()&&!c.trim().startsWith("#")){let[l,...p]=c.split("=");l&&(r[l.trim()]=p.join("=").trim())}});let u=["PORT","NODE_ENV","SINCH_TUNNEL"];for(let[c,l]of Object.entries(r))if(!u.includes(c))if(l===""||l===null||l===void 0){let p="",m=!1;if(i&&(c==="PROJECT_ID"&&i.projectId?p=i.projectId:c==="PROJECT_ID_API_KEY"&&i.keyId?p=i.keyId:c==="PROJECT_ID_API_SECRET"&&i.keySecret?(p=i.keySecret,m=!0):c==="VOICE_APPLICATION_KEY"&&i.applicationKey?p=i.applicationKey:c==="VOICE_APPLICATION_SECRET"&&i.applicationSecret&&(p=i.applicationSecret,m=!0)),!p)try{let C="sinch-functions-cli",w=`${e}-${c}`;p=await tn.default.getPassword(C,w)||"",p&&(m=!0,t.debug(`Loaded custom secret ${c} from keychain`))}catch(C){t.debug(`Could not load ${c} from keychain: ${C.message}`)}p&&(n[c]={Value:p,Secret:m})}else n[c]={Value:l,Secret:!1}}catch(a){t.debug("Could not read .env file: "+a.message)}}return n}async function Co(o,e){let i=Date.now(),s=!1,a;return t.newline(),d.start("\u23F3 Connecting to deployment stream..."),new Promise((r,u)=>{let c,l;o.streamDeployment(e,p=>{let m=Math.floor((Date.now()-i)/1e3);switch(p.type){case"connected":d.text="\u23F3 Deployment stream connected, waiting for updates...";break;case"status":let C=p.data.data.message;d.text=`\u23F3 ${C} (${m}s)`;break;case"progress":let w=p.data.data.message,A=p.data.data.percentComplete;A?d.text=`\u23F3 ${w} (${A}%, ${m}s)`:d.text=`\u23F3 ${w} (${m}s)`;break;case"completed":s=!0,a=p.data.data.url,d.succeed("\u2705 Function deployed successfully"),o.getFunction(e).then(async W=>{if(t.newline(),t.info("\u{1F389} Deployment Complete!"),t.info(` Function: ${k.default.cyan(W.name)}`),t.info(` Status: ${gt("Running")}`),t.info(` URL: ${k.default.blue(a)}`),a){t.newline(),t.info("\u{1F4DE} Voice Integration:");try{d.start("Updating Sinch Voice callback URL..."),await lt(a),d.succeed("Voice callback URL updated automatically"),t.info(` Callback URL set to: ${k.default.cyan(a)}`)}catch(P){d.fail("Failed to update callback URL automatically"),t.warn(` Error: ${P.message}`),t.info(` Manual setup: ${k.default.cyan(`sinch voice callback-url ${a}`)}`)}t.info(` Test function: ${k.default.cyan(`curl ${a}`)}`)}t.newline(),t.info("\u{1F4A1} Next steps:"),t.info(` \u2022 View logs: ${k.default.cyan(`sinch functions logs ${e} --follow`)}`),t.info(` \u2022 Check status: ${k.default.cyan(`sinch functions status ${e}`)}`),c&&c(),l&&clearTimeout(l),r()}).catch(W=>{t.error(`Failed to get function details: ${W.message}`),c&&c(),l&&clearTimeout(l),r()});break;case"failed":s=!0;let J=p.data.data.errorMessage;d.fail("\u274C Deployment failed"),t.newline(),t.error("Deployment failed:"),J&&t.error(` ${J}`),t.newline(),t.info("\u{1F4A1} Troubleshooting:"),t.info(` \u2022 Check logs: ${k.default.cyan(`sinch functions logs ${e}`)}`),t.info(` \u2022 Check status: ${k.default.cyan(`sinch functions status ${e}`)}`),c&&c(),l&&clearTimeout(l),process.exit(1);break}},p=>{t.debug("SSE stream error, falling back to polling:",p),d.text="\u23F3 Deployment stream unavailable, checking status...",c&&c(),Qt(o,e,i,3e5).then(r).catch(u)}).then(p=>{t.debug("SSE stream setup successful, cleanup function received"),c=p,l=setTimeout(()=>{s||(d.fail("\u23F0 Deployment timeout"),t.newline(),t.warn("Deployment is taking longer than expected"),t.info("\u{1F4A1} Check deployment progress with:"),t.info(` ${k.default.cyan(`sinch functions status ${e}`)}`),c&&c(),r())},3e5)}).catch(p=>{t.debug(`Failed to set up SSE stream, falling back to polling: ${p.message}`),Qt(o,e,i,3e5).then(r).catch(u)})})}async function Qt(o,e,n,i){for(;Date.now()-n<i;){try{let r=(await o.getFunctionStatus(e)).function;if(r.status==="Running"){if(d.succeed("\u2705 Function deployed successfully"),t.newline(),t.info("\u{1F389} Deployment Complete!"),t.info(` Function: ${k.default.cyan(r.name)}`),t.info(` Status: ${gt(r.status)}`),t.info(` URL: ${k.default.blue(r.containerAppUrl)}`),r.containerAppUrl){t.newline(),t.info("\u{1F4DE} Voice Integration:");try{d.start("Updating Sinch Voice callback URL..."),await lt(r.containerAppUrl),d.succeed("Voice callback URL updated automatically"),t.info(` Callback URL set to: ${k.default.cyan(r.containerAppUrl)}`)}catch(c){d.fail("Failed to update callback URL automatically"),t.warn(` Error: ${c.message}`),t.info(` Manual setup: ${k.default.cyan(`sinch voice callback-url ${r.containerAppUrl}`)}`)}t.info(` Test function: ${k.default.cyan(`curl ${r.containerAppUrl}`)}`)}t.newline(),t.info("\u{1F4A1} Next steps:"),t.info(` \u2022 View logs: ${k.default.cyan(`sinch functions logs ${e} --follow`)}`),t.info(` \u2022 Check status: ${k.default.cyan(`sinch functions status ${e}`)}`);return}r.status==="Failed"&&(d.fail("\u274C Deployment failed"),t.newline(),t.error("Deployment failed:"),r.errorMessage&&t.error(` ${r.errorMessage}`),t.newline(),t.info("\u{1F4A1} Troubleshooting:"),t.info(` \u2022 Check logs: ${k.default.cyan(`sinch functions logs ${e}`)}`),t.info(` \u2022 Check status: ${k.default.cyan(`sinch functions status ${e}`)}`),process.exit(1));let u=Math.floor((Date.now()-n)/1e3);d.text=`\u23F3 Deploying function... (${r.status}, ${u}s)`}catch(a){t.debug(`Status check failed: ${a.message}`)}await new Promise(a=>setTimeout(a,3e3))}d.fail("\u23F0 Deployment timeout"),t.newline(),t.warn("Deployment is taking longer than expected"),t.info("\u{1F4A1} Check deployment progress with:"),t.info(` ${k.default.cyan(`sinch functions status ${e}`)}`)}function gt(o){return{Running:k.default.green("\u2705 Running"),Failed:k.default.red("\u274C Failed"),Pending:k.default.yellow("\u23F3 Pending"),Building:k.default.blue("\u{1F528} Building")}[o]||k.default.gray(o)}async function bo(o,e){let n=!1;if(e.docs===!1){t.info("Skipping documentation generation (--no-docs flag)");return}if(e.nonInteractive)t.info("Generating documentation (non-interactive mode)"),n=!0;else{if(o.docsPreference==="never")return;if(So(o))n=!0;else{let i=await ft.default.prompt([{type:"list",name:"docsChoice",message:"Generate/update documentation before deployment?",choices:[{name:"Yes - Generate documentation this time",value:"yes"},{name:"No - Skip documentation this time",value:"no"},{name:"Always - Generate documentation and remember preference",value:"always"},{name:"Never - Don't generate documentation and remember preference",value:"never"}],default:"yes"}]);i.docsChoice==="yes"?n=!0:i.docsChoice==="no"?n=!1:i.docsChoice==="always"?(n=!0,f.set("docsPreference","always",!0),await f.saveProjectConfig()):i.docsChoice==="never"&&(n=!1,f.set("docsPreference","never",!0),await f.saveProjectConfig())}}if(n)try{d.start("\u{1F4DD} Generating documentation...");let{generateDocsFromLocal:i,saveDocumentationToFile:s}=(pt(),F(zt)),a=await i(),r=be.default.basename(process.cwd());await s(a,"README.md",r),d.succeed("\u{1F4DD} Documentation updated in README.md")}catch(i){d.warn(`\u26A0\uFE0F Failed to generate documentation: ${i.message}`),t.warn("Continuing with deployment...")}}function So(o){return o.docsPreference==="always"}async function vo(o,e){if(e.private||o.accessPreference==="always-private")return"private";if(o.accessPreference==="always-public"||e.nonInteractive)return"public";let i=(await ft.default.prompt([{type:"list",name:"accessChoice",message:"Deployment access level?",choices:[{name:"Public - Accessible from the internet",value:"public"},{name:"Private - Internal access only (Sinch services)",value:"private"},{name:"Always Public - Remember this choice",value:"always-public"},{name:"Always Private - Remember this choice",value:"always-private"}],default:"public"}])).accessChoice;return i==="always-public"?(f.set("accessPreference","always-public",!0),await f.saveProjectConfig(),"public"):i==="always-private"?(f.set("accessPreference","always-private",!0),await f.saveProjectConfig(),"private"):i}async function $o(o,e){d.start("Building function locally...");try{await new Promise((s,a)=>{let r=(0,Le.spawn)("dotnet",["build",e,"-c","Release"],{cwd:o,stdio:"pipe",shell:!0}),u="",c="";r.stdout?.on("data",l=>{c+=l}),r.stderr?.on("data",l=>{u+=l}),r.on("close",l=>{l!==0?a(new Error(`Build failed:
|
|
50
|
+
${u||c}`)):s()})}),d.succeed("Build successful")}catch(s){throw d.fail("Build failed"),s}d.start("Starting function for validation...");let n=null,i="";try{if(n=(0,Le.spawn)("dotnet",["run","--project",e,"--no-build","-c","Release"],{cwd:o,stdio:"pipe",shell:!0}),n.stdout?.on("data",a=>{i+=a.toString()}),n.stderr?.on("data",a=>{i+=a.toString()}),await Po("http://localhost:3000/health",3e4))d.succeed("Function started and health check passed");else throw d.fail("Function failed to start within timeout"),i&&console.error(`
|
|
51
51
|
Process output:
|
|
52
|
-
`+
|
|
52
|
+
`+i),new Error("Function validation failed: could not start function")}catch(s){throw d.fail("Validation failed"),i&&console.error(`
|
|
53
53
|
Process output:
|
|
54
|
-
`+
|
|
54
|
+
`+i),s}finally{if(n&&n.pid){try{process.kill(n.pid)}catch{}await new Promise(s=>setTimeout(s,1e3))}}}async function Po(o,e){let n=Date.now();for(;Date.now()-n<e;){try{if((await fetch(o)).ok)return!0}catch{}await new Promise(i=>setTimeout(i,500))}return!1}on.exports=nn});var un=U((is,ln)=>{"use strict";var T=h(require("fs-extra")),oe=h(require("path")),xe=h(require("chalk")),mt=require("child_process"),rn=require("commander"),an=h(require("inquirer"));j();B();O();var cn=new rn.Command("dev");cn.description("Start local development server").option("-p, --port <port>","Port to run on","3000").option("-d, --debug","Enable debugging with --inspect").option("--tunnel","Force tunnel creation").option("--no-tunnel",'Disable tunnel and reset "always" preference').action(async o=>{try{if(await f.load(),!f.isInProject())throw new Error('Not in a Sinch Functions project directory. Run "sinch functions init" first.');let e=f.getProjectConfig();if(!e)throw new Error("No project configuration found");let n=e.runtime||"node",i;if(n==="csharp"){let s=await T.default.readdir(process.cwd()).then(a=>a.filter(r=>r.endsWith(".csproj")));if(s.length===0)throw new Error("No .csproj file found. Make sure you're in a valid C# function directory.");i=s[0],t.debug(`Using project file: ${i}`)}else{let s=oe.default.join(process.cwd(),"node_modules",".bin","sinch-runtime");if(!await T.default.pathExists(s))throw new Error("@sinch/functions-runtime not found. Run npm install first.")}t.title(`Starting ${e.name} (${e.runtime})`),t.info(`Port: ${o.port}`),t.newline(),await Eo(o,e,i)}catch(e){d.stop(),t.error(`Failed to start development server: ${e.message}`),process.exit(1)}});async function ko(o,e){if(e==="node"){let n=oe.default.join(process.cwd(),".env");if(await T.default.pathExists(n)){let i=await T.default.readFile(n,"utf-8"),s=`SINCH_TUNNEL=${o}`;i.includes("SINCH_TUNNEL=")?i=i.replace(/SINCH_TUNNEL=(true|false)/g,s):i+=`
|
|
55
55
|
${s}
|
|
56
|
-
`,await T.default.writeFile(n,i,"utf-8"),t.debug(`Updated .env: SINCH_TUNNEL=${o}`)}}else if(e==="csharp"){let n=oe.default.join(process.cwd(),"appsettings.Development.json");if(await T.default.pathExists(n)){let i=await T.default.readJson(n);i.SinchTunnel=o,await T.default.writeJson(n,i,{spaces:2}),t.debug(`Updated appsettings.Development.json: SinchTunnel=${o}`)}}}async function Eo(o,e){let n=e.runtime||"node",i=!1;if(o.tunnel===!0)i=!0;else if(o.tunnel===!1)i=!1,e.tunnel?.preference==="always"&&(p.set("tunnel",{...e.tunnel,preference:"no"},!0),await p.saveProjectConfig());else if(e.tunnel?.preference==="never")i=!1;else if(To(e))i=!0;else{let{tunnelChoice:c}=await an.default.prompt([{type:"list",name:"tunnelChoice",message:"Enable Sinch tunnel for external access?",choices:[{name:"Yes - Enable tunnel this time",value:"yes"},{name:"No - Local only this time",value:"no"},{name:"Always - Enable tunnel and remember preference",value:"always"},{name:"Never - Don't enable tunnel and remember preference",value:"never"}],default:"no"}]);c==="yes"?i=!0:c==="no"?i=!1:c==="always"?(i=!0,p.set("tunnel",{...e.tunnel,preference:"always"},!0),await p.saveProjectConfig()):c==="never"&&(i=!1,p.set("tunnel",{...e.tunnel,preference:"never"},!0),await p.saveProjectConfig())}await ko(i,n);let s={...process.env,PORT:o.port,NODE_ENV:"development",SINCH_FUNCTIONS_LOCAL:"true",SINCH_TUNNEL:i?"true":"false"};e.variables&&Object.entries(e.variables).forEach(([c,u])=>{s[c]=u});try{let c=await p.getApplicationCredentials(e.voiceAppKey);c?(s.SINCH_APPLICATION_KEY=c.applicationKey,s.SINCH_APPLICATION_SECRET=c.applicationSecret,t.debug("\u2705 Injected application credentials for voice operations")):t.debug("\u26A0\uFE0F No application credentials found - voice features may not work")}catch(c){t.debug(`\u26A0\uFE0F Could not load application credentials: ${c.message}`)}t.info("\u{1F680} Starting local server...");let r=null,a=!1;function l(){if(r&&r.kill(),n==="csharp"){let c=["watch","run","--no-launch-profile"];o.port&&c.push("--urls",`http://localhost:${o.port}`),s.ASPNETCORE_ENVIRONMENT="Development",s.ASPNETCORE_URLS=`http://localhost:${o.port}`,r=(0,mt.spawn)("dotnet",c,{env:s,stdio:"inherit",cwd:process.cwd()})}else r=(0,mt.spawn)("npm",["run","dev"],{env:s,stdio:"inherit",cwd:process.cwd(),shell:!0});r.on("spawn",async()=>{if(!a){a=!0,t.newline(),t.success(`\u2705 Server running on http://localhost:${o.port}`),o.debug&&(t.newline(),n==="csharp"?jo():Io()),t.newline(),t.info("\u{1F4A1} Development commands:"),t.info(` \u2022 Test function: ${xe.default.cyan(`curl http://localhost:${o.port}`)}`),t.info(` \u2022 View in browser: ${xe.default.cyan(`http://localhost:${o.port}`)}`),t.info(` \u2022 Stop server: ${xe.default.gray("Ctrl+C")}`);let c=n==="csharp"?"dotnet watch":"nodemon";t.info(` \u2022 File watching: ${xe.default.green(`enabled (via ${c})`)}`)}}),r.on("error",c=>{t.error(`Server error: ${c.message}`)}),r.on("exit",(c,u)=>{u!=="SIGTERM"&&u!=="SIGKILL"&&t.error(`Server exited with code ${c}`)})}l(),process.on("SIGINT",()=>{t.newline(),t.info("\u{1F534} Stopping development server..."),r&&r.kill("SIGTERM"),process.exit(0)}),await new Promise(()=>{})}async function Io(){try{let o=await je("code",".vscode"),e=await je("cursor",".cursor"),n=await je("webstorm",".idea");if(o||e){let i=o?"VS Code":"Cursor",s=".vscode";if(t.info(`\u{1F41B} ${i} detected! Debug setup:`),await Ro(s))t.info(" 1. \u2705 Created .vscode/launch.json for you");else{let a=oe.default.join(process.cwd(),s,"launch.json");await T.default.pathExists(a)?t.info(" 1. \u2705 Found existing .vscode/launch.json"):t.info(" 1. \u26A0\uFE0F Could not create .vscode/launch.json")}t.info(" 2. \u{1F50D} Press F5 to attach debugger"),t.info(" 3. \u{1F534} Set breakpoints in your function.js"),t.info(" 4. \u{1F4DE} Test your function to hit breakpoints")}else n?(t.info("\u{1F41B} WebStorm detected! Debug setup:"),t.info(" 1. \u{1F50D} Run \u2192 Attach to Node.js/Chrome \u2192 localhost:9229"),t.info(" 2. \u{1F534} Set breakpoints in your function.js")):(t.info("\u{1F41B} Manual debug setup:"),t.info(' \u2022 VS Code/Cursor: Open "Run and Debug" \u2192 "Attach to Node.js Process"'),t.info(' \u2022 Chrome DevTools: Visit chrome://inspect \u2192 Click "inspect"'),t.info(" \u2022 Manual: Connect debugger to ws://localhost:9229"))}catch{t.info("\u{1F41B} Debug instructions:"),t.info(" \u2022 Connect your debugger to ws://localhost:9229"),t.info(" \u2022 Set breakpoints and test your function")}}async function je(o,e){try{if(o==="code"&&Ao())return!0;let{spawn:n}=require("child_process"),i=await new Promise(r=>{let a=n(o,["--version"],{stdio:"pipe"});a.on("close",l=>r(l===0)),a.on("error",()=>r(!1))}),s=e?await T.default.pathExists(e):!1;return i||s}catch{return!1}}function Ao(){return process.env.TERM_PROGRAM==="vscode"||!!process.env.VSCODE_IPC_HOOK||!!process.env.VSCODE_PID}async function Ro(o=".vscode"){try{let e=oe.default.join(process.cwd(),o),n=oe.default.join(e,"launch.json");if(await T.default.pathExists(n))return!1;await T.default.ensureDir(e);let i={version:"0.2.0",configurations:[{name:"Attach to Sinch Function",type:"node",request:"attach",port:9229,localRoot:"${workspaceFolder}",remoteRoot:"${workspaceFolder}",skipFiles:["<node_internals>/**","node_modules/**"]}]};return await T.default.writeJson(n,i,{spaces:2}),!!await T.default.pathExists(n)}catch{return!1}}function To(o){return o.tunnel?o.tunnel.preference==="always":!1}async function jo(){try{let o=await je("code",".vscode"),e=await je("devenv"),n=await je("rider",".idea");o?(t.info("\u{1F41B} VS Code detected! Debug setup:"),await Do(".vscode")?t.info(" 1. \u2705 Created .vscode/launch.json for C#"):t.info(" 1. \u2705 Found existing .vscode/launch.json"),t.info(" 2. \u{1F50D} Press F5 to attach debugger"),t.info(" 3. \u{1F534} Set breakpoints in your Function.cs"),t.info(" 4. \u{1F4DE} Test your function to hit breakpoints")):e?(t.info("\u{1F41B} Visual Studio detected! Debug setup:"),t.info(" 1. \u{1F50D} Debug \u2192 Attach to Process \u2192 dotnet.exe"),t.info(" 2. \u{1F534} Set breakpoints in your Function.cs"),t.info(" 3. \u{1F4DE} Test your function to hit breakpoints")):n?(t.info("\u{1F41B} JetBrains Rider detected! Debug setup:"),t.info(" 1. \u{1F50D} Run \u2192 Attach to Process \u2192 dotnet"),t.info(" 2. \u{1F534} Set breakpoints in your Function.cs")):(t.info("\u{1F41B} C# Debug setup:"),t.info(" \u2022 Visual Studio: Debug \u2192 Attach to Process \u2192 dotnet.exe"),t.info(" \u2022 VS Code: Install C# extension, then F5 to debug"),t.info(" \u2022 Rider: Run \u2192 Attach to Process"))}catch{t.info("\u{1F41B} C# Debug instructions:"),t.info(" \u2022 Attach your debugger to the dotnet process"),t.info(" \u2022 Set breakpoints in Function.cs")}}async function Do(o=".vscode"){try{let e=oe.default.join(process.cwd(),o),n=oe.default.join(e,"launch.json");if(await T.default.pathExists(n))return!1;await T.default.ensureDir(e);let i={version:"0.2.0",configurations:[{name:".NET Core Launch (web)",type:"coreclr",request:"launch",preLaunchTask:"build",program:"${workspaceFolder}/bin/Debug/net8.0/Function.dll",args:[],cwd:"${workspaceFolder}",stopAtEntry:!1,serverReadyAction:{action:"openExternally",pattern:"\\bNow listening on:\\s+(https?://\\S+)"},env:{ASPNETCORE_ENVIRONMENT:"Development"},sourceFileMap:{"/Views":"${workspaceFolder}/Views"}},{name:".NET Core Attach",type:"coreclr",request:"attach"}]};await T.default.writeJson(n,i,{spaces:2});let s=oe.default.join(e,"tasks.json");if(!await T.default.pathExists(s)){let r={version:"2.0.0",tasks:[{label:"build",command:"dotnet",type:"process",args:["build","${workspaceFolder}/Function.csproj","/property:GenerateFullPaths=true","/consoleloggerparameters:NoSummary"],problemMatcher:"$msCompile"}]};await T.default.writeJson(s,r,{spaces:2})}return await T.default.pathExists(n)}catch{return!1}}ln.exports=cn});var mn=U((ls,gn)=>{"use strict";var V=m(require("chalk")),dn=require("commander");x();j();B();O();var pn=new dn.Command("status");pn.description("Show function status and details").argument("[function-id]","Function ID to check (optional if sinch.json exists)").option("-f, --follow","Watch status changes in real-time").option("--json","Output raw JSON").action(async(o,e)=>{try{await p.load();let n=new I(p.getApiConfig()),i=o;if(!i){if(!p.isInProject())throw new Error("Function ID required. Provide as argument or run from function directory with sinch.json");if(i=p.getProjectConfig()?.functionId,!i)throw new Error("No function ID found in sinch.json. Deploy the function first or provide function ID as argument.")}e.follow?await Oo(n,i):await Fo(n,i,e)}catch(n){d.stop(),t.error(`Failed to get function status: ${n.message}`),process.exit(1)}});async function Fo(o,e,n){d.start("\u{1F4E1} Loading function status...");try{let i=await o.getFunction(e),s=await o.getFunctionStatus(e);if(d.stop(),n.json){console.log(JSON.stringify({function:i,deployment:s},null,2));return}let r=i,a=s.status,l=s.error;t.newline(),t.title(`Function Status: ${r.name}`),t.newline(),t.info("\u{1F4CB} Function Details:"),t.info(` ID: ${V.default.gray(r.id)}`),t.info(` Name: ${V.default.cyan(r.name)}`),t.info(` Runtime: ${V.default.yellow(r.runtime)}`),t.info(` Deployment Status: ${fn(a)}`),r.created&&t.info(` Created: ${new Date(r.created).toLocaleString()}`),r.updated&&t.info(` Updated: ${new Date(r.updated).toLocaleString()}`),r.url&&t.info(` URL: ${V.default.blue(r.url)}`),a==="Failed"&&l&&(t.newline(),t.error("Deployment Error:"),t.error(` ${l}`)),t.newline(),t.info("\u{1F4A1} Commands:"),t.info(` \u2022 View logs: ${V.default.cyan(`sinch functions logs ${e}`)}`),t.info(` \u2022 Redeploy: ${V.default.cyan("sinch functions deploy")}`),t.info(` \u2022 Delete: ${V.default.cyan(`sinch functions delete ${e}`)}`)}catch(i){throw d.stop(),i}}async function Oo(o,e){t.info("\u{1F440} Watching deployment status (press Ctrl+C to stop)..."),t.newline();let n=null,i=setInterval(async()=>{try{let s=await o.getFunctionStatus(e),r=s.status;if(r!==n){let a=new Date().toLocaleTimeString();if(t.info(`[${a}] Status: ${fn(r)}`),n=r,r==="Running"){t.success("Function deployment is now running!");try{let l=await o.getFunction(e);l.url&&t.info(`URL: ${V.default.blue(l.url)}`)}catch{}}else r==="Failed"&&(t.error("Function deployment failed!"),s.error&&t.error(`Error: ${s.error}`),clearInterval(i))}}catch(s){t.error(`Error checking status: ${s.message}`)}},3e3);process.on("SIGINT",()=>{clearInterval(i),t.newline(),t.info("Stopped watching function status"),process.exit(0)})}function fn(o){return{Running:V.default.green("\u2705 Running"),Failed:V.default.red("\u274C Failed"),Pending:V.default.yellow("\u23F3 Pending"),Building:V.default.blue("\u{1F528} Building")}[o]||V.default.gray(o)}gn.exports=pn});var Pn=U((gs,$n)=>{"use strict";var Se=m(require("chalk")),wn=require("commander");x();j();B();O();var ht=require("child_process"),Ne=m(require("fs")),Ue=m(require("os")),Ke=m(require("path")),yt=new wn.Command("logs");yt.description("View function logs").argument("[function-id]","Function ID to get logs for (optional if sinch.json exists)").option("-f, --follow","Follow log output in real-time").option("-n, --lines <number>","Number of historical lines to show","50").option("--level <level>","Filter by log level (debug, info, warning, error)").option("--search <text>","Search for text in log messages").option("--since <duration>","Show logs since duration (e.g., 1h, 30m, 5s)").action(async(o,e)=>{try{await p.load();let n=new I(p.getApiConfig()),i=o;if(!i){if(!p.isInProject())throw new Error("Function ID required. Provide as argument or run from function directory with sinch.json");let r=p.getProjectConfig();if(!r)throw new Error("No project configuration found");if(i=r.functionId,!i)throw new Error("No function ID found in sinch.json. Deploy the function first or provide function ID as argument.")}d.start("Loading function details...");let s=await n.getFunction(i);d.stop(),t.info(`\u{1F4CB} Logs for function: ${Se.default.cyan(s.name)} (${Lo(s.status)})`),t.newline(),e.follow?await Cn(n,i,s.name,e):await Ho(n,i,e)}catch(n){d.stop(),t.error(`Failed to get logs: ${n.message}`),process.exit(1)}});yt.command("stream").description("Stream function logs in real-time").argument("[function-id]","Function ID to stream logs for (optional if sinch.json exists)").option("--level <level>","Filter by log level (debug, info, warning, error)").option("--search <text>","Search for text in log messages").action(async(o,e)=>{try{await p.load();let n=new I(p.getApiConfig()),i=o;if(!i){if(!p.isInProject())throw new Error("Function ID required. Provide as argument or run from function directory with sinch.json");let r=p.getProjectConfig();if(!r)throw new Error("No project configuration found");if(i=r.functionId,!i)throw new Error("No function ID found in sinch.json. Deploy the function first or provide function ID as argument.")}d.start("Connecting to log stream...");let s=await _o(n,i);d.stop(),await Cn(n,i,s.name,{...e,follow:!0})}catch(n){d.stop(),t.error(`Failed to stream logs: ${n.message}`),process.exit(1)}});async function _o(o,e){return await o.getFunction(e)}async function Cn(o,e,n,i){let s=o.baseUrl.replace(/\/+$/,""),r=o.projectId,a=`${s}/v1/projects/${r}/functions/${e}/logs/stream`,l=o.credentials,c=[],u=Sn(c,"STREAMING",n),g={Accept:"text/event-stream","Cache-Control":"no-cache"};if(l)try{let C=await l.retrieve();if(C&&C.keyId&&C.keySecret){let w=Buffer.from(`${C.keyId}:${C.keySecret}`).toString("base64");g.Authorization=`Basic ${w}`}}catch(C){t.debug("Failed to add authentication:",C)}let h=new AbortController;try{let C=await fetch(a,{method:"GET",headers:g,signal:h.signal});if(!C.ok)throw new Error(`SSE connection failed: ${C.status} ${C.statusText}`);if(!C.body)throw new Error("Response body is null");hn(u.statusBar,"CONNECTED",n),u.screen.render();let w=C.body.getReader(),A=new TextDecoder,J="";(async()=>{try{for(;;){let{done:$,value:b}=await w.read();if($)break;J+=A.decode(b,{stream:!0});let S=J.split(`
|
|
57
|
-
`);J=S.pop()||"";for(let y of S)if(!y.startsWith("event:")&&y.startsWith("data:")){let v=y.substring(5).trim();if(v)try{let R=JSON.parse(v);R.type==="request"&&R.request&&(c.push(R.request),bn(
|
|
56
|
+
`,await T.default.writeFile(n,i,"utf-8"),t.debug(`Updated .env: SINCH_TUNNEL=${o}`)}}else if(e==="csharp"){let n=oe.default.join(process.cwd(),"appsettings.Development.json");if(await T.default.pathExists(n)){let i=await T.default.readJson(n);i.SinchTunnel=o,await T.default.writeJson(n,i,{spaces:2}),t.debug(`Updated appsettings.Development.json: SinchTunnel=${o}`)}}}async function Eo(o,e,n){let i=e.runtime||"node",s=!1;if(o.tunnel===!0)s=!0;else if(o.tunnel===!1)s=!1,e.tunnel?.preference==="always"&&(f.set("tunnel",{...e.tunnel,preference:"no"},!0),await f.saveProjectConfig());else if(e.tunnel?.preference==="never")s=!1;else if(To(e))s=!0;else{let{tunnelChoice:l}=await an.default.prompt([{type:"list",name:"tunnelChoice",message:"Enable Sinch tunnel for external access?",choices:[{name:"Yes - Enable tunnel this time",value:"yes"},{name:"No - Local only this time",value:"no"},{name:"Always - Enable tunnel and remember preference",value:"always"},{name:"Never - Don't enable tunnel and remember preference",value:"never"}],default:"no"}]);l==="yes"?s=!0:l==="no"?s=!1:l==="always"?(s=!0,f.set("tunnel",{...e.tunnel,preference:"always"},!0),await f.saveProjectConfig()):l==="never"&&(s=!1,f.set("tunnel",{...e.tunnel,preference:"never"},!0),await f.saveProjectConfig())}await ko(s,i);let a={...process.env,PORT:o.port,NODE_ENV:"development",SINCH_FUNCTIONS_LOCAL:"true",SINCH_TUNNEL:s?"true":"false"};e.variables&&Object.entries(e.variables).forEach(([l,p])=>{a[l]=p});try{let l=await f.getApplicationCredentials(e.voiceAppKey);l?(a.SINCH_APPLICATION_KEY=l.applicationKey,a.SINCH_APPLICATION_SECRET=l.applicationSecret,t.debug("\u2705 Injected application credentials for voice operations")):t.debug("\u26A0\uFE0F No application credentials found - voice features may not work")}catch(l){t.debug(`\u26A0\uFE0F Could not load application credentials: ${l.message}`)}t.info("\u{1F680} Starting local server...");let r=null,u=!1;function c(){if(r&&r.kill(),i==="csharp"){let l=["watch","run","--no-launch-profile"];n&&l.push("--project",n),o.port&&l.push("--urls",`http://localhost:${o.port}`),a.ASPNETCORE_ENVIRONMENT="Development",a.ASPNETCORE_URLS=`http://localhost:${o.port}`,r=(0,mt.spawn)("dotnet",l,{env:a,stdio:"inherit",cwd:process.cwd()})}else r=(0,mt.spawn)("npm",["run","dev"],{env:a,stdio:"inherit",cwd:process.cwd(),shell:!0});r.on("spawn",async()=>{if(!u){u=!0,t.newline(),t.success(`\u2705 Server running on http://localhost:${o.port}`),o.debug&&(t.newline(),i==="csharp"?jo():Io()),t.newline(),t.info("\u{1F4A1} Development commands:"),t.info(` \u2022 Test function: ${xe.default.cyan(`curl http://localhost:${o.port}`)}`),t.info(` \u2022 View in browser: ${xe.default.cyan(`http://localhost:${o.port}`)}`),t.info(` \u2022 Stop server: ${xe.default.gray("Ctrl+C")}`);let l=i==="csharp"?"dotnet watch":"nodemon";t.info(` \u2022 File watching: ${xe.default.green(`enabled (via ${l})`)}`)}}),r.on("error",l=>{t.error(`Server error: ${l.message}`)}),r.on("exit",(l,p)=>{p!=="SIGTERM"&&p!=="SIGKILL"&&t.error(`Server exited with code ${l}`)})}c(),process.on("SIGINT",()=>{t.newline(),t.info("\u{1F534} Stopping development server..."),r&&r.kill("SIGTERM"),process.exit(0)}),await new Promise(()=>{})}async function Io(){try{let o=await je("code",".vscode"),e=await je("cursor",".cursor"),n=await je("webstorm",".idea");if(o||e){let i=o?"VS Code":"Cursor",s=".vscode";if(t.info(`\u{1F41B} ${i} detected! Debug setup:`),await Ro(s))t.info(" 1. \u2705 Created .vscode/launch.json for you");else{let r=oe.default.join(process.cwd(),s,"launch.json");await T.default.pathExists(r)?t.info(" 1. \u2705 Found existing .vscode/launch.json"):t.info(" 1. \u26A0\uFE0F Could not create .vscode/launch.json")}t.info(" 2. \u{1F50D} Press F5 to attach debugger"),t.info(" 3. \u{1F534} Set breakpoints in your function.js"),t.info(" 4. \u{1F4DE} Test your function to hit breakpoints")}else n?(t.info("\u{1F41B} WebStorm detected! Debug setup:"),t.info(" 1. \u{1F50D} Run \u2192 Attach to Node.js/Chrome \u2192 localhost:9229"),t.info(" 2. \u{1F534} Set breakpoints in your function.js")):(t.info("\u{1F41B} Manual debug setup:"),t.info(' \u2022 VS Code/Cursor: Open "Run and Debug" \u2192 "Attach to Node.js Process"'),t.info(' \u2022 Chrome DevTools: Visit chrome://inspect \u2192 Click "inspect"'),t.info(" \u2022 Manual: Connect debugger to ws://localhost:9229"))}catch{t.info("\u{1F41B} Debug instructions:"),t.info(" \u2022 Connect your debugger to ws://localhost:9229"),t.info(" \u2022 Set breakpoints and test your function")}}async function je(o,e){try{if(o==="code"&&Ao())return!0;let{spawn:n}=require("child_process"),i=await new Promise(a=>{let r=n(o,["--version"],{stdio:"pipe"});r.on("close",u=>a(u===0)),r.on("error",()=>a(!1))}),s=e?await T.default.pathExists(e):!1;return i||s}catch{return!1}}function Ao(){return process.env.TERM_PROGRAM==="vscode"||!!process.env.VSCODE_IPC_HOOK||!!process.env.VSCODE_PID}async function Ro(o=".vscode"){try{let e=oe.default.join(process.cwd(),o),n=oe.default.join(e,"launch.json");if(await T.default.pathExists(n))return!1;await T.default.ensureDir(e);let i={version:"0.2.0",configurations:[{name:"Attach to Sinch Function",type:"node",request:"attach",port:9229,localRoot:"${workspaceFolder}",remoteRoot:"${workspaceFolder}",skipFiles:["<node_internals>/**","node_modules/**"]}]};return await T.default.writeJson(n,i,{spaces:2}),!!await T.default.pathExists(n)}catch{return!1}}function To(o){return o.tunnel?o.tunnel.preference==="always":!1}async function jo(){try{let o=await je("code",".vscode"),e=await je("devenv"),n=await je("rider",".idea");o?(t.info("\u{1F41B} VS Code detected! Debug setup:"),await Do(".vscode")?t.info(" 1. \u2705 Created .vscode/launch.json for C#"):t.info(" 1. \u2705 Found existing .vscode/launch.json"),t.info(" 2. \u{1F50D} Press F5 to attach debugger"),t.info(" 3. \u{1F534} Set breakpoints in your Function.cs"),t.info(" 4. \u{1F4DE} Test your function to hit breakpoints")):e?(t.info("\u{1F41B} Visual Studio detected! Debug setup:"),t.info(" 1. \u{1F50D} Debug \u2192 Attach to Process \u2192 dotnet.exe"),t.info(" 2. \u{1F534} Set breakpoints in your Function.cs"),t.info(" 3. \u{1F4DE} Test your function to hit breakpoints")):n?(t.info("\u{1F41B} JetBrains Rider detected! Debug setup:"),t.info(" 1. \u{1F50D} Run \u2192 Attach to Process \u2192 dotnet"),t.info(" 2. \u{1F534} Set breakpoints in your Function.cs")):(t.info("\u{1F41B} C# Debug setup:"),t.info(" \u2022 Visual Studio: Debug \u2192 Attach to Process \u2192 dotnet.exe"),t.info(" \u2022 VS Code: Install C# extension, then F5 to debug"),t.info(" \u2022 Rider: Run \u2192 Attach to Process"))}catch{t.info("\u{1F41B} C# Debug instructions:"),t.info(" \u2022 Attach your debugger to the dotnet process"),t.info(" \u2022 Set breakpoints in Function.cs")}}async function Do(o=".vscode"){try{let e=oe.default.join(process.cwd(),o),n=oe.default.join(e,"launch.json");if(await T.default.pathExists(n))return!1;await T.default.ensureDir(e);let i={version:"0.2.0",configurations:[{name:".NET Core Launch (web)",type:"coreclr",request:"launch",preLaunchTask:"build",program:"${workspaceFolder}/bin/Debug/net8.0/Function.dll",args:[],cwd:"${workspaceFolder}",stopAtEntry:!1,serverReadyAction:{action:"openExternally",pattern:"\\bNow listening on:\\s+(https?://\\S+)"},env:{ASPNETCORE_ENVIRONMENT:"Development"},sourceFileMap:{"/Views":"${workspaceFolder}/Views"}},{name:".NET Core Attach",type:"coreclr",request:"attach"}]};await T.default.writeJson(n,i,{spaces:2});let s=oe.default.join(e,"tasks.json");if(!await T.default.pathExists(s)){let a={version:"2.0.0",tasks:[{label:"build",command:"dotnet",type:"process",args:["build","${workspaceFolder}/Function.csproj","/property:GenerateFullPaths=true","/consoleloggerparameters:NoSummary"],problemMatcher:"$msCompile"}]};await T.default.writeJson(s,a,{spaces:2})}return await T.default.pathExists(n)}catch{return!1}}ln.exports=cn});var mn=U((ls,gn)=>{"use strict";var V=h(require("chalk")),dn=require("commander");x();j();B();O();var pn=new dn.Command("status");pn.description("Show function status and details").argument("[function-id]","Function ID to check (optional if sinch.json exists)").option("-f, --follow","Watch status changes in real-time").option("--json","Output raw JSON").action(async(o,e)=>{try{await f.load();let n=new I(f.getApiConfig()),i=o;if(!i){if(!f.isInProject())throw new Error("Function ID required. Provide as argument or run from function directory with sinch.json");if(i=f.getProjectConfig()?.functionId,!i)throw new Error("No function ID found in sinch.json. Deploy the function first or provide function ID as argument.")}e.follow?await Oo(n,i):await Fo(n,i,e)}catch(n){d.stop(),t.error(`Failed to get function status: ${n.message}`),process.exit(1)}});async function Fo(o,e,n){d.start("\u{1F4E1} Loading function status...");try{let i=await o.getFunction(e),s=await o.getFunctionStatus(e);if(d.stop(),n.json){console.log(JSON.stringify({function:i,deployment:s},null,2));return}let a=i,r=s.status,u=s.error;t.newline(),t.title(`Function Status: ${a.name}`),t.newline(),t.info("\u{1F4CB} Function Details:"),t.info(` ID: ${V.default.gray(a.id)}`),t.info(` Name: ${V.default.cyan(a.name)}`),t.info(` Runtime: ${V.default.yellow(a.runtime)}`),t.info(` Deployment Status: ${fn(r)}`),a.created&&t.info(` Created: ${new Date(a.created).toLocaleString()}`),a.updated&&t.info(` Updated: ${new Date(a.updated).toLocaleString()}`),a.url&&t.info(` URL: ${V.default.blue(a.url)}`),r==="Failed"&&u&&(t.newline(),t.error("Deployment Error:"),t.error(` ${u}`)),t.newline(),t.info("\u{1F4A1} Commands:"),t.info(` \u2022 View logs: ${V.default.cyan(`sinch functions logs ${e}`)}`),t.info(` \u2022 Redeploy: ${V.default.cyan("sinch functions deploy")}`),t.info(` \u2022 Delete: ${V.default.cyan(`sinch functions delete ${e}`)}`)}catch(i){throw d.stop(),i}}async function Oo(o,e){t.info("\u{1F440} Watching deployment status (press Ctrl+C to stop)..."),t.newline();let n=null,i=setInterval(async()=>{try{let s=await o.getFunctionStatus(e),a=s.status;if(a!==n){let r=new Date().toLocaleTimeString();if(t.info(`[${r}] Status: ${fn(a)}`),n=a,a==="Running"){t.success("Function deployment is now running!");try{let u=await o.getFunction(e);u.url&&t.info(`URL: ${V.default.blue(u.url)}`)}catch{}}else a==="Failed"&&(t.error("Function deployment failed!"),s.error&&t.error(`Error: ${s.error}`),clearInterval(i))}}catch(s){t.error(`Error checking status: ${s.message}`)}},3e3);process.on("SIGINT",()=>{clearInterval(i),t.newline(),t.info("Stopped watching function status"),process.exit(0)})}function fn(o){return{Running:V.default.green("\u2705 Running"),Failed:V.default.red("\u274C Failed"),Pending:V.default.yellow("\u23F3 Pending"),Building:V.default.blue("\u{1F528} Building")}[o]||V.default.gray(o)}gn.exports=pn});var Pn=U((gs,$n)=>{"use strict";var Se=h(require("chalk")),wn=require("commander");x();j();B();O();var ht=require("child_process"),Ne=h(require("fs")),Ue=h(require("os")),Ke=h(require("path")),yt=new wn.Command("logs");yt.description("View function logs").argument("[function-id]","Function ID to get logs for (optional if sinch.json exists)").option("-f, --follow","Follow log output in real-time").option("-n, --lines <number>","Number of historical lines to show","50").option("--level <level>","Filter by log level (debug, info, warning, error)").option("--search <text>","Search for text in log messages").option("--since <duration>","Show logs since duration (e.g., 1h, 30m, 5s)").action(async(o,e)=>{try{await f.load();let n=new I(f.getApiConfig()),i=o;if(!i){if(!f.isInProject())throw new Error("Function ID required. Provide as argument or run from function directory with sinch.json");let a=f.getProjectConfig();if(!a)throw new Error("No project configuration found");if(i=a.functionId,!i)throw new Error("No function ID found in sinch.json. Deploy the function first or provide function ID as argument.")}d.start("Loading function details...");let s=await n.getFunction(i);d.stop(),t.info(`\u{1F4CB} Logs for function: ${Se.default.cyan(s.name)} (${Lo(s.status)})`),t.newline(),e.follow?await Cn(n,i,s.name,e):await Ho(n,i,e)}catch(n){d.stop(),t.error(`Failed to get logs: ${n.message}`),process.exit(1)}});yt.command("stream").description("Stream function logs in real-time").argument("[function-id]","Function ID to stream logs for (optional if sinch.json exists)").option("--level <level>","Filter by log level (debug, info, warning, error)").option("--search <text>","Search for text in log messages").action(async(o,e)=>{try{await f.load();let n=new I(f.getApiConfig()),i=o;if(!i){if(!f.isInProject())throw new Error("Function ID required. Provide as argument or run from function directory with sinch.json");let a=f.getProjectConfig();if(!a)throw new Error("No project configuration found");if(i=a.functionId,!i)throw new Error("No function ID found in sinch.json. Deploy the function first or provide function ID as argument.")}d.start("Connecting to log stream...");let s=await _o(n,i);d.stop(),await Cn(n,i,s.name,{...e,follow:!0})}catch(n){d.stop(),t.error(`Failed to stream logs: ${n.message}`),process.exit(1)}});async function _o(o,e){return await o.getFunction(e)}async function Cn(o,e,n,i){let s=o.baseUrl.replace(/\/+$/,""),a=o.projectId,r=`${s}/v1/projects/${a}/functions/${e}/logs/stream`,u=o.credentials,c=[],l=Sn(c,"STREAMING",n),p={Accept:"text/event-stream","Cache-Control":"no-cache"};if(u)try{let C=await u.retrieve();if(C&&C.keyId&&C.keySecret){let w=Buffer.from(`${C.keyId}:${C.keySecret}`).toString("base64");p.Authorization=`Basic ${w}`}}catch(C){t.debug("Failed to add authentication:",C)}let m=new AbortController;try{let C=await fetch(r,{method:"GET",headers:p,signal:m.signal});if(!C.ok)throw new Error(`SSE connection failed: ${C.status} ${C.statusText}`);if(!C.body)throw new Error("Response body is null");hn(l.statusBar,"CONNECTED",n),l.screen.render();let w=C.body.getReader(),A=new TextDecoder,J="";(async()=>{try{for(;;){let{done:P,value:b}=await w.read();if(P)break;J+=A.decode(b,{stream:!0});let S=J.split(`
|
|
57
|
+
`);J=S.pop()||"";for(let y of S)if(!y.startsWith("event:")&&y.startsWith("data:")){let v=y.substring(5).trim();if(v)try{let R=JSON.parse(v);R.type==="request"&&R.request&&(c.push(R.request),bn(l.table,R.request,c),l.table.focus(),l.screen.render())}catch{}}}}catch(P){P.name!=="AbortError"&&(hn(l.statusBar,"RECONNECTING",n),l.screen.render())}})(),l.screen.key(["q","C-c"],()=>{m.abort(),process.exit(0)}),await new Promise(()=>{})}catch(C){m.abort(),t.error(`\u274C Streaming failed: ${C.message}`),process.exit(1)}}function Lo(o){return{Running:Se.default.green("\u2705 Running"),Failed:Se.default.red("\u274C Failed"),Pending:Se.default.yellow("\u23F3 Pending"),Building:Se.default.blue("\u{1F528} Building")}[o]||Se.default.gray(o)}var ve=[];function bn(o,e,n){let i=new Date(e.startTime),s=i.getFullYear()+"-"+String(i.getMonth()+1).padStart(2,"0")+"-"+String(i.getDate()).padStart(2,"0")+" "+String(i.getHours()).padStart(2,"0")+":"+String(i.getMinutes()).padStart(2,"0")+":"+String(i.getSeconds()).padStart(2,"0"),a=Mo(e),r=`${e.executionTimeMs}ms`,u=e.statusCode.toString(),c=process.stdout.columns||120,p=Math.max(30,c-35),m=e.url.length>p?e.url.substring(0,p-2)+"..":e.url;ve.push([s,a,r,u,m]),ve.length>100&&(ve=ve.slice(-100),n&&n.length>100&&n.splice(0,n.length-100));let C=[["Time","Callback","Duration","Status","Path"],...ve];o.setData(C)}function xo(o,e,n,i,s){try{let a=require("blessed");t.debug(`Showing request details for ${o.httpMethod} ${o.url}`);let r=a.box({parent:e,top:0,left:0,width:"100%",height:"100%",border:{type:"line"},style:{border:{fg:"cyan"},bg:"black",fg:"white"},scrollable:!0,alwaysScroll:!0,keys:!0,vi:!0,tags:!0,label:" Request Details "}),u=a.box({parent:r,top:1,left:2,width:"100%-4",height:1,content:"{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J/1] JSON [C/2] cURL{/}",tags:!0,style:{bg:"blue",fg:"white"}});a.box({parent:r,top:2,left:2,width:"100%-4",height:1,content:`{bold}{cyan-fg}${o.httpMethod}{/} {blue-fg}${o.url}{/} - {${Vo(o.statusCode)}}${o.statusCode}{/} - {yellow-fg}${o.executionTimeMs}ms{/} - {magenta-fg}${o.memoryUsedMB||0}MB{/}`,tags:!0,style:{bg:"black"}});let c=a.box({parent:r,top:4,left:2,width:"100%-4",height:"100%-5",scrollable:!0,alwaysScroll:!0,keys:!0,vi:!0,tags:!0,content:No(o)});c.focus(),e.render();let l=!0,p=()=>{l&&(l=!1,r.destroy(),n.focus(),e.render())};e.key(["escape","q"],()=>{l&&p()}),e.key(["up","k"],()=>{l&&(c.scroll(-1),e.render())}),e.key(["down","j"],()=>{l&&(c.scroll(1),e.render())}),e.on("keypress",(m,C)=>{l&&t.debug(`Key pressed: ch="${m}" key=${JSON.stringify(C)}`)}),e.key(["J","j"],()=>{l&&(t.debug("J/j key pressed - attempting JSON copy"),u.setContent("{black-bg}{yellow-fg} J KEY PRESSED - COPYING JSON... {/}"),e.render(),setTimeout(()=>{try{let m=JSON.stringify(o,null,2);t.debug(`JSON content length: ${m.length}`),t.debug("Attempting native clipboard copy"),ze(m).then(()=>{u.setContent("{green-fg}\u2713 Request JSON copied to clipboard!{/}"),t.debug("Native clipboard copy succeeded"),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}).catch(C=>{t.debug(`Native clipboard failed: ${C.message}`);let w=Ke.default.join(Ue.default.tmpdir(),`sinch-request-${Date.now()}.json`);Ne.default.writeFileSync(w,m),u.setContent(`{yellow-fg}\u2713 JSON saved to: ${w}{/}`),t.debug(`Saved to temp file: ${w}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)})}catch(m){t.debug(`JSON copy error: ${m.message}`),u.setContent(`{red-fg}\u2717 Copy failed: ${m.message}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}},100))}),e.key(["C","c"],()=>{l&&(t.debug("C/c key pressed - attempting cURL copy"),u.setContent("{black-bg}{yellow-fg} C KEY PRESSED - COPYING CURL... {/}"),e.render(),setTimeout(()=>{try{let m=yn(o);t.debug("Attempting native clipboard copy for cURL"),ze(m).then(()=>{u.setContent("{green-fg}\u2713 cURL command copied to clipboard!{/}"),t.debug("Native clipboard copy succeeded for cURL"),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}).catch(C=>{t.debug(`Native clipboard failed for cURL: ${C.message}`);let w=Ke.default.join(Ue.default.tmpdir(),`sinch-curl-${Date.now()}.sh`);Ne.default.writeFileSync(w,m),u.setContent(`{yellow-fg}\u2713 cURL saved to: ${w}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)})}catch(m){t.debug(`cURL copy error: ${m.message}`),u.setContent(`{red-fg}\u2717 Copy failed: ${m.message}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}},100))}),e.key(["1"],()=>{l&&(t.debug("1 key pressed - copying JSON (alternative binding)"),u.setContent("{black-bg}{yellow-fg} 1 KEY - COPYING JSON... {/}"),e.render(),setTimeout(()=>{try{let m=JSON.stringify(o,null,2);ze(m).then(()=>{u.setContent("{green-fg}\u2713 Request JSON copied to clipboard!{/}"),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}).catch(C=>{let w=Ke.default.join(Ue.default.tmpdir(),`sinch-request-${Date.now()}.json`);Ne.default.writeFileSync(w,m),u.setContent(`{yellow-fg}\u2713 JSON saved to: ${w}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)})}catch(m){u.setContent(`{red-fg}\u2717 Copy failed: ${m.message}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}},100))}),e.key(["2"],()=>{l&&(t.debug("2 key pressed - copying cURL (alternative binding)"),u.setContent("{black-bg}{yellow-fg} 2 KEY - COPYING CURL... {/}"),e.render(),setTimeout(()=>{try{let m=yn(o);ze(m).then(()=>{u.setContent("{green-fg}\u2713 cURL command copied to clipboard!{/}"),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}).catch(C=>{let w=Ke.default.join(Ue.default.tmpdir(),`sinch-curl-${Date.now()}.sh`);Ne.default.writeFileSync(w,m),u.setContent(`{yellow-fg}\u2713 cURL saved to: ${w}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)})}catch(m){u.setContent(`{red-fg}\u2717 Copy failed: ${m.message}{/}`),e.render(),setTimeout(()=>{l&&(u.setContent("{gray-fg}[Esc/Q] Close [\u2191\u2193] Scroll [J] JSON [C] cURL{/}"),e.render())},3e3)}},100))})}catch(a){t.debug(`Error in showBlessedZoomedRequest: ${a.message}`)}}function No(o){let e="";return e+=`
|
|
58
58
|
`,e+=Uo(o),e+=`
|
|
59
59
|
`,e+=Ko(o),e+=`
|
|
60
60
|
`,e+=Bo(o),e}function Uo(o){let e="",n=process.stdout.columns-6;e+="{bold}{green-fg}\u250C\u2500 REQUEST "+"\u2500".repeat(Math.max(0,n-10))+`\u2510{/}
|
|
61
61
|
`;let i=Jo(o);if(i&&(e+=`{green-fg}\u2502{/} {bold}Call ID:{/} {cyan-fg}${i}{/}
|
|
62
62
|
`),o.headers){e+=`{green-fg}\u2502{/} {bold}Headers:{/}
|
|
63
|
-
`;try{let s=typeof o.headers=="string"?JSON.parse(o.headers):o.headers;Object.entries(s).forEach(([r
|
|
63
|
+
`;try{let s=typeof o.headers=="string"?JSON.parse(o.headers):o.headers;Object.entries(s).forEach(([a,r])=>{let u=` ${a}: ${r}`;e+=ie(u,n-2,"{green-fg}\u2502{/} ")})}catch{e+=ie(` ${o.headers}`,n-2,"{green-fg}\u2502{/} ")}}if(o.requestBody){e+=`{green-fg}\u2502{/} {bold}Body:{/}
|
|
64
64
|
`;try{let s=JSON.parse(o.requestBody);JSON.stringify(s,null,2).split(`
|
|
65
|
-
`).forEach(
|
|
65
|
+
`).forEach(r=>{e+=ie(r,n-2,"{green-fg}\u2502{/} ")})}catch{e+=ie(o.requestBody,n-2,"{green-fg}\u2502{/} ")}}return e+="{green-fg}\u2514"+"\u2500".repeat(Math.max(0,n))+`\u2518{/}
|
|
66
66
|
`,e}function Ko(o){let e="",n=process.stdout.columns-6;if(e+="{bold}{blue-fg}\u250C\u2500 RESPONSE "+"\u2500".repeat(Math.max(0,n-11))+`\u2510{/}
|
|
67
67
|
`,o.responseHeaders){e+=`{blue-fg}\u2502{/} {bold}Headers:{/}
|
|
68
|
-
`;try{let i=typeof o.responseHeaders=="string"?JSON.parse(o.responseHeaders):o.responseHeaders;Object.entries(i).forEach(([s,
|
|
68
|
+
`;try{let i=typeof o.responseHeaders=="string"?JSON.parse(o.responseHeaders):o.responseHeaders;Object.entries(i).forEach(([s,a])=>{let r=` ${s}: ${a}`;e+=ie(r,n-2,"{blue-fg}\u2502{/} ")})}catch{e+=ie(` ${o.responseHeaders}`,n-2,"{blue-fg}\u2502{/} ")}}if(o.responseBody){e+=`{blue-fg}\u2502{/} {bold}Body:{/}
|
|
69
69
|
`;try{let i=JSON.parse(o.responseBody);JSON.stringify(i,null,2).split(`
|
|
70
|
-
`).forEach(
|
|
70
|
+
`).forEach(a=>{e+=ie(a,n-2,"{blue-fg}\u2502{/} ")})}catch{e+=ie(o.responseBody,n-2,"{blue-fg}\u2502{/} ")}}return o.errorMessage&&(e+=`{blue-fg}\u2502{/} {bold}{red-fg}Error:{/}
|
|
71
71
|
`,e+=ie(o.errorMessage,n-2,"{blue-fg}\u2502{/} ")),e+="{blue-fg}\u2514"+"\u2500".repeat(Math.max(0,n))+`\u2518{/}
|
|
72
72
|
`,e}function Bo(o){let e="",n=process.stdout.columns-6;return e+="{bold}{magenta-fg}\u250C\u2500 CONSOLE LOGS "+"\u2500".repeat(Math.max(0,n-15))+`\u2510{/}
|
|
73
|
-
`,o.logs&&o.logs.length>0?o.logs.forEach((i,s)=>{let
|
|
73
|
+
`,o.logs&&o.logs.length>0?o.logs.forEach((i,s)=>{let a=new Date(i.timestamp).toLocaleTimeString(),r=i.level.toUpperCase().padEnd(5),u=qo(i.level),c=`${a} [${r}] ${i.message}`;e+=ie(c,n-2,"{magenta-fg}\u2502{/} ",u)}):e+=`{magenta-fg}\u2502{/} {gray-fg}No console logs for this request{/}
|
|
74
74
|
`,e+="{magenta-fg}\u2514"+"\u2500".repeat(Math.max(0,n))+`\u2518{/}
|
|
75
75
|
`,e}function ie(o,e,n,i=""){if(!o)return"";let s="";return o.split(`
|
|
76
|
-
`).forEach(
|
|
77
|
-
`;else{let
|
|
78
|
-
`,
|
|
79
|
-
`)}}),s}function qo(o){switch(o.toLowerCase()){case"debug":return"gray-fg";case"info":return"blue-fg";case"warning":return"yellow-fg";case"error":return"red-fg";default:return"white-fg"}}function Vo(o){return o>=200&&o<300?"green-fg":o>=300&&o<400?"yellow-fg":o>=400&&o<500?"red-fg":o>=500?"red-fg}{bold":"white-fg"}function Jo(o){try{if(o.requestBody){let e=JSON.parse(o.requestBody);return e.callId||e.callid||e.call_id||null}}catch{}return null}function Mo(o){try{let e="";if(o.requestBody){let n=JSON.parse(o.requestBody);if(n.event)e=n.event.toLowerCase();else{let i=o.url.split("/").filter(s=>s);e=i[i.length-1]||""}return e||""}}catch{}return""}async function Ho(o,e,n){try{d.start(`Loading ${n.lines} recent log entries...`);let i={limit:parseInt(n.lines||"50"),level:n.level,search:n.search};if(n.since){let
|
|
80
|
-
-H "${
|
|
81
|
-
-d '${JSON.stringify(
|
|
76
|
+
`).forEach(r=>{if(r.length<=e)s+=`${n}${i}${r}{/}
|
|
77
|
+
`;else{let u=r,c=!0;for(;u.length>e;){let l=e-(c?0:4),p=u.substring(0,l);s+=`${n}${c?"":" "}${i}${p}{/}
|
|
78
|
+
`,u=u.substring(l),c=!1}u.length>0&&(s+=`${n}${c?"":" "}${i}${u}{/}
|
|
79
|
+
`)}}),s}function qo(o){switch(o.toLowerCase()){case"debug":return"gray-fg";case"info":return"blue-fg";case"warning":return"yellow-fg";case"error":return"red-fg";default:return"white-fg"}}function Vo(o){return o>=200&&o<300?"green-fg":o>=300&&o<400?"yellow-fg":o>=400&&o<500?"red-fg":o>=500?"red-fg}{bold":"white-fg"}function Jo(o){try{if(o.requestBody){let e=JSON.parse(o.requestBody);return e.callId||e.callid||e.call_id||null}}catch{}return null}function Mo(o){try{let e="";if(o.requestBody){let n=JSON.parse(o.requestBody);if(n.event)e=n.event.toLowerCase();else{let i=o.url.split("/").filter(s=>s);e=i[i.length-1]||""}return e||""}}catch{}return""}async function Ho(o,e,n){try{d.start(`Loading ${n.lines} recent log entries...`);let i={limit:parseInt(n.lines||"50"),level:n.level,search:n.search};if(n.since){let r=Wo(n.since);r&&(i.startTime=r.toISOString())}let s=await o.getFunctionLogs(e,i);if(d.stop(),t.debug("Historical API response:",{totalRequests:s.requests?.length||0,firstRequest:s.requests?.[0]||"No requests",responseKeys:Object.keys(s)}),!s.requests||s.requests.length===0){t.info("\u{1F4DD} No logs found"),t.info("\u{1F4A1} Logs will appear here after function receives requests");return}let a=s.requests;t.debug("Historical requests:",{totalRequests:a.length,firstRequest:a[0]||"No requests",requestTimestamps:a.slice(0,3).map(r=>r.startTime)}),await Go(a,"HISTORICAL","Function")}catch(i){throw d.stop(),i}}function Wo(o){if(!o)return null;let e=o.match(/^(\d+)([smhd])$/);if(!e)return null;let n=parseInt(e[1]),i=e[2],s=new Date;switch(i){case"s":return new Date(s.getTime()-n*1e3);case"m":return new Date(s.getTime()-n*60*1e3);case"h":return new Date(s.getTime()-n*60*60*1e3);case"d":return new Date(s.getTime()-n*24*60*60*1e3);default:return null}}async function Go(o,e,n){let i=Sn(o,e,n);o.forEach(s=>{bn(i.table,s,o)}),i.screen.render(),await new Promise(()=>{})}function Sn(o,e,n){let i=require("blessed");process.stdout.write("\x1Bc"),ve=[];let s=i.screen({smartCSR:!0,title:`Sinch Functions - ${n} Logs`,fullUnicode:!0}),a=i.box({parent:s,top:0,left:0,width:"100%",height:1,content:vn(e,n),tags:!0,style:{bg:"black"}}),r=i.listtable({parent:s,top:1,left:0,width:"100%",height:"100%-1",border:{type:"line",fg:"blue"},style:{header:{fg:"white",bg:"blue",bold:!0},cell:{fg:"white"},selected:{bg:"blue",fg:"white",bold:!0}},keys:!0,vi:!0,mouse:!0,interactive:!0,label:`${n} Logs (q to quit)`,align:"left",pad:1}),u=["Time","Callback","Duration","Status","Path"];r.setData([u]),r.focus(),s.key(["q","C-c"],()=>{process.exit(0)});let c=()=>{try{let l=r.selected||0,p=l-1;if(p>=0&&p<o.length&&o[p])t.debug(`Opening request details for index ${p}`),xo(o[p],s,r,a,n);else{let m=`Selected: ${l}, DataIndex: ${p}, Requests: ${o.length}, TableData: ${ve.length}`;t.debug(`Selection out of bounds: ${m}`)}}catch(l){t.debug(`Error in request selection: ${l.message}`)}};return s.key(["enter"],c),r.on("select",(l,p)=>{c()}),s.on("wheelup",()=>{r.focused&&(r.scroll(-1),s.render())}),s.on("wheeldown",()=>{r.focused&&(r.scroll(1),s.render())}),{screen:s,table:r,statusBar:a}}function vn(o,e){switch(o){case"STREAMING":return"{blue-fg}\u{1F534} STREAMING: "+e+"{/} {gray-fg}| \u2191\u2193/Wheel=scroll | Enter/Click=details | Q=quit{/}";case"CONNECTED":return"{green-fg}\u2705 CONNECTED: "+e+"{/} {gray-fg}| \u2191\u2193/Wheel=scroll | Enter/Click=details | Q=quit{/}";case"RECONNECTING":return"{yellow-fg}\u26A0\uFE0F RECONNECTING: "+e+"{/} {gray-fg}| \u2191\u2193/Wheel=scroll | Enter/Click=details | Q=quit{/}";case"HISTORICAL":return"{cyan-fg}\u{1F4DC} HISTORICAL: "+e+"{/} {gray-fg}| \u2191\u2193/Wheel=scroll | Enter/Click=details | Q=quit{/}";default:return"{gray-fg}"+e+" | \u2191\u2193/Wheel=scroll | Enter/Click=details | Q=quit{/}"}}function hn(o,e,n){o.setContent(vn(e,n))}function ze(o){return new Promise((e,n)=>{let i,s;process.platform==="win32"?(i="clip",s=[]):process.platform==="darwin"?(i="pbcopy",s=[]):(i="xclip",s=["-selection","clipboard"]),t.debug(`Using clipboard command: ${i} with args:`,s);let a=(0,ht.spawn)(i,s,{stdio:["pipe","ignore","pipe"]}),r="";a.stderr.on("data",u=>{r+=u.toString()}),a.on("error",u=>{if(t.debug(`Clipboard process error: ${u.message}`),process.platform==="linux"&&i==="xclip"){t.debug("Trying xsel as fallback");let c=(0,ht.spawn)("xsel",["--clipboard","--input"],{stdio:["pipe","ignore","pipe"]});c.on("error",l=>{n(new Error(`No clipboard utility found: ${u.message} / ${l.message}`))}),c.on("close",l=>{l===0?e():n(new Error(`xsel failed with code ${l}`))}),c.stdin&&(c.stdin.write(o),c.stdin.end());return}n(u)}),a.on("close",u=>{u===0?(t.debug("Clipboard copy successful"),e()):(t.debug(`Clipboard process failed with code ${u}, error: ${r}`),n(new Error(`Clipboard command failed with code ${u}: ${r}`)))}),a.stdin&&(a.stdin.write(o),a.stdin.end())})}function yn(o){let e=process.platform==="win32",n=`curl -X ${o.httpMethod}`,i={};if(o.headers)try{i=typeof o.headers=="string"?JSON.parse(o.headers):o.headers}catch{}let s=o.url;if(s&&!s.startsWith("http")){let a=i.host||i.Host;a&&(s=`${a.includes("localhost")||a.includes("127.0.0.1")?"http":"https"}://${a}${s.startsWith("/")?s:"/"+s}`)}if(n+=` "${s}"`,Object.entries(i).forEach(([a,r])=>{let u=["content-length","connection","user-agent"];o.url.startsWith("http")||u.push("host"),u.includes(a.toLowerCase())||(e?n+=` -H "${a}: ${r}"`:n+=` \\
|
|
80
|
+
-H "${a}: ${r}"`)}),o.requestBody&&["POST","PUT","PATCH"].includes(o.httpMethod)){try{let a=JSON.parse(o.requestBody),r=JSON.stringify(a);e?n+=` -d '${r.replace(/'/g,"\\'")}'`:n+=` \\
|
|
81
|
+
-d '${JSON.stringify(a,null,2)}'`}catch{e?n+=` -d '${o.requestBody.replace(/'/g,"\\'")}'`:n+=` \\
|
|
82
82
|
-d '${o.requestBody}'`}n.toLowerCase().includes("content-type")||(e?n+=' -H "Content-Type: application/json"':n+=` \\
|
|
83
83
|
-H "Content-Type: application/json"`)}return e?n+=" -v":n+=` \\
|
|
84
|
-
-v`,n}$n.exports=yt});var Rn=U((Cs,An)=>{"use strict";var M=m(require("chalk")),kn=m(require("inquirer")),En=require("commander");x();j();B();O();var In=new En.Command("delete");In.alias("del").description("Delete a function").argument("<function-id>","Function ID to delete").option("-f, --force","Skip confirmation").action(async(o,e)=>{try{await p.load();let n=new I(p.getApiConfig());d.start("Loading function details...");let i=await n.getFunction(o);if(d.stop(),t.newline(),t.info("\u{1F5D1}\uFE0F Function to delete:"),t.info(` Name: ${M.default.cyan(i.name)}`),t.info(` ID: ${M.default.gray(i.id)}`),t.info(` Runtime: ${M.default.yellow(i.runtime)}`),t.info(` Status: ${Yo(i.status)}`),t.info(` Created: ${new Date(i.createdAt).toLocaleString()}`),i.containerAppUrl&&t.info(` URL: ${M.default.blue(i.containerAppUrl)}`),!e.force){t.newline(),t.warn("\u26A0\uFE0F This action cannot be undone!");let{confirm:s}=await kn.default.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete function '${i.name}'?`,default:!1}]);if(!s){t.info("Deletion cancelled");return}}d.start("Deleting function..."),await n.deleteFunction(o),d.succeed(`Function '${i.name}' deleted successfully`),p.isInProject()&&p.getProjectConfig()?.functionId===o&&(p.set("functionId",void 0,!0),await p.saveProjectConfig(),t.newline(),t.info("\u{1F4A1} Removed function ID from sinch.json"),t.info(" Deploy again with: sinch functions deploy")),t.newline(),t.info("\u{1F4A1} Next steps:"),t.info(` \u2022 List remaining functions: ${M.default.cyan("sinch functions list")}`),t.info(` \u2022 Deploy new function: ${M.default.cyan("sinch functions deploy")}`)}catch(n){d.stop(),n.message.includes("404")||n.message.includes("not found")?(t.error(`Function '${o}' not found`),t.info("\u{1F4A1} List available functions with:"),t.info(` ${M.default.cyan("sinch functions list")}`)):t.error(`Failed to delete function: ${n.message}`),process.exit(1)}});function Yo(o){return{Running:M.default.green("\u2705 Running"),Failed:M.default.red("\u274C Failed"),Pending:M.default.yellow("\u23F3 Pending"),Building:M.default.blue("\u{1F528} Building")}[o]||M.default.gray(o)}An.exports=In});var Dn=U((ks,jn)=>{"use strict";var Tn=require("commander"),wt=m(require("fs-extra")),Ct=m(require("path")),$e=m(require("chalk"));j();B();O();pt();x();var bt=new Tn.Command("docs");bt.description("Generate documentation for voice functions (saves to README.md)");bt.option("-f, --fresh","Force regeneration (skip cache)").option("-u, --update","Update documentation for deployed function via API").action(async o=>{try{await p.load(),o.update?await Qo():await zo(o)}catch(e){d.fail("\u274C Failed to generate documentation"),e.message.includes("No function file found")?t.error("No function file found. Make sure you're in a function directory with function.js, index.js, or handler.js"):e.message.includes("unauthorized")||e.message.includes("401")?t.error("Authentication failed. Run `sinch auth login` first."):e.message.includes("AI service")?t.error("AI documentation service unavailable. Please try again later."):e.message.includes("Function not found")||e.message.includes("404")?t.error("Function not found. Make sure the function is deployed first."):t.error(`Error: ${e.message}`),t.debug("Full error:",e),process.exit(1)}});async function zo(o){d.start("\u{1F916} Generating documentation...");let e=await ut();d.succeed("\u2705 Documentation generated!"),await dt(e,"README.md"),await Zo()}async function Qo(){let o=Ct.default.basename(process.cwd());d.start("\u{1F4D6} Reading local README.md...");let e=Ct.default.join(process.cwd(),"README.md");if(!await wt.default.pathExists(e))throw new Error("README.md not found. Run `sinch functions docs` first to generate documentation locally.");if(!(await wt.default.readFile(e,"utf8")).trim())throw new Error("README.md is empty. Run `sinch functions docs` first to generate documentation.");d.text="\u{1F50D} Finding deployed function...";let r=(await new I(p.getApiConfig()).listFunctions()).find(a=>a.name===o);if(!r)throw new Error(`Function '${o}' not found in project. Make sure it's deployed first.`);d.text="\u{1F4E4} Uploading documentation content...",t.info("Documentation content ready for update"),d.succeed("\u2705 Documentation updated!"),t.newline(),t.success(`\u{1F4C4} Documentation updated for deployed function: ${$e.default.cyan(o)}`),t.info(""),t.info("\u2728 Your function documentation has been updated:"),t.info(` \u2022 Function ID: ${$e.default.gray(r.id)}`),t.info(` \u2022 Source: ${$e.default.gray("Local README.md")}`),t.info(` \u2022 Updated: ${$e.default.gray(new Date().toLocaleString())}`),t.info(` \u2022 View in dashboard: ${$e.default.cyan("Dashboard \u2192 Functions \u2192 "+o)}`),t.newline(),t.info("\u{1F4A1} The updated documentation is now available in the dashboard!")}async function Zo(){t.newline(),t.success(`\u{1F4C4} Documentation updated in: ${$e.default.cyan("README.md")}`),t.info(""),t.info("\u2728 Your function documentation is ready:"),t.info(" \u2022 Review and edit the AI-generated content as needed"),t.info(" \u2022 Sinch-themed diagrams will render in markdown viewers"),t.info(" \u2022 File is ready for version control and deployment"),t.newline(),t.info("\u{1F4A1} Popular markdown viewers:"),t.info(" \u2022 VS Code (built-in)"),t.info(" \u2022 GitHub (drag & drop file)"),t.info(" \u2022 Typora, Mark Text, or any markdown app")}jn.exports=bt});var xn=U((Ts,Ln)=>{"use strict";var _=m(require("chalk")),St=m(require("inquirer")),Fn=require("commander"),Z=m(require("fs-extra")),de=m(require("path")),On=m(require("adm-zip"));x();j();B();O();var _n=new Fn.Command("download");_n.description("Download function source code").argument("[function-id]","Function ID to download (ULID format)").option("-o, --output <dir>","Output directory (default: ./functions/<function-name>)").option("--no-extract","Keep as ZIP file without extracting").option("--non-interactive","Skip interactive selection").option("-f, --force","Overwrite existing directory without prompting").action(async(o,e)=>{try{await p.load();let n=new I(p.getApiConfig()),i=o;if(!i&&!e.nonInteractive){let u=await Xo(n);if(!u){t.info("Download cancelled");return}i=u}i||(t.error("Function ID required. Provide as argument or select interactively"),t.info(`Usage: ${_.default.cyan("sinch functions download 01HX3KC5V8G3KCNZ8S5Y9ABCDE")}`),t.info(` or: ${_.default.cyan("sinch functions download")} (interactive selection)`),process.exit(1)),d.start("\u{1F4E1} Fetching function metadata...");let s=await n.getFunction(i);d.succeed("Function metadata loaded");let r=de.join("functions",s.name),a=e.output||r,l=de.resolve(a);if(await Z.pathExists(l)){if(!e.force){let{overwrite:u}=await St.default.prompt([{type:"confirm",name:"overwrite",message:`Directory '${a}' already exists. Overwrite?`,default:!1}]);if(!u){t.info("Download cancelled");return}}d.start("\u{1F5D1}\uFE0F Removing existing directory..."),await Z.remove(l),d.succeed("Existing directory removed")}d.start("\u{1F4E5} Downloading function source code...");let c=await n.downloadFunction(i);if(d.succeed("Source code downloaded"),e.extract!==!1){d.start("\u{1F4E6} Extracting files..."),await Z.ensureDir(l);let u=new On.default(c),g=u.getEntries();u.extractAllTo(l,!0),d.succeed(`\u{1F4E6} Extracted ${g.length} files`);let h=de.join(l,"sinch-metadata.json"),C={functionId:s.id,name:s.name,runtime:s.runtime,status:s.status,downloadedAt:new Date().toISOString(),url:s.containerAppUrl,configuration:s.configuration};await Z.writeJson(h,C,{spaces:2}),t.newline(),t.success("\u2705 Function downloaded successfully!"),t.newline(),t.info(`\u{1F4C1} Location: ${_.default.cyan(a)}`),t.info(`\u{1F4CB} Files: ${g.length} files extracted`);let w=de.join(l,"sinch.json");await Z.pathExists(w)&&t.info("\u{1F527} Config: sinch.json found"),t.newline(),t.info("\u{1F4A1} Next steps:"),t.info(` \u2022 Navigate: ${_.default.cyan(`cd ${a}`)}`),t.info(` \u2022 Run locally: ${_.default.cyan("sinch functions dev")}`),t.info(` \u2022 Deploy changes: ${_.default.cyan("sinch functions deploy")}`)}else{let u=`${s.name}.zip`,g=e.output?de.resolve(e.output):de.resolve(u);d.start(`\u{1F4BE} Saving as ${u}...`),await Z.writeFile(g,c),d.succeed("ZIP file saved"),t.newline(),t.success("\u2705 Function downloaded as ZIP!"),t.info(`\u{1F4C1} File: ${_.default.cyan(g)}`),t.info(`\u{1F4E6} Size: ${(c.length/1024).toFixed(2)} KB`)}}catch(n){d.stop(),n.message.includes("404")||n.message.includes("not found")?(t.error(`Function not found with ID: ${o}`),t.info("\u{1F4A1} List available functions with:"),t.info(` ${_.default.cyan("sinch functions list")}`),t.info("\u{1F4A1} Or use interactive selection:"),t.info(` ${_.default.cyan("sinch functions download")}`)):t.error(`Failed to download function: ${n.message}`),process.exit(1)}});async function Xo(o){try{d.start("\u{1F4CB} Loading functions...");let e=await o.listFunctions();if(d.stop(),!e.functions||e.functions.length===0)return t.warn("No functions found to download"),null;let n=e.functions.map(s=>({name:`${_.default.cyan(s.name.padEnd(20))} ${_.default.yellow(s.runtime.padEnd(8))} ${ei(s.status)}`,value:s.id,short:s.name}));t.newline();let{selectedFunction:i}=await St.default.prompt([{type:"list",name:"selectedFunction",message:"Select a function to download:",choices:n,pageSize:15}]);return i}catch(e){throw d.stop(),e}}function ei(o){return{Running:_.default.green("\u2705 Running"),Failed:_.default.red("\u274C Failed"),Pending:_.default.yellow("\u23F3 Pending"),Building:_.default.blue("\u{1F528} Building")}[o]||_.default.gray(o)}Ln.exports=_n});var Kn=U((js,Un)=>{"use strict";var Nn=require("commander"),ti=Kt(),ni=Mt(),oi=sn(),ii=un(),si=mn(),ri=Pn(),ai=Rn(),ci=Dn(),li=xn(),X=new Nn.Command("functions");X.description("Manage Sinch Functions");X.addCommand(ti);X.addCommand(ni);X.addCommand(oi);X.addCommand(li);X.addCommand(ii);X.addCommand(si);X.addCommand(ri);X.addCommand(ai);X.addCommand(ci);Un.exports=X});var Vn=U((Ls,qn)=>{"use strict";var Bn=require("commander"),H=m(require("chalk"));x();j();B();O();var se=new Bn.Command("templates");se.description("Browse and manage function templates");se.command("list").alias("ls").description("List available templates").argument("[runtime]","Filter by runtime (node, csharp, python)").option("-c, --category <category>","Filter by category (voice, sms, verification)").option("-d, --detailed","Show detailed information").action(async(o,e)=>{try{await p.load();let n=new I(p.getApiConfig());d.start("Loading templates...");let i;if(o?i=await n.listRuntimeTemplates(o,e.category):i=await n.listAllTemplates(e.category),d.stop(),i.templates.length===0){t.info(`No templates found${o?` for ${o}`:""}${e.category?` in category ${e.category}`:""}`);return}let s=`Available Templates${o?` (${o})`:""}${e.category?` - ${e.category}`:""}`;if(t.title(s),e.detailed)i.templates.forEach((r,a)=>{a>0&&t.newline(),t.log(H.default.bold.blue(`${r.name}`)),t.log(` Runtime: ${r.runtime}`),t.log(` Category: ${r.category}`),t.log(` Description: ${r.description}`),r.tags&&r.tags.length>0&&t.log(` Tags: ${r.tags.map(l=>H.default.gray(l)).join(", ")}`),t.log(` Path: ${H.default.gray(r.path)}`)});else{let r=i.templates.map(a=>[a.name,a.runtime,a.category,a.description.substring(0,50)+(a.description.length>50?"...":""),a.tags?a.tags.slice(0,2).join(", ")+(a.tags.length>2?"...":""):""]);t.table(["Name","Runtime","Category","Description","Tags"],r)}t.newline(),t.info(`Found ${i.templates.length} template${i.templates.length===1?"":"s"}`),t.info('Use "sinch templates show <runtime>/<template>" for details')}catch(n){d.stop(),t.error(`Failed to list templates: ${n.message}`),process.exit(1)}});se.command("show").description("Show detailed template information").argument("<template>",'Template name in format "runtime/template-name"').action(async o=>{try{await p.load();let e=new I(p.getApiConfig());if(!o.includes("/"))throw new Error('Template must be in format "runtime/template-name" (e.g., "node/simple-voice-ivr")');let n=o.split("/"),i=n[0],s=n[1];if(!i||!s)throw new Error('Template must be in format "runtime/template-name" (e.g., "node/simple-voice-ivr")');d.start(`Loading template details for ${o}...`);let r=await e.getTemplateDetails(i,s);d.stop(),t.title(`Template: ${r.name}`),t.newline(),t.log(H.default.bold("Basic Information:")),t.log(` Runtime: ${r.runtime}`),t.log(` Category: ${r.category}`),t.log(` Description: ${r.description}`),r.tags&&r.tags.length>0&&t.log(` Tags: ${r.tags.map(a=>H.default.blue(a)).join(", ")}`),r.variables&&Object.keys(r.variables).length>0&&(t.newline(),t.log(H.default.bold("Template Variables:")),Object.entries(r.variables).forEach(([a,l])=>{t.log(` ${a}: ${H.default.gray(l)}`)})),r.files&&r.files.length>0&&(t.newline(),t.log(H.default.bold("Files:")),r.files.forEach(a=>{t.log(` ${H.default.gray("\u2022")} ${a}`)})),r.readmeContent&&(t.newline(),t.log(H.default.bold("README:")),r.readmeContent.split(`
|
|
85
|
-
`).slice(0,10).forEach(
|
|
86
|
-
`).length>10&&t.log(` ${H.default.gray("... (truncated)")}`)),t.newline(),t.info(`Use "sinch functions init --template ${o}" to create a function from this template`)}catch(e){d.stop(),t.error(`Failed to show template details: ${e.message}`),process.exit(1)}});se.command("node").description("List Node.js templates").option("-c, --category <category>","Filter by category").action(async o=>{let e=se.commands.find(n=>n.name()==="list");e&&await e.action("node",o)});se.command("csharp").description("List C# templates").option("-c, --category <category>","Filter by category").action(async o=>{let e=se.commands.find(n=>n.name()==="list");e&&await e.action("csharp",o)});se.command("python").description("List Python templates").option("-c, --category <category>","Filter by category").action(async o=>{let e=se.commands.find(n=>n.name()==="list");e&&await e.action("python",o)});qn.exports=se});var Wn=U((Ks,Hn)=>{"use strict";var Jn=require("commander"),Pe=
|
|
84
|
+
-v`,n}$n.exports=yt});var Rn=U((Cs,An)=>{"use strict";var M=h(require("chalk")),kn=h(require("inquirer")),En=require("commander");x();j();B();O();var In=new En.Command("delete");In.alias("del").description("Delete a function").argument("<function-id>","Function ID to delete").option("-f, --force","Skip confirmation").action(async(o,e)=>{try{await f.load();let n=new I(f.getApiConfig());d.start("Loading function details...");let i=await n.getFunction(o);if(d.stop(),t.newline(),t.info("\u{1F5D1}\uFE0F Function to delete:"),t.info(` Name: ${M.default.cyan(i.name)}`),t.info(` ID: ${M.default.gray(i.id)}`),t.info(` Runtime: ${M.default.yellow(i.runtime)}`),t.info(` Status: ${Yo(i.status)}`),t.info(` Created: ${new Date(i.createdAt).toLocaleString()}`),i.containerAppUrl&&t.info(` URL: ${M.default.blue(i.containerAppUrl)}`),!e.force){t.newline(),t.warn("\u26A0\uFE0F This action cannot be undone!");let{confirm:s}=await kn.default.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete function '${i.name}'?`,default:!1}]);if(!s){t.info("Deletion cancelled");return}}d.start("Deleting function..."),await n.deleteFunction(o),d.succeed(`Function '${i.name}' deleted successfully`),f.isInProject()&&f.getProjectConfig()?.functionId===o&&(f.set("functionId",void 0,!0),await f.saveProjectConfig(),t.newline(),t.info("\u{1F4A1} Removed function ID from sinch.json"),t.info(" Deploy again with: sinch functions deploy")),t.newline(),t.info("\u{1F4A1} Next steps:"),t.info(` \u2022 List remaining functions: ${M.default.cyan("sinch functions list")}`),t.info(` \u2022 Deploy new function: ${M.default.cyan("sinch functions deploy")}`)}catch(n){d.stop(),n.message.includes("404")||n.message.includes("not found")?(t.error(`Function '${o}' not found`),t.info("\u{1F4A1} List available functions with:"),t.info(` ${M.default.cyan("sinch functions list")}`)):t.error(`Failed to delete function: ${n.message}`),process.exit(1)}});function Yo(o){return{Running:M.default.green("\u2705 Running"),Failed:M.default.red("\u274C Failed"),Pending:M.default.yellow("\u23F3 Pending"),Building:M.default.blue("\u{1F528} Building")}[o]||M.default.gray(o)}An.exports=In});var Dn=U((ks,jn)=>{"use strict";var Tn=require("commander"),wt=h(require("fs-extra")),Ct=h(require("path")),$e=h(require("chalk"));j();B();O();pt();x();var bt=new Tn.Command("docs");bt.description("Generate documentation for voice functions (saves to README.md)");bt.option("-f, --fresh","Force regeneration (skip cache)").option("-u, --update","Update documentation for deployed function via API").action(async o=>{try{await f.load(),o.update?await Qo():await zo(o)}catch(e){d.fail("\u274C Failed to generate documentation"),e.message.includes("No function file found")?t.error("No function file found. Make sure you're in a function directory with function.js, index.js, or handler.js"):e.message.includes("unauthorized")||e.message.includes("401")?t.error("Authentication failed. Run `sinch auth login` first."):e.message.includes("AI service")?t.error("AI documentation service unavailable. Please try again later."):e.message.includes("Function not found")||e.message.includes("404")?t.error("Function not found. Make sure the function is deployed first."):t.error(`Error: ${e.message}`),t.debug("Full error:",e),process.exit(1)}});async function zo(o){d.start("\u{1F916} Generating documentation...");let e=await ut();d.succeed("\u2705 Documentation generated!"),await dt(e,"README.md"),await Zo()}async function Qo(){let o=Ct.default.basename(process.cwd());d.start("\u{1F4D6} Reading local README.md...");let e=Ct.default.join(process.cwd(),"README.md");if(!await wt.default.pathExists(e))throw new Error("README.md not found. Run `sinch functions docs` first to generate documentation locally.");if(!(await wt.default.readFile(e,"utf8")).trim())throw new Error("README.md is empty. Run `sinch functions docs` first to generate documentation.");d.text="\u{1F50D} Finding deployed function...";let a=(await new I(f.getApiConfig()).listFunctions()).find(r=>r.name===o);if(!a)throw new Error(`Function '${o}' not found in project. Make sure it's deployed first.`);d.text="\u{1F4E4} Uploading documentation content...",t.info("Documentation content ready for update"),d.succeed("\u2705 Documentation updated!"),t.newline(),t.success(`\u{1F4C4} Documentation updated for deployed function: ${$e.default.cyan(o)}`),t.info(""),t.info("\u2728 Your function documentation has been updated:"),t.info(` \u2022 Function ID: ${$e.default.gray(a.id)}`),t.info(` \u2022 Source: ${$e.default.gray("Local README.md")}`),t.info(` \u2022 Updated: ${$e.default.gray(new Date().toLocaleString())}`),t.info(` \u2022 View in dashboard: ${$e.default.cyan("Dashboard \u2192 Functions \u2192 "+o)}`),t.newline(),t.info("\u{1F4A1} The updated documentation is now available in the dashboard!")}async function Zo(){t.newline(),t.success(`\u{1F4C4} Documentation updated in: ${$e.default.cyan("README.md")}`),t.info(""),t.info("\u2728 Your function documentation is ready:"),t.info(" \u2022 Review and edit the AI-generated content as needed"),t.info(" \u2022 Sinch-themed diagrams will render in markdown viewers"),t.info(" \u2022 File is ready for version control and deployment"),t.newline(),t.info("\u{1F4A1} Popular markdown viewers:"),t.info(" \u2022 VS Code (built-in)"),t.info(" \u2022 GitHub (drag & drop file)"),t.info(" \u2022 Typora, Mark Text, or any markdown app")}jn.exports=bt});var xn=U((Ts,Ln)=>{"use strict";var _=h(require("chalk")),St=h(require("inquirer")),Fn=require("commander"),X=h(require("fs-extra")),de=h(require("path")),On=h(require("adm-zip"));x();j();B();O();var _n=new Fn.Command("download");_n.description("Download function source code").argument("[function-id]","Function ID to download (ULID format)").option("-o, --output <dir>","Output directory (default: ./functions/<function-name>)").option("--no-extract","Keep as ZIP file without extracting").option("--non-interactive","Skip interactive selection").option("-f, --force","Overwrite existing directory without prompting").action(async(o,e)=>{try{await f.load();let n=new I(f.getApiConfig()),i=o;if(!i&&!e.nonInteractive){let l=await Xo(n);if(!l){t.info("Download cancelled");return}i=l}i||(t.error("Function ID required. Provide as argument or select interactively"),t.info(`Usage: ${_.default.cyan("sinch functions download 01HX3KC5V8G3KCNZ8S5Y9ABCDE")}`),t.info(` or: ${_.default.cyan("sinch functions download")} (interactive selection)`),process.exit(1)),d.start("\u{1F4E1} Fetching function metadata...");let s=await n.getFunction(i);d.succeed("Function metadata loaded");let a=de.join("functions",s.name),r=e.output||a,u=de.resolve(r);if(await X.pathExists(u)){if(!e.force){let{overwrite:l}=await St.default.prompt([{type:"confirm",name:"overwrite",message:`Directory '${r}' already exists. Overwrite?`,default:!1}]);if(!l){t.info("Download cancelled");return}}d.start("\u{1F5D1}\uFE0F Removing existing directory..."),await X.remove(u),d.succeed("Existing directory removed")}d.start("\u{1F4E5} Downloading function source code...");let c=await n.downloadFunction(i);if(d.succeed("Source code downloaded"),e.extract!==!1){d.start("\u{1F4E6} Extracting files..."),await X.ensureDir(u);let l=new On.default(c),p=l.getEntries();l.extractAllTo(u,!0),d.succeed(`\u{1F4E6} Extracted ${p.length} files`);let m=de.join(u,"sinch-metadata.json"),C={functionId:s.id,name:s.name,runtime:s.runtime,status:s.status,downloadedAt:new Date().toISOString(),url:s.containerAppUrl,configuration:s.configuration};await X.writeJson(m,C,{spaces:2}),t.newline(),t.success("\u2705 Function downloaded successfully!"),t.newline(),t.info(`\u{1F4C1} Location: ${_.default.cyan(r)}`),t.info(`\u{1F4CB} Files: ${p.length} files extracted`);let w=de.join(u,"sinch.json");await X.pathExists(w)&&t.info("\u{1F527} Config: sinch.json found"),t.newline(),t.info("\u{1F4A1} Next steps:"),t.info(` \u2022 Navigate: ${_.default.cyan(`cd ${r}`)}`),t.info(` \u2022 Run locally: ${_.default.cyan("sinch functions dev")}`),t.info(` \u2022 Deploy changes: ${_.default.cyan("sinch functions deploy")}`)}else{let l=`${s.name}.zip`,p=e.output?de.resolve(e.output):de.resolve(l);d.start(`\u{1F4BE} Saving as ${l}...`),await X.writeFile(p,c),d.succeed("ZIP file saved"),t.newline(),t.success("\u2705 Function downloaded as ZIP!"),t.info(`\u{1F4C1} File: ${_.default.cyan(p)}`),t.info(`\u{1F4E6} Size: ${(c.length/1024).toFixed(2)} KB`)}}catch(n){d.stop(),n.message.includes("404")||n.message.includes("not found")?(t.error(`Function not found with ID: ${o}`),t.info("\u{1F4A1} List available functions with:"),t.info(` ${_.default.cyan("sinch functions list")}`),t.info("\u{1F4A1} Or use interactive selection:"),t.info(` ${_.default.cyan("sinch functions download")}`)):t.error(`Failed to download function: ${n.message}`),process.exit(1)}});async function Xo(o){try{d.start("\u{1F4CB} Loading functions...");let e=await o.listFunctions();if(d.stop(),!e.functions||e.functions.length===0)return t.warn("No functions found to download"),null;let n=e.functions.map(s=>({name:`${_.default.cyan(s.name.padEnd(20))} ${_.default.yellow(s.runtime.padEnd(8))} ${ei(s.status)}`,value:s.id,short:s.name}));t.newline();let{selectedFunction:i}=await St.default.prompt([{type:"list",name:"selectedFunction",message:"Select a function to download:",choices:n,pageSize:15}]);return i}catch(e){throw d.stop(),e}}function ei(o){return{Running:_.default.green("\u2705 Running"),Failed:_.default.red("\u274C Failed"),Pending:_.default.yellow("\u23F3 Pending"),Building:_.default.blue("\u{1F528} Building")}[o]||_.default.gray(o)}Ln.exports=_n});var Kn=U((js,Un)=>{"use strict";var Nn=require("commander"),ti=Kt(),ni=Mt(),oi=sn(),ii=un(),si=mn(),ri=Pn(),ai=Rn(),ci=Dn(),li=xn(),ee=new Nn.Command("functions");ee.description("Manage Sinch Functions");ee.addCommand(ti);ee.addCommand(ni);ee.addCommand(oi);ee.addCommand(li);ee.addCommand(ii);ee.addCommand(si);ee.addCommand(ri);ee.addCommand(ai);ee.addCommand(ci);Un.exports=ee});var Vn=U((Ls,qn)=>{"use strict";var Bn=require("commander"),H=h(require("chalk"));x();j();B();O();var se=new Bn.Command("templates");se.description("Browse and manage function templates");se.command("list").alias("ls").description("List available templates").argument("[runtime]","Filter by runtime (node, csharp, python)").option("-c, --category <category>","Filter by category (voice, sms, verification)").option("-d, --detailed","Show detailed information").action(async(o,e)=>{try{await f.load();let n=new I(f.getApiConfig());d.start("Loading templates...");let i;if(o?i=await n.listRuntimeTemplates(o,e.category):i=await n.listAllTemplates(e.category),d.stop(),i.templates.length===0){t.info(`No templates found${o?` for ${o}`:""}${e.category?` in category ${e.category}`:""}`);return}let s=`Available Templates${o?` (${o})`:""}${e.category?` - ${e.category}`:""}`;if(t.title(s),e.detailed)i.templates.forEach((a,r)=>{r>0&&t.newline(),t.log(H.default.bold.blue(`${a.name}`)),t.log(` Runtime: ${a.runtime}`),t.log(` Category: ${a.category}`),t.log(` Description: ${a.description}`),a.tags&&a.tags.length>0&&t.log(` Tags: ${a.tags.map(u=>H.default.gray(u)).join(", ")}`),t.log(` Path: ${H.default.gray(a.path)}`)});else{let a=i.templates.map(r=>[r.name,r.runtime,r.category,r.description.substring(0,50)+(r.description.length>50?"...":""),r.tags?r.tags.slice(0,2).join(", ")+(r.tags.length>2?"...":""):""]);t.table(["Name","Runtime","Category","Description","Tags"],a)}t.newline(),t.info(`Found ${i.templates.length} template${i.templates.length===1?"":"s"}`),t.info('Use "sinch templates show <runtime>/<template>" for details')}catch(n){d.stop(),t.error(`Failed to list templates: ${n.message}`),process.exit(1)}});se.command("show").description("Show detailed template information").argument("<template>",'Template name in format "runtime/template-name"').action(async o=>{try{await f.load();let e=new I(f.getApiConfig());if(!o.includes("/"))throw new Error('Template must be in format "runtime/template-name" (e.g., "node/simple-voice-ivr")');let n=o.split("/"),i=n[0],s=n[1];if(!i||!s)throw new Error('Template must be in format "runtime/template-name" (e.g., "node/simple-voice-ivr")');d.start(`Loading template details for ${o}...`);let a=await e.getTemplateDetails(i,s);d.stop(),t.title(`Template: ${a.name}`),t.newline(),t.log(H.default.bold("Basic Information:")),t.log(` Runtime: ${a.runtime}`),t.log(` Category: ${a.category}`),t.log(` Description: ${a.description}`),a.tags&&a.tags.length>0&&t.log(` Tags: ${a.tags.map(r=>H.default.blue(r)).join(", ")}`),a.variables&&Object.keys(a.variables).length>0&&(t.newline(),t.log(H.default.bold("Template Variables:")),Object.entries(a.variables).forEach(([r,u])=>{t.log(` ${r}: ${H.default.gray(u)}`)})),a.files&&a.files.length>0&&(t.newline(),t.log(H.default.bold("Files:")),a.files.forEach(r=>{t.log(` ${H.default.gray("\u2022")} ${r}`)})),a.readmeContent&&(t.newline(),t.log(H.default.bold("README:")),a.readmeContent.split(`
|
|
85
|
+
`).slice(0,10).forEach(u=>{t.log(` ${H.default.gray(u)}`)}),a.readmeContent.split(`
|
|
86
|
+
`).length>10&&t.log(` ${H.default.gray("... (truncated)")}`)),t.newline(),t.info(`Use "sinch functions init --template ${o}" to create a function from this template`)}catch(e){d.stop(),t.error(`Failed to show template details: ${e.message}`),process.exit(1)}});se.command("node").description("List Node.js templates").option("-c, --category <category>","Filter by category").action(async o=>{let e=se.commands.find(n=>n.name()==="list");e&&await e.action("node",o)});se.command("csharp").description("List C# templates").option("-c, --category <category>","Filter by category").action(async o=>{let e=se.commands.find(n=>n.name()==="list");e&&await e.action("csharp",o)});se.command("python").description("List Python templates").option("-c, --category <category>","Filter by category").action(async o=>{let e=se.commands.find(n=>n.name()==="list");e&&await e.action("python",o)});qn.exports=se});var Wn=U((Ks,Hn)=>{"use strict";var Jn=require("commander"),Pe=h(require("chalk")),Mn=h(require("inquirer"));j();B();O();var Be=new Jn.Command("voice");Be.description("Manage Sinch Voice applications and settings");Be.command("callback-url").alias("webhook").description("Update webhook callback URL for your Voice application").argument("[url]","New callback URL (if not provided, will prompt)").option("-a, --app-key <key>","Application key (if not provided, will show selection)").action(async(o,e)=>{try{await f.load(),await vt()||(t.error('Not authenticated. Run "sinch auth login" first.'),process.exit(1));let n=await ui(),i=e.appKey;if(!i){let s=f.getPublicCredentialInfo()?.applicationKey;s||(t.error('No default application key found. Run "sinch auth login" first.'),process.exit(1)),i=s,t.info(`Using default application: ${i}`)}if(!o){let{newUrl:s}=await Mn.default.prompt([{type:"input",name:"newUrl",message:"Enter new callback URL:",validate:a=>{if(!a)return"URL is required";try{return new URL(a),!0}catch{return"Please enter a valid URL"}}}]);o=s}d.start("Updating callback URL...");try{let s=await n.voice.applications.get(i),a={...s,capability:{...s.capability,voice:{...s.capability?.voice,webhooks:{...s.capability?.voice?.webhooks,url:o,method:"POST"}}}};await n.voice.applications.update(i,a),d.succeed("Callback URL updated successfully!"),t.newline(),t.info(`Application: ${s.displayName||i}`),t.info(`New callback URL: ${o}`),t.newline(),t.info("\u{1F389} Your Voice functions will now receive webhooks at this URL"),t.info("\u{1F4A1} Test with: sinch functions dev --tunnel")}catch(s){throw d.fail("Failed to update callback URL"),s}}catch(n){d.stop(),t.error(`Failed to update callback URL: ${n.message}`),process.exit(1)}});Be.command("get-callbacks").description("Get current callback URLs with full debug output").option("-a, --app-key <key>","Application key (defaults to stored app key)").option("--curl","Show equivalent curl command").action(async o=>{try{await f.load(),await vt()||(t.error('Not authenticated. Run "sinch auth login" first.'),process.exit(1));let e=await f.getApplicationCredentials();e||(t.error('No application credentials found. Run "sinch auth login" first.'),process.exit(1));let n=o.appKey||e.applicationKey;if(t.info("\u{1F50D} Getting callback URLs..."),t.newline(),o.curl){let i=`${e.applicationKey}:${e.applicationSecret}`,s=Buffer.from(i).toString("base64");t.info("\u{1F4CB} CURL Command:"),t.info(Pe.default.gray("```bash"));let a=`curl -X GET \\
|
|
87
87
|
https://calling.api.sinch.com/calling/v1/applications/${n}/callbacks/urls \\
|
|
88
|
-
-H "Authorization: Basic ${s}"`;t.info(Pe.default.cyan(
|
|
88
|
+
-H "Authorization: Basic ${s}"`;t.info(Pe.default.cyan(a)),t.info(Pe.default.gray("```")),t.newline()}try{let{SinchClient:i}=require("@sinch/sdk-core"),s=new i({applicationKey:e.applicationKey,applicationSecret:e.applicationSecret});d.start("Fetching callback URLs...");let a=await s.voice.applications.getCallbackURLs({applicationkey:n});d.succeed("Callback URLs retrieved"),t.newline(),t.info("\u{1F4E5} Current Callback Configuration:"),t.info(` currentCallbacks.primary: ${a?.primary||"undefined"}`),t.info(` currentCallbacks.fallback: ${a?.fallback||"undefined"}`)}catch(i){d.fail("Failed to get callback URLs"),t.error(`Error: ${i.message}`),t.newline(),t.info("Full error details:"),t.info(JSON.stringify(i,null,2))}}catch(e){t.error(`Command failed: ${e.message}`),process.exit(1)}});Be.command("set-callback").description("Update callback URL with debug output showing exact API call").argument("<url>","Callback URL to set").option("-a, --app-key <key>","Application key (defaults to stored app key)").option("--primary-only","Only set primary URL (no fallback)").option("--debug","Show full curl command and response").action(async(o,e)=>{try{await f.load(),await vt()||(t.error('Not authenticated. Run "sinch auth login" first.'),process.exit(1));let n=await f.getApplicationCredentials();n||(t.error('No application credentials found. Run "sinch auth login" first.'),process.exit(1));let i=e.appKey||n.applicationKey;t.info("\u{1F527} Updating callback URL with debug output..."),t.newline();let s=e.primaryOnly?{url:{primary:o}}:{url:{primary:o,fallback:o}},a=`${n.applicationKey}:${n.applicationSecret}`,r=Buffer.from(a).toString("base64");t.info("\u{1F4CB} CURL Command:"),t.info(Pe.default.gray("```bash"));let u=`curl -X POST \\
|
|
89
89
|
https://calling.api.sinch.com/calling/v1/applications/${i}/callbacks/urls \\
|
|
90
|
-
-H "Authorization: Basic ${
|
|
90
|
+
-H "Authorization: Basic ${r}" \\
|
|
91
91
|
-H "Content-Type: application/json" \\
|
|
92
|
-
-d '${JSON.stringify(s,null,2)}'`;t.info(Pe.default.cyan(
|
|
92
|
+
-d '${JSON.stringify(s,null,2)}'`;t.info(Pe.default.cyan(u)),t.info(Pe.default.gray("```")),t.newline();try{let{SinchClient:c}=require("@sinch/sdk-core"),l=new c({applicationKey:n.applicationKey,applicationSecret:n.applicationSecret});t.info("\u{1F4E4} Request Body:"),t.info(JSON.stringify(s,null,2)),t.newline(),d.start("Sending update request..."),await l.voice.applications.updateCallbackURLs({applicationkey:i,updateCallbacksRequestBody:s}),d.succeed("Update request sent"),d.start("Waiting for changes to propagate..."),await new Promise(C=>setTimeout(C,5e3)),d.start("Verifying update...");let p=await l.voice.applications.getCallbackURLs({applicationkey:i});d.succeed("Verification complete"),t.newline(),t.info("\u{1F4E5} Current Callback URLs:"),t.info(JSON.stringify(p,null,2));let m=p?.url||p?.primary||p?.urls?.primary;m===o?(t.newline(),t.success("\u2705 Callback URL successfully updated!")):(t.newline(),t.warn("\u26A0\uFE0F Callback URL may not have been updated correctly"),t.info("Expected: "+o),t.info("Actual: "+(typeof m=="object"?JSON.stringify(m):m||"not found")),t.newline(),t.info("\u{1F50D} Debug - Response structure:"),t.info(" typeof currentCallbacks: "+typeof p),t.info(" currentCallbacks.url: "+(p?.url||"undefined")),t.info(" currentCallbacks.primary: "+(p?.primary||"undefined")),t.info(" currentCallbacks.urls?.primary: "+(p?.urls?.primary||"undefined")))}catch(c){d.fail("Update failed"),t.error(`Error: ${c.message}`),e.debug&&(t.newline(),t.info("Full error details:"),t.info(JSON.stringify(c,null,2)))}}catch(n){t.error(`Command failed: ${n.message}`),process.exit(1)}});async function vt(){return await f.hasCredentials()}async function ui(){return await f.createSinchClient()}Hn.exports=Be});var zn=U((qs,Yn)=>{"use strict";var Gn=require("commander"),re=h(require("keytar")),D=h(require("chalk"));B();var $t=h(require("inquirer")),pe="sinch-functions-cli",ke=new Gn.Command("secrets");ke.description("Manage secure secrets in OS keychain").addHelpText("after",`
|
|
93
93
|
Examples:
|
|
94
94
|
${D.default.cyan("sinch secrets list")} List all custom secrets
|
|
95
95
|
${D.default.cyan("sinch secrets add API_KEY abc123")} Add or update a secret
|
|
@@ -100,43 +100,43 @@ Note: Secrets are stored securely in your OS keychain:
|
|
|
100
100
|
- Windows: Credential Manager
|
|
101
101
|
- macOS: Keychain
|
|
102
102
|
- Linux: Secret Service API
|
|
103
|
-
`);ke.command("list").description("List all custom secrets (keys only)").action(async()=>{try{let e=(await re.default.findCredentials(pe)).filter(n=>n.account&&n.account.startsWith("custom-")).map(n=>n.account.replace("custom-",""));if(e.length===0){t.info("No custom secrets found"),t.info(""),t.info("\u{1F4A1} Add a secret with:"),t.info(` ${D.default.cyan("sinch secrets add <KEY> <VALUE>")}`);return}t.info(D.default.bold("Custom Secrets:")),t.info(""),e.forEach(n=>{t.info(` \u{1F510} ${D.default.cyan(n)}`)}),t.info(""),t.info(`Total: ${e.length} secret(s)`)}catch(o){t.error("Failed to list secrets:",o.message),process.exit(1)}});ke.command("add <key> <value>").description("Add or update a secret in OS keychain").action(async(o,e)=>{try{o.match(/^[A-Z0-9_]+$/)||(t.error("Secret key must be uppercase letters, numbers, and underscores only"),t.info(`Example: ${D.default.cyan("API_KEY")}, ${D.default.cyan("DATABASE_PASSWORD")}`),process.exit(1));let n=`custom-${o}`,s=await re.default.getPassword(pe,n)!==null;await re.default.setPassword(pe,n,e),s?t.success(`\u2705 Updated secret: ${D.default.cyan(o)}`):t.success(`\u2705 Added secret: ${D.default.cyan(o)}`),t.info(""),t.info("\u{1F4DD} To use in your function:"),t.info(` 1. Add ${D.default.cyan(o+"=")} to your .env file (leave value empty)`),t.info(` 2. Access via ${D.default.cyan("process.env."+o)} in your code`),t.info(" 3. The secret will be loaded automatically from OS keychain")}catch(n){t.error("Failed to add secret:",n.message),process.exit(1)}});ke.command("get <key>").description("Get a specific secret value").option("--show","Show the actual value (be careful!)").action(async(o,e)=>{try{let n=`custom-${o}`,i=await re.default.getPassword(pe,n);i||(t.error(`Secret not found: ${D.default.cyan(o)}`),t.info(""),t.info("\u{1F4A1} Available secrets:"),t.info(` Run ${D.default.cyan("sinch secrets list")} to see all secrets`),process.exit(1)),t.info(`Secret: ${D.default.cyan(o)}`),e.show?(t.warn("\u26A0\uFE0F Showing secret value - be careful not to expose it!"),t.info(`Value: ${i}`)):(t.info(`Value: ${D.default.gray("[HIDDEN - use --show to reveal]")}`),t.info(`Length: ${i.length} characters`))}catch(n){t.error("Failed to get secret:",n.message),process.exit(1)}});ke.command("delete <key>").alias("remove").alias("rm").description("Remove a secret from OS keychain").option("-f, --force","Skip confirmation").action(async(o,e)=>{try{let n=`custom-${o}`;if(await re.default.getPassword(pe,n)||(t.error(`Secret not found: ${D.default.cyan(o)}`),process.exit(1)),!e.force&&!(await $t.default.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete secret '${o}'?`,default:!1}])).confirm){t.info("Cancelled");return}await re.default.deletePassword(pe,n)?t.success(`\u2705 Deleted secret: ${D.default.cyan(o)}`):(t.error("Failed to delete secret"),process.exit(1))}catch(n){t.error("Failed to delete secret:",n.message),process.exit(1)}});ke.command("clear").description("Remove ALL custom secrets (use with caution!)").option("-f, --force","Skip confirmation").action(async o=>{try{let n=(await re.default.findCredentials(pe)).filter(s=>s.account&&s.account.startsWith("custom-"));if(n.length===0){t.info("No custom secrets to clear");return}if(!o.force&&(t.warn(`\u26A0\uFE0F This will delete ${n.length} custom secret(s)`),!(await $t.default.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete ALL custom secrets?",default:!1}])).confirm)){t.info("Cancelled");return}let i=0;for(let s of n)await re.default.deletePassword(pe,s.account)&&i++;t.success(`\u2705 Deleted ${i} custom secret(s)`)}catch(e){t.error("Failed to clear secrets:",e.message),process.exit(1)}});Yn.exports=ke});var Pt=require("commander"),
|
|
103
|
+
`);ke.command("list").description("List all custom secrets (keys only)").action(async()=>{try{let e=(await re.default.findCredentials(pe)).filter(n=>n.account&&n.account.startsWith("custom-")).map(n=>n.account.replace("custom-",""));if(e.length===0){t.info("No custom secrets found"),t.info(""),t.info("\u{1F4A1} Add a secret with:"),t.info(` ${D.default.cyan("sinch secrets add <KEY> <VALUE>")}`);return}t.info(D.default.bold("Custom Secrets:")),t.info(""),e.forEach(n=>{t.info(` \u{1F510} ${D.default.cyan(n)}`)}),t.info(""),t.info(`Total: ${e.length} secret(s)`)}catch(o){t.error("Failed to list secrets:",o.message),process.exit(1)}});ke.command("add <key> <value>").description("Add or update a secret in OS keychain").action(async(o,e)=>{try{o.match(/^[A-Z0-9_]+$/)||(t.error("Secret key must be uppercase letters, numbers, and underscores only"),t.info(`Example: ${D.default.cyan("API_KEY")}, ${D.default.cyan("DATABASE_PASSWORD")}`),process.exit(1));let n=`custom-${o}`,s=await re.default.getPassword(pe,n)!==null;await re.default.setPassword(pe,n,e),s?t.success(`\u2705 Updated secret: ${D.default.cyan(o)}`):t.success(`\u2705 Added secret: ${D.default.cyan(o)}`),t.info(""),t.info("\u{1F4DD} To use in your function:"),t.info(` 1. Add ${D.default.cyan(o+"=")} to your .env file (leave value empty)`),t.info(` 2. Access via ${D.default.cyan("process.env."+o)} in your code`),t.info(" 3. The secret will be loaded automatically from OS keychain")}catch(n){t.error("Failed to add secret:",n.message),process.exit(1)}});ke.command("get <key>").description("Get a specific secret value").option("--show","Show the actual value (be careful!)").action(async(o,e)=>{try{let n=`custom-${o}`,i=await re.default.getPassword(pe,n);i||(t.error(`Secret not found: ${D.default.cyan(o)}`),t.info(""),t.info("\u{1F4A1} Available secrets:"),t.info(` Run ${D.default.cyan("sinch secrets list")} to see all secrets`),process.exit(1)),t.info(`Secret: ${D.default.cyan(o)}`),e.show?(t.warn("\u26A0\uFE0F Showing secret value - be careful not to expose it!"),t.info(`Value: ${i}`)):(t.info(`Value: ${D.default.gray("[HIDDEN - use --show to reveal]")}`),t.info(`Length: ${i.length} characters`))}catch(n){t.error("Failed to get secret:",n.message),process.exit(1)}});ke.command("delete <key>").alias("remove").alias("rm").description("Remove a secret from OS keychain").option("-f, --force","Skip confirmation").action(async(o,e)=>{try{let n=`custom-${o}`;if(await re.default.getPassword(pe,n)||(t.error(`Secret not found: ${D.default.cyan(o)}`),process.exit(1)),!e.force&&!(await $t.default.prompt([{type:"confirm",name:"confirm",message:`Are you sure you want to delete secret '${o}'?`,default:!1}])).confirm){t.info("Cancelled");return}await re.default.deletePassword(pe,n)?t.success(`\u2705 Deleted secret: ${D.default.cyan(o)}`):(t.error("Failed to delete secret"),process.exit(1))}catch(n){t.error("Failed to delete secret:",n.message),process.exit(1)}});ke.command("clear").description("Remove ALL custom secrets (use with caution!)").option("-f, --force","Skip confirmation").action(async o=>{try{let n=(await re.default.findCredentials(pe)).filter(s=>s.account&&s.account.startsWith("custom-"));if(n.length===0){t.info("No custom secrets to clear");return}if(!o.force&&(t.warn(`\u26A0\uFE0F This will delete ${n.length} custom secret(s)`),!(await $t.default.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to delete ALL custom secrets?",default:!1}])).confirm)){t.info("Cancelled");return}let i=0;for(let s of n)await re.default.deletePassword(pe,s.account)&&i++;t.success(`\u2705 Deleted ${i} custom secret(s)`)}catch(e){t.error("Failed to clear secrets:",e.message),process.exit(1)}});Yn.exports=ke});var Pt=require("commander"),g=h(require("chalk")),fe=h(require("fs-extra")),Qe=h(require("path")),kt=h(require("os")),Qn=require("child_process");var ye=h(require("fs")),Xe=h(require("path")),et=h(require("chalk")),so=18e5,ro="https://registry.npmjs.org/@sinch/cli";function ao(){if(process.platform!=="win32")try{if(ye.default.existsSync("/.dockerenv"))return!0;let o=ye.default.readFileSync("/proc/1/cgroup","utf8");return o.includes("docker")||o.includes("containerd")}catch{return!1}return!!process.env.DOCKER_CONTAINER}function co(){return!!process.env.CI}function lo(){return ao()||co()}function uo(o){return o.includes("-dev.")?"dev":parseInt(o.split(".")[0]||"0")>=1?"latest":"beta"}function po(o){try{if(!ye.default.existsSync(o))return!0;let e=parseInt(ye.default.readFileSync(o,"utf8"));return Date.now()-e>so}catch{return!0}}function fo(o,e){let n=o.replace(/^v/,"").split("-")[0]||"0.0.0",i=e.replace(/^v/,"").split("-")[0]||"0.0.0",s=n.split(".").map(r=>parseInt(r)||0),a=i.split(".").map(r=>parseInt(r)||0);for(let r=0;r<3;r++){let u=s[r]||0,c=a[r]||0;if(c>u)return!0;if(c<u)return!1}if(o.includes("-dev.")&&e.includes("-dev.")){let r=parseInt(o.split("-dev.")[1]||"0");return parseInt(e.split("-dev.")[1]||"0")>r}return!1}async function go(o){try{let e=await fetch(ro,{signal:AbortSignal.timeout(3e3)});return e.ok&&(await e.json())["dist-tags"]?.[o]||null}catch{return null}}async function mo(o,e){let n=Ze().version,i=uo(n);try{let s=await go(i);if(!s)return;fo(n,s)&&(console.log(et.default.yellow(`
|
|
104
104
|
\u{1F4E6} Update available: ${n} \u2192 ${s}`)),console.log(et.default.cyan(`Run: npm install -g @sinch/cli@${i}
|
|
105
|
-
`))),ye.default.mkdirSync(o,{recursive:!0}),ye.default.writeFileSync(e,Date.now().toString())}catch{}}function Rt(){if(lo())return;let o=Xe.default.join(require("os").homedir(),".sinch"),e=Xe.default.join(o,".last-update-check");po(e)&&mo(o,e).catch(()=>{})}process.env.NODE_NO_WARNINGS||(process.env.NODE_NO_WARNINGS="1",process.removeAllListeners("warning"));Rt();var di=Ze(),pi=Kn(),fi=Vn(),gi=Wn(),mi=zn(),
|
|
106
|
-
\u{1F510} Sinch Voice API Authentication`)),console.log(
|
|
107
|
-
`)),fe.default.existsSync(o.credentialsFile)||(console.error(
|
|
108
|
-
Expected format:`)),console.error(
|
|
109
|
-
\u2705 Authentication successful!`)),console.log(
|
|
110
|
-
\u274C ${A.message||"Failed to authenticate with provided credentials"}`)),process.exit(1)}}catch(c){console.error(
|
|
111
|
-
\u{1F510} Sinch Voice API Authentication`)),console.log(i?
|
|
112
|
-
`):
|
|
113
|
-
`));let
|
|
114
|
-
\u2705 Authentication successful!`)),console.log(
|
|
115
|
-
\u274C Error: ${c.message}`)),console.log(
|
|
116
|
-
\u{1F4A1} Please check your credentials and try again`)),process.exit(1)}}catch(i){console.error(
|
|
117
|
-
\u{1F510} Authentication Status`)),e&&n){console.log(
|
|
118
|
-
\u{1F4CB} Configuration:`));let n=e.getApiConfig();Object.entries(n).forEach(([i,s])=>{console.log(` ${i}: ${s}`)})}else console.log(
|
|
119
|
-
\u2699\uFE0F Configuration Management`)),console.log(
|
|
120
|
-
`))}catch(n){console.error(
|
|
121
|
-
\u{1F3E5} Health Status:`)),console.log(` Status: ${
|
|
122
|
-
\u274C ${i.message}`)),process.exit(1)}});
|
|
123
|
-
\u{1F4A5} Uncaught Exception: ${o.message}`)),process.env.DEBUG&&console.error(o.stack),process.exit(1)});process.on("unhandledRejection",o=>{console.error(
|
|
124
|
-
\u{1F4A5} Unhandled Rejection: ${o}`)),process.env.DEBUG&&console.error(o),process.exit(1)});async function hi(){let o=process.argv.slice(2),e=o[0],n=["auth","help","completion","--help","-h","--version","-V"],i=o.includes("--non-interactive");if(e&&!n.includes(e)&&!n.some(s=>o.includes(s))){let{config:s}=(j(),F(we));if(await s.load(),!await s.hasCredentials()){i&&(console.error(
|
|
125
|
-
\u274C Authentication required`)),console.error("Please set up authentication first with: sinch auth login"),console.error("Or provide credentials via environment variables for CI/CD"),process.exit(1));let
|
|
105
|
+
`))),ye.default.mkdirSync(o,{recursive:!0}),ye.default.writeFileSync(e,Date.now().toString())}catch{}}function Rt(){if(lo())return;let o=Xe.default.join(require("os").homedir(),".sinch"),e=Xe.default.join(o,".last-update-check");po(e)&&mo(o,e).catch(()=>{})}process.env.NODE_NO_WARNINGS||(process.env.NODE_NO_WARNINGS="1",process.removeAllListeners("warning"));Rt();var di=Ze(),pi=Kn(),fi=Vn(),gi=Wn(),mi=zn(),te=new Pt.Command;te.name("sinch").description("Sinch Functions - Serverless function platform for voice applications").version(di.version,"-V, --version","output the version number").helpOption("-h, --help","Display help for command");te.addCommand(pi);te.addCommand(fi);te.addCommand(gi);te.addCommand(mi);var qe=new Pt.Command("auth");qe.description("Authentication management for Sinch Voice API");qe.command("login").description("Authenticate with Sinch Voice API").option("-f, --credentials-file <path>","Path to credentials JSON file").action(async o=>{let{config:e}=(j(),F(we)),n=require("inquirer");try{if(await e.load(),o.credentialsFile){console.log(g.default.blue(`
|
|
106
|
+
\u{1F510} Sinch Voice API Authentication`)),console.log(g.default.gray(`Loading credentials from: ${o.credentialsFile}
|
|
107
|
+
`)),fe.default.existsSync(o.credentialsFile)||(console.error(g.default.red(`\u274C Credentials file not found: ${o.credentialsFile}`)),process.exit(1));try{let c=fe.default.readFileSync(o.credentialsFile,"utf-8"),l=JSON.parse(c),m=["projectId","keyId","keySecret","applicationKey","applicationSecret"].filter(A=>!l[A]);m.length>0&&(console.error(g.default.red(`\u274C Missing required fields in credentials file: ${m.join(", ")}`)),console.error(g.default.gray(`
|
|
108
|
+
Expected format:`)),console.error(g.default.gray(JSON.stringify({projectId:"your-project-id",keyId:"your-key-id",keySecret:"your-key-secret",applicationKey:"your-app-key",applicationSecret:"your-app-secret"},null,2))),process.exit(1));let C={projectId:l.projectId,keyId:l.keyId,keySecret:l.keySecret,applicationKey:l.applicationKey,applicationSecret:l.applicationSecret},{spinner:w}=(O(),F(Ae));w.start("Verifying credentials...");try{w.update("Obtaining OAuth access token...");let{SinchAPI:A}=(x(),F(Ie)),W=await new A({apiUrl:e.get("apiUrl"),projectId:C.projectId,credentials:e._credentials}).authenticateOAuth(C.keyId,C.keySecret);w.succeed("OAuth token obtained successfully!"),w.start("Testing Voice API connection...");let{SinchClient:P}=require("@sinch/sdk-core");await new P({applicationKey:C.applicationKey,applicationSecret:C.applicationSecret}).voice.applications.getCallbackURLs({applicationkey:C.applicationKey}),w.succeed("Credentials verified successfully!"),await e._credentials.storeOAuthToken(W),await e._credentials.store(C),console.log(g.default.green(`
|
|
109
|
+
\u2705 Authentication successful!`)),console.log(g.default.gray("All credentials saved securely. You can now:")),console.log(" \u2022 Update callback URLs with: sinch voice callback-url <url>"),console.log(" \u2022 Deploy functions with live webhook testing"),console.log(" \u2022 Buy numbers and manage project resources"),console.log(""),console.log(g.default.blue("\u{1F512} Security:")),console.log(g.default.gray(" \u2022 Secrets stored in OS credential manager (Windows/macOS/Linux)")),console.log(g.default.gray(" \u2022 Non-sensitive data in ~/.sinch/config.json"));return}catch(A){w.fail(g.default.red("Authentication failed")),console.error(g.default.red(`
|
|
110
|
+
\u274C ${A.message||"Failed to authenticate with provided credentials"}`)),process.exit(1)}}catch(c){console.error(g.default.red(`\u274C Failed to parse credentials file: ${c.message}`)),process.exit(1)}}let i=await e.getCredentials(),s=e.getPublicCredentialInfo();console.log(g.default.blue(`
|
|
111
|
+
\u{1F510} Sinch Voice API Authentication`)),console.log(i?g.default.gray(`Found existing credentials. Press Enter to reuse them or enter new values.
|
|
112
|
+
`):g.default.gray(`Enter your Sinch credentials to manage voice applications and callbacks
|
|
113
|
+
`));let a=await n.prompt([{type:"input",name:"projectId",message:"Project ID (from Sinch Dashboard):",default:s?.projectId||void 0,validate:c=>!c&&s?.projectId?!0:c.length>0||"Project ID is required"},{type:"input",name:"keyId",message:"Key ID (from Project \u2192 Access Keys):",default:s?.keyId||void 0,validate:c=>!c&&s?.keyId?!0:c.length>0||"Key ID is required"},{type:"password",name:"keySecret",message:"Key Secret:",default:i?.keySecret||void 0,validate:c=>!c&&i?.keySecret?!0:c.length>0||"Key Secret is required"},{type:"input",name:"applicationKey",message:"Voice Application Key:",default:s?.applicationKey||void 0,validate:c=>!c&&s?.applicationKey?!0:c.length>0||"Application Key is required"},{type:"password",name:"applicationSecret",message:"Voice Application Secret:",default:i?.applicationSecret||void 0,validate:c=>!c&&i?.applicationSecret?!0:c.length>0||"Application Secret is required"}]),r={projectId:a.projectId||s?.projectId,keyId:a.keyId||s?.keyId,keySecret:a.keySecret||i?.keySecret,applicationKey:a.applicationKey||s?.applicationKey,applicationSecret:a.applicationSecret||i?.applicationSecret},{spinner:u}=(O(),F(Ae));u.start("Verifying credentials...");try{u.update("Obtaining OAuth access token...");let{SinchAPI:c}=(x(),F(Ie)),p=await new c({apiUrl:e.get("apiUrl"),projectId:r.projectId||e.get("projectId"),credentials:e._credentials}).authenticateOAuth(r.keyId,r.keySecret);u.succeed("OAuth token obtained successfully!"),u.start("Testing Voice API connection...");let{SinchClient:m}=require("@sinch/sdk-core");await new m({applicationKey:r.applicationKey,applicationSecret:r.applicationSecret}).voice.applications.getCallbackURLs({applicationkey:r.applicationKey}),u.succeed("Credentials verified successfully!"),await e._credentials.storeOAuthToken(p),await e._credentials.store(r),console.log(g.default.green(`
|
|
114
|
+
\u2705 Authentication successful!`)),console.log(g.default.gray("All credentials saved securely. You can now:")),console.log(" \u2022 Update callback URLs with: sinch voice callback-url <url>"),console.log(" \u2022 Deploy functions with live webhook testing"),console.log(" \u2022 Buy numbers and manage project resources"),console.log(""),console.log(g.default.blue("\u{1F512} Security:")),console.log(g.default.gray(" \u2022 Secrets stored in OS credential manager (Windows/macOS/Linux)")),console.log(g.default.gray(" \u2022 Non-sensitive data in ~/.sinch/config.json"))}catch(c){u.fail("Authentication failed"),console.error(g.default.red(`
|
|
115
|
+
\u274C Error: ${c.message}`)),console.log(g.default.yellow(`
|
|
116
|
+
\u{1F4A1} Please check your credentials and try again`)),process.exit(1)}}catch(i){console.error(g.default.red(`Authentication failed: ${i.message}`)),process.exit(1)}});qe.command("status").description("Show current authentication status").action(async()=>{let{config:o}=(j(),F(we));try{await o.load();let e=await o.hasCredentials(),n=o.getPublicCredentialInfo();if(console.log(g.default.blue(`
|
|
117
|
+
\u{1F510} Authentication Status`)),e&&n){console.log(g.default.green("\u2705 Authenticated")),console.log(` Project ID: ${n.projectId}`),console.log(` Key ID: ${n.keyId}`),console.log(` Application Key: ${n.applicationKey}`),console.log(g.default.gray(" (Secrets stored securely in OS keychain)"));try{let s=(x(),F(Ie)).default,a=o.getApiConfig();await new s(a).authenticate(),console.log(g.default.green(" OAuth Token: Valid"))}catch{console.log(g.default.yellow(" OAuth Token: Expired or invalid (will auto-refresh on next API call)"))}let{spinner:i}=(O(),F(Ae));i.start("Testing connection...");try{let s=await o.getApplicationCredentials();if(!s){i.fail("No application credentials found");return}let{SinchClient:a}=require("@sinch/sdk-core");await new a({applicationKey:s.applicationKey,applicationSecret:s.applicationSecret}).voice.applications.getCallbackURLs({applicationkey:s.applicationKey}),i.succeed("Connection active")}catch{i.fail("Connection failed"),console.log(g.default.yellow("\u26A0\uFE0F Credentials may be expired or invalid"))}}else console.log(g.default.red("\u274C Not authenticated")),console.log(g.default.gray('Run "sinch auth login" to authenticate'))}catch(e){console.error(g.default.red(`Failed to check status: ${e.message}`)),process.exit(1)}});qe.command("logout").description("Clear stored authentication credentials").action(async()=>{let{config:o}=(j(),F(we)),e=require("inquirer");try{(await e.prompt([{type:"confirm",name:"confirm",message:"Are you sure you want to logout and clear credentials?",default:!1}])).confirm?(await o.load(),await o.clearCredentials(),console.log(g.default.green("\u2705 Logged out successfully")),console.log(g.default.gray("All credentials cleared from secure storage"))):console.log(g.default.gray("Logout cancelled"))}catch(n){console.error(g.default.red(`Logout failed: ${n.message}`)),process.exit(1)}});te.addCommand(qe);te.command("config").description("Configuration management").option("--set <key=value>","Set configuration value").option("--get <key>","Get configuration value").option("--list","List all configuration values").action(async o=>{let{config:e}=(j(),F(we));try{if(await e.load(),o.set){let[n,i]=o.set.split("=");(!n||!i)&&(console.error(g.default.red("Invalid format. Use: --set key=value")),process.exit(1)),e.set(n,i),await e.save(),console.log(g.default.green(`\u2705 Set ${n} = ${i}`))}else if(o.get){let n=e.get(o.get);console.log(n!==null?n:g.default.gray("(not set)"))}else if(o.list){console.log(g.default.blue(`
|
|
118
|
+
\u{1F4CB} Configuration:`));let n=e.getApiConfig();Object.entries(n).forEach(([i,s])=>{console.log(` ${i}: ${s}`)})}else console.log(g.default.blue(`
|
|
119
|
+
\u2699\uFE0F Configuration Management`)),console.log(g.default.gray(`Use "sinch config --help" for available options
|
|
120
|
+
`))}catch(n){console.error(g.default.red(`Failed to manage config: ${n.message}`)),process.exit(1)}});te.command("health").description("Check API connection and health").action(async()=>{let{SinchAPI:o}=(x(),F(Ie)),{config:e}=(j(),F(we)),{spinner:n}=(O(),F(Ae));try{await e.load();let i=new o(e.getApiConfig());n.start("Checking API health...");let s=await i.checkHealth();n.succeed("API is healthy"),console.log(g.default.blue(`
|
|
121
|
+
\u{1F3E5} Health Status:`)),console.log(` Status: ${g.default.green(s.status)}`),console.log(` API URL: ${e.get("apiUrl")}`),console.log(` Project ID: ${e.get("projectId")}`)}catch(i){n.fail("API health check failed"),console.error(g.default.red(`
|
|
122
|
+
\u274C ${i.message}`)),process.exit(1)}});te.command("completion").description("Generate shell completion scripts").option("--shell <shell>","Shell type (powershell, bash, zsh)","powershell").option("--install","Automatically install completion (PowerShell only)").action(async o=>{let e=o.shell.toLowerCase();o.install&&e==="powershell"?await yi():e==="powershell"?bi():e==="bash"?Si():e==="zsh"?vi():(console.error(g.default.red(`Unsupported shell: ${e}`)),console.log("Supported shells: powershell, bash, zsh"),process.exit(1))});process.on("uncaughtException",o=>{console.error(g.default.red(`
|
|
123
|
+
\u{1F4A5} Uncaught Exception: ${o.message}`)),process.env.DEBUG&&console.error(o.stack),process.exit(1)});process.on("unhandledRejection",o=>{console.error(g.default.red(`
|
|
124
|
+
\u{1F4A5} Unhandled Rejection: ${o}`)),process.env.DEBUG&&console.error(o),process.exit(1)});async function hi(){let o=process.argv.slice(2),e=o[0],n=["auth","help","completion","--help","-h","--version","-V"],i=o.includes("--non-interactive");if(e&&!n.includes(e)&&!n.some(s=>o.includes(s))){let{config:s}=(j(),F(we));if(await s.load(),!await s.hasCredentials()){i&&(console.error(g.default.red(`
|
|
125
|
+
\u274C Authentication required`)),console.error("Please set up authentication first with: sinch auth login"),console.error("Or provide credentials via environment variables for CI/CD"),process.exit(1));let a=require("inquirer");console.log(g.default.yellow(`
|
|
126
126
|
\u26A0\uFE0F Authentication Required`)),console.log(`You need to authenticate with Sinch to use the CLI.
|
|
127
|
-
`);let{shouldLogin:
|
|
128
|
-
You can authenticate anytime with:`),console.log(` ${
|
|
129
|
-
`),process.exit(0))}}
|
|
130
|
-
\u{1F3AF} Sinch Functions CLI`)),console.log(
|
|
131
|
-
`)),console.log("Quick start:"),console.log(` ${
|
|
132
|
-
\u2139\uFE0F Completion is already installed`)),console.log(
|
|
127
|
+
`);let{shouldLogin:r}=await a.prompt([{type:"confirm",name:"shouldLogin",message:"Would you like to login now?",default:!0}]);r?process.argv.splice(2,process.argv.length-2,"auth","login"):(console.log(`
|
|
128
|
+
You can authenticate anytime with:`),console.log(` ${g.default.cyan("sinch auth login")}
|
|
129
|
+
`),process.exit(0))}}te.parse(process.argv),process.argv.slice(2).length||(console.log(g.default.blue.bold(`
|
|
130
|
+
\u{1F3AF} Sinch Functions CLI`)),console.log(g.default.gray(`Serverless function platform for voice applications
|
|
131
|
+
`)),console.log("Quick start:"),console.log(` ${g.default.cyan("sinch auth login")} # Authenticate with Sinch Voice API`),console.log(` ${g.default.cyan("sinch templates list")} # Browse available templates`),console.log(` ${g.default.cyan("sinch functions init")} # Create a new function`),console.log(` ${g.default.cyan("sinch functions dev")} # Start local development`),console.log(` ${g.default.cyan("sinch voice callback-url")} # Update webhook URL for live testing`),console.log(` ${g.default.cyan("sinch functions deploy")} # Deploy to production`),console.log(` ${g.default.cyan("sinch functions status [id]")} # Check deployment status`),console.log(` ${g.default.cyan("sinch secrets list")} # Manage custom secrets`),console.log(""),te.help())}hi().catch(o=>{console.error(g.default.red("Error:"),o.message),process.exit(1)});async function yi(){let{spinner:o}=(O(),F(Ae));try{o.start("Installing PowerShell completion...");let e=Qe.default.join(kt.default.homedir(),"Documents","PowerShell"),n=Qe.default.join(e,"sinch-completion.ps1");await fe.default.ensureDir(e),o.update("Creating completion script...");let i=Ci();await fe.default.writeFile(n,i),o.update("Updating PowerShell profile...");let s=await wi(),a="";await fe.default.pathExists(s)&&(a=await fe.default.readFile(s,"utf8"));let r='. "$env:USERPROFILE\\Documents\\PowerShell\\sinch-completion.ps1"';if(a.includes("sinch-completion.ps1"))o.info("PowerShell completion already installed"),console.log(g.default.blue(`
|
|
132
|
+
\u2139\uFE0F Completion is already installed`)),console.log(g.default.gray("If tab completion isn't working, try restarting PowerShell"));else{let u=a+(a?`
|
|
133
133
|
`:"")+`# Sinch Functions CLI completion
|
|
134
|
-
`+
|
|
135
|
-
`;await fe.default.writeFile(s,
|
|
136
|
-
\u2705 Installation Complete!`)),console.log(
|
|
137
|
-
\u26A1 To activate completion:`)),console.log(" 1. Restart PowerShell, OR"),console.log(" 2. Run: "+
|
|
138
|
-
\u{1F4A1} Test with: sinch functions <TAB>`))}}catch(e){o.fail("Failed to install PowerShell completion"),console.error(
|
|
139
|
-
\u{1F4A1} Try manual installation with: sinch completion`)),process.exit(1)}}async function wi(){return new Promise(o=>{let e=n=>new Promise(i=>{let s=(0,Qn.spawn)(n,["-Command","$PROFILE"],{stdio:["ignore","pipe","pipe"]}),
|
|
134
|
+
`+r+`
|
|
135
|
+
`;await fe.default.writeFile(s,u),o.succeed("PowerShell completion installed successfully!"),console.log(g.default.green(`
|
|
136
|
+
\u2705 Installation Complete!`)),console.log(g.default.blue("\u{1F4C1} Files created:")),console.log(` ${g.default.gray(n)}`),console.log(` ${g.default.gray("Updated:")} ${s}`),console.log(g.default.yellow(`
|
|
137
|
+
\u26A1 To activate completion:`)),console.log(" 1. Restart PowerShell, OR"),console.log(" 2. Run: "+g.default.cyan(". $PROFILE")),console.log(g.default.gray(`
|
|
138
|
+
\u{1F4A1} Test with: sinch functions <TAB>`))}}catch(e){o.fail("Failed to install PowerShell completion"),console.error(g.default.red(`\u274C Error: ${e.message}`)),console.log(g.default.yellow(`
|
|
139
|
+
\u{1F4A1} Try manual installation with: sinch completion`)),process.exit(1)}}async function wi(){return new Promise(o=>{let e=n=>new Promise(i=>{let s=(0,Qn.spawn)(n,["-Command","$PROFILE"],{stdio:["ignore","pipe","pipe"]}),a="";s.stdout.on("data",r=>{a+=r.toString()}),s.on("close",r=>{i(r===0?{success:!0,path:a.trim(),version:n}:{success:!1})}),s.on("error",()=>{i({success:!1})})});e("pwsh").then(n=>{n.success&&n.path?(console.log(g.default.gray(` Detected PowerShell 7 profile: ${n.path}`)),o(n.path)):e("powershell").then(i=>{if(i.success&&i.path)console.log(g.default.gray(` Detected Windows PowerShell profile: ${i.path}`)),o(i.path);else{let s=Qe.default.join(kt.default.homedir(),"Documents","PowerShell","Microsoft.PowerShell_profile.ps1");console.log(g.default.gray(` Using fallback profile path: ${s}`)),o(s)}})})})}function Ci(){return`# PowerShell completion for Sinch Functions CLI
|
|
140
140
|
# Auto-generated by 'sinch completion --install'
|
|
141
141
|
# Compatible with both PowerShell 7 and Windows PowerShell 5.1
|
|
142
142
|
|
|
@@ -233,8 +233,8 @@ Register-ArgumentCompleter -Native -CommandName sinch -ScriptBlock {
|
|
|
233
233
|
# . "$env:USERPROFILE\\Documents\\PowerShell\\sinch-completion.ps1"
|
|
234
234
|
#
|
|
235
235
|
# To find your profile location, run: $PROFILE
|
|
236
|
-
`;console.log(
|
|
237
|
-
`)),console.log(o),console.log(
|
|
236
|
+
`;console.log(g.default.blue("\u{1F527} PowerShell Completion Script")),console.log(g.default.gray(`Copy and save this to your PowerShell profile:
|
|
237
|
+
`)),console.log(o),console.log(g.default.yellow("Installation Instructions:")),console.log(g.default.green("\u{1F680} Easy way: ")+g.default.cyan("sinch completion --install")),console.log(g.default.gray("\u{1F4DD} Manual way:")),console.log("1. Save this script as sinch-completion.ps1 in your Documents\\PowerShell folder"),console.log("2. Add this line to your PowerShell profile:"),console.log(g.default.cyan(' . "$env:USERPROFILE\\\\Documents\\\\PowerShell\\\\sinch-completion.ps1"')),console.log("3. Restart PowerShell or run: . $PROFILE")}function Si(){let o=`
|
|
238
238
|
# Bash completion for Sinch Functions CLI
|
|
239
239
|
_sinch_completion() {
|
|
240
240
|
local cur prev commands
|
|
@@ -274,7 +274,7 @@ _sinch_completion() {
|
|
|
274
274
|
complete -F _sinch_completion sinch
|
|
275
275
|
|
|
276
276
|
# To install: Add this to your ~/.bashrc or ~/.bash_profile
|
|
277
|
-
`;console.log(
|
|
277
|
+
`;console.log(g.default.blue("\u{1F527} Bash Completion Script")),console.log(g.default.gray(`Add this to your ~/.bashrc or ~/.bash_profile:
|
|
278
278
|
`)),console.log(o)}function vi(){let o=`
|
|
279
279
|
#compdef sinch
|
|
280
280
|
|
|
@@ -329,5 +329,5 @@ _sinch "$@"
|
|
|
329
329
|
|
|
330
330
|
# To install: Save as _sinch in your zsh completions directory
|
|
331
331
|
# Usually: /usr/local/share/zsh/site-functions/_sinch
|
|
332
|
-
`;console.log(
|
|
332
|
+
`;console.log(g.default.blue("\u{1F527} Zsh Completion Script")),console.log(g.default.gray(`Save this as _sinch in your zsh completions directory:
|
|
333
333
|
`)),console.log(o)}
|