tsp-scale-sdk 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,36 +2,42 @@
2
2
 
3
3
  Official Node.js SDK for TSP Scale.
4
4
 
5
- ## Install
5
+ ## šŸš€ Quick Start (Zero-Config)
6
6
 
7
+ Initialize your project in seconds. This will link your project, create a secure hidden config, and add it to your `.gitignore` automatically.
8
+
9
+ ```bash
10
+ npx tsp-scale init
11
+ ```
12
+
13
+ ### Manual Installation
14
+ If you prefer manual setup:
7
15
  ```bash
8
16
  npm install tsp-scale-sdk
9
17
  ```
10
18
 
11
- ## Usage
19
+ ## šŸ› ļø Usage
12
20
 
13
- ```js
14
- const { TspScaleClient } = require("tsp-scale-sdk");
21
+ ```javascript
22
+ const { TspScaleClient } = require('tsp-scale-sdk');
15
23
 
16
- const client = new TspScaleClient({
17
- apiKey: process.env.TSP_API_KEY,
18
- baseUrl: "https://api.tspscale.in/api/v1",
19
- });
20
-
21
- async function run() {
22
- const result = await client.sendEmail({
23
- from: "support@yourdomain.com",
24
- to: "user@example.com",
25
- subject: "Hello from TSP Scale",
26
- html: "<h1>It works</h1>",
27
- });
24
+ // Authenticates automatically from local config or environment variables
25
+ const client = new TspScaleClient();
28
26
 
29
- console.log(result);
27
+ async function sendTest() {
28
+ const res = await client.sendEmail({
29
+ to: "recipient@example.com",
30
+ subject: "Hello from TSP Scale",
31
+ html: "<h1>It works!</h1>"
32
+ });
33
+ console.log(res);
30
34
  }
31
35
 
32
36
  run().catch(console.error);
33
37
  ```
34
38
 
39
+ > **Note**: The `from` field is optional if your API Key is locked to a specific sender identity.
40
+
35
41
  ### WhatsApp Messaging
36
42
 
37
43
  ```js
@@ -0,0 +1,142 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { execSync } = require('child_process');
4
+ const path = require('path');
5
+ const os = require('os');
6
+ const fs = require('fs');
7
+
8
+ try {
9
+ const readline = require('readline');
10
+ const crypto = require('crypto');
11
+ const https = require('https');
12
+
13
+ function ask(question) {
14
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
15
+ return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans); }));
16
+ }
17
+
18
+ async function post(url, data) {
19
+ return new Promise((resolve, reject) => {
20
+ const req = https.request(url, {
21
+ method: 'POST',
22
+ headers: { 'Content-Type': 'application/json' }
23
+ }, res => {
24
+ let body = '';
25
+ res.on('data', chunk => body += chunk);
26
+ res.on('end', () => {
27
+ try {
28
+ resolve({ ok: res.statusCode < 300, json: () => JSON.parse(body) });
29
+ } catch (e) {
30
+ resolve({ ok: false, json: () => ({ message: 'Invalid JSON response from server' }) });
31
+ }
32
+ });
33
+ });
34
+ req.on('error', reject);
35
+ req.write(JSON.stringify(data));
36
+ req.end();
37
+ });
38
+ }
39
+
40
+ async function init() {
41
+ console.log("\nšŸš€ TSP Scale SDK - Initializing Project\n");
42
+ const apiKey = await ask("šŸ”‘ Enter your API Key: ");
43
+ if (!apiKey) return console.error("Error: API Key is required.");
44
+
45
+ const projectIdentifier = await ask("šŸ“‚ Enter Project Name: ");
46
+ const projectId = crypto.createHash('md5').update(process.cwd()).digest('hex');
47
+
48
+ console.log("ā³ Verifying with server...");
49
+
50
+ try {
51
+ const res = await post("https://api.tspscale.in/api/v1/apikeys/verify", {
52
+ key: apiKey,
53
+ projectId,
54
+ projectIdentifier: projectIdentifier || "NodeJS Project"
55
+ });
56
+ const result = await res.json();
57
+ if (!res.ok) throw new Error(result.message || "Verification failed");
58
+
59
+ // 1. Save to Global Vault (Fallback)
60
+ const configDir = path.join(os.homedir(), '.tsp-scale');
61
+ if (!fs.existsSync(configDir)) fs.mkdirSync(configDir, { recursive: true });
62
+ fs.writeFileSync(path.join(configDir, 'config.json'), JSON.stringify({ apiKey }, null, 2));
63
+
64
+ // 2. Save to Local Hidden Config (.tspscale) - Primary
65
+ fs.writeFileSync(path.join(process.cwd(), '.tspscale'), JSON.stringify({ apiKey, projectId }, null, 2));
66
+
67
+ // 3. Auto-GitIgnore
68
+ const gitignorePath = path.join(process.cwd(), '.gitignore');
69
+ const ignoreLine = '\n# TSP Scale Config\n.tspscale\n';
70
+ if (fs.existsSync(gitignorePath)) {
71
+ const content = fs.readFileSync(gitignorePath, 'utf8');
72
+ if (!content.includes('.tspscale')) fs.appendFileSync(gitignorePath, ignoreLine);
73
+ } else {
74
+ fs.writeFileSync(gitignorePath, ignoreLine);
75
+ }
76
+
77
+ console.log("\nāœ… Success! Project linked and .tspscale config created.");
78
+ console.log(`šŸ“” Status: ${result.status}\n`);
79
+ console.log(`šŸ”’ Note: Added .tspscale to your .gitignore for security.\n`);
80
+
81
+ console.log("-------------------------------------------");
82
+ console.log("šŸš€ PRODUCTION DEPLOYMENT GUIDE");
83
+ console.log("-------------------------------------------");
84
+ console.log("When you deploy to Railway, Vercel, or a VPS,");
85
+ console.log("add these two Environment Variables:");
86
+ console.log("");
87
+ console.log(` TSP_API_KEY = ${apiKey}`);
88
+ console.log(` TSP_PROJECT_ID = ${projectId}`);
89
+ console.log("-------------------------------------------\n");
90
+
91
+ const install = await ask("šŸ“¦ Would you like to install the 'tsp-scale-sdk' in this project? (y/n): ");
92
+ if (install.toLowerCase() === 'y') {
93
+ console.log("ā³ Installing...");
94
+ try {
95
+ execSync('npm install tsp-scale-sdk', { stdio: 'inherit' });
96
+ console.log("\nāœ… SDK installed successfully!");
97
+ } catch (e) {
98
+ console.error("\nāŒ Installation failed. Please run 'npm install tsp-scale-sdk' manually.");
99
+ }
100
+ }
101
+
102
+ const example = await ask("šŸ“„ Would you like to generate a sample 'tsp-test.js' script? (y/n): ");
103
+ if (example.toLowerCase() === 'y') {
104
+ const sampleCode = `const { TspScaleClient } = require('tsp-scale-sdk');
105
+
106
+ // Smart Auth: Automatically uses .tspscale or environment variables
107
+ const client = new TspScaleClient();
108
+
109
+ async function main() {
110
+ console.log("Sending test email...");
111
+ try {
112
+ const res = await client.sendEmail({
113
+ // 'from' is optional if your key is locked to a sender identity
114
+ to: "recipient@example.com",
115
+ subject: "TSP Scale Test",
116
+ html: "<h1>It works!</h1>"
117
+ });
118
+ console.log("Response:", res);
119
+ } catch (err) {
120
+ console.error("Error:", err.message);
121
+ }
122
+ }
123
+
124
+ main();`;
125
+ fs.writeFileSync(path.join(process.cwd(), "tsp-test.js"), sampleCode);
126
+ console.log("\nāœ… 'tsp-test.js' created. Run it with: node tsp-test.js");
127
+ }
128
+ } catch (err) {
129
+ console.error(`\nāŒ Error: ${err.message}`);
130
+ }
131
+ }
132
+
133
+ const command = process.argv[2];
134
+ if (command === 'init') {
135
+ init();
136
+ } else {
137
+ console.log("Usage: npx tsp-scale-sdk init");
138
+ }
139
+
140
+ } catch (err) {
141
+ console.error("Initialization failed:", err.message);
142
+ }
package/dist/index.d.ts CHANGED
@@ -1,3 +1,9 @@
1
+ export type EmailAttachment = {
2
+ filename: string;
3
+ contentType: string;
4
+ content: string;
5
+ };
6
+
1
7
  export type SendEmailPayload = {
2
8
  to: string;
3
9
  from: string;
@@ -6,11 +12,37 @@ export type SendEmailPayload = {
6
12
  html?: string;
7
13
  bodyText?: string;
8
14
  bodyHtml?: string;
9
- attachments?: Array<{
10
- filename: string;
11
- contentType: string;
12
- content: string;
13
- }>;
15
+ priority?: number;
16
+ region?: string;
17
+ category?: string;
18
+ attachments?: EmailAttachment[];
19
+ expiresIn?: number;
20
+ useGhost?: boolean;
21
+ runForensics?: boolean;
22
+ isLocked?: boolean;
23
+ scheduledAt?: string;
24
+ templateId?: string;
25
+ viewPassword?: string;
26
+ };
27
+
28
+ export type SendEmailStatus = "QUEUED" | "SANDBOX_DELIVERED";
29
+
30
+ export type SendEmailResponse = {
31
+ id: string;
32
+ status: SendEmailStatus;
33
+ message?: string;
34
+ };
35
+
36
+ export type SendWhatsAppPayload = {
37
+ to: string;
38
+ text: string;
39
+ mediaUrl?: string;
40
+ configId?: string;
41
+ };
42
+
43
+ export type SendWhatsAppResponse = {
44
+ success: true;
45
+ message: string;
14
46
  };
15
47
 
16
48
  export type TspScaleClientOptions = {
@@ -23,5 +55,6 @@ export type TspScaleClientOptions = {
23
55
 
24
56
  export declare class TspScaleClient {
25
57
  constructor(options: TspScaleClientOptions);
26
- sendEmail(payload: SendEmailPayload): Promise<{ message: string; emailId: string }>;
58
+ sendEmail(payload: SendEmailPayload): Promise<SendEmailResponse>;
59
+ sendWhatsApp(payload: SendWhatsAppPayload): Promise<SendWhatsAppResponse>;
27
60
  }
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var m=require("crypto"),y={prod:"https://api.tspscale.in/api/v1",staging:"https://staging-api.tspscale.in/api/v1",local:"http://localhost:4000/api/v1"};function g(l){if(l.baseUrl)return l.baseUrl;let t=(l.env||"prod").toLowerCase();return y[t]||y.prod}var d=class{constructor(t){if(!t||!t.apiKey)throw new Error("apiKey is required");if(this.apiKey=t.apiKey,this.baseUrl=g(t).replace(/\/+$/,""),this.timeoutMs=t.timeoutMs||15e3,this.fetchImpl=t.fetchImpl||globalThis.fetch,typeof this.fetchImpl!="function")throw new Error("Fetch implementation is not available. Use Node 18+ or pass fetchImpl.")}async sendEmail(t){let e="/emails/send",c=`${this.baseUrl}${e}`,a=JSON.stringify(t||{}),n=Date.now().toString(),o=m.randomBytes(16).toString("hex"),h=this._sign({timestamp:n,nonce:o,method:"POST",path:e,body:a}),p=new AbortController,u=setTimeout(()=>p.abort(),this.timeoutMs);try{let s=await this.fetchImpl(c,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"x-tsp-client":"tsp-scale-sdk/1.0.0","x-tsp-timestamp":n,"x-tsp-nonce":o,"x-tsp-signature":h},body:a,signal:p.signal}),r=await s.json().catch(()=>({}));if(!s.ok){let i=new Error(r?.error||`Request failed with status ${s.status}`);throw i.status=s.status,i.response=r,i}return r}finally{clearTimeout(u)}}async sendWhatsApp(t){let e="/whatsapp/messages/send",c=`${this.baseUrl}${e}`,a=JSON.stringify(t||{}),n=Date.now().toString(),o=m.randomBytes(16).toString("hex"),h=this._sign({timestamp:n,nonce:o,method:"POST",path:e,body:a}),p=new AbortController,u=setTimeout(()=>p.abort(),this.timeoutMs);try{let s=await this.fetchImpl(c,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"x-tsp-client":"tsp-scale-sdk/1.0.0","x-tsp-timestamp":n,"x-tsp-nonce":o,"x-tsp-signature":h},body:a,signal:p.signal}),r=await s.json().catch(()=>({}));if(!s.ok){let i=new Error(r?.error||`Request failed with status ${s.status}`);throw i.status=s.status,i.response=r,i}return r}finally{clearTimeout(u)}}_sign({timestamp:t,nonce:e,method:c,path:a,body:n}){let o=`${t}.${e}.${c}.${a}.${n}`;return m.createHmac("sha256",this.apiKey).update(o).digest("hex")}};module.exports={TspScaleClient:d};
1
+ var d=require("crypto"),m="1.2.1",y={prod:"https://api.tspscale.in/api/v1",staging:"https://staging-api.tspscale.in/api/v1",local:"http://localhost:4000/api/v1"};function g(l){if(l.baseUrl)return l.baseUrl;let t=(l.env||"prod").toLowerCase();return y[t]||y.prod}var f=class{constructor(t){let s={};typeof t=="string"?s={apiKey:t}:s=t||{};let e=require("fs"),o=require("path"),a=require("os"),n=this._loadLocalConfig();if(this.apiKey=s.apiKey||process.env.TSP_API_KEY||n.apiKey||this._loadGlobalKey(),this.projectId=s.projectId||process.env.TSP_PROJECT_ID||n.projectId,this.apiKey||console.warn("\u26A0\uFE0F TSP Scale: No API Key found. Run 'npx tsp-scale init'."),this.baseUrl=g(s).replace(/\/+$/,""),this.timeoutMs=s.timeoutMs||15e3,this.fetchImpl=s.fetchImpl||globalThis.fetch,typeof this.fetchImpl!="function")throw new Error("Fetch implementation is not available. Use Node 18+ or pass fetchImpl.")}_loadLocalConfig(){try{let t=require("fs"),e=require("path").join(process.cwd(),".tspscale");if(t.existsSync(e))return JSON.parse(t.readFileSync(e,"utf8"))}catch{}return{}}_loadGlobalKey(){try{let t=require("fs"),s=require("path"),e=require("os"),o=s.join(e.homedir(),".tsp-scale","config.json");if(t.existsSync(o))return JSON.parse(t.readFileSync(o,"utf8")).apiKey}catch{}return null}async sendEmail(t){let s="/emails/send",e=`${this.baseUrl}${s}`,o=JSON.stringify(t||{}),a=Date.now().toString(),n=d.randomBytes(16).toString("hex"),h=this._sign({timestamp:a,nonce:n,method:"POST",path:s,body:o}),p=new AbortController,u=setTimeout(()=>p.abort(),this.timeoutMs);try{let i=await this.fetchImpl(e,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"x-tsp-client":`tsp-scale-sdk/${m}`,"x-tsp-timestamp":a,"x-tsp-nonce":n,"x-tsp-signature":h,...this.projectId?{"x-tsp-project-id":this.projectId}:{}},body:o,signal:p.signal}),r=await i.json().catch(()=>({}));if(!i.ok){let c=new Error(r?.error||`Request failed with status ${i.status}`);throw c.status=i.status,c.response=r,c}return r}finally{clearTimeout(u)}}async sendWhatsApp(t){let s="/whatsapp/messages/send",e=`${this.baseUrl}${s}`,o=JSON.stringify(t||{}),a=Date.now().toString(),n=d.randomBytes(16).toString("hex"),h=this._sign({timestamp:a,nonce:n,method:"POST",path:s,body:o}),p=new AbortController,u=setTimeout(()=>p.abort(),this.timeoutMs);try{let i=await this.fetchImpl(e,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"x-tsp-client":`tsp-scale-sdk/${m}`,"x-tsp-timestamp":a,"x-tsp-nonce":n,"x-tsp-signature":h},body:o,signal:p.signal}),r=await i.json().catch(()=>({}));if(!i.ok){let c=new Error(r?.error||`Request failed with status ${i.status}`);throw c.status=i.status,c.response=r,c}return r}finally{clearTimeout(u)}}_sign({timestamp:t,nonce:s,method:e,path:o,body:a}){let n=`${t}.${s}.${e}.${o}.${a}`;return d.createHmac("sha256",this.apiKey).update(n).digest("hex")}};module.exports={TspScaleClient:f};
2
2
  //# sourceMappingURL=index.js.map
package/package.json CHANGED
@@ -1,12 +1,15 @@
1
1
  {
2
2
  "name": "tsp-scale-sdk",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "description": "Official Node.js client for TSP Scale Email and WhatsApp API",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "author": "TSP Scale",
8
8
  "license": "MIT",
9
9
  "homepage": "https://tspscale.in",
10
+ "bin": {
11
+ "tsp-scale": "./bin/tsp-scale.js"
12
+ },
10
13
  "keywords": [
11
14
  "tsp",
12
15
  "smtp",