@trimlynk/sdk 0.0.0-stage → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +387 -2
  3. package/dist/cjs/cli/commands/analytics.d.ts +3 -0
  4. package/dist/cjs/cli/commands/analytics.js +80 -0
  5. package/dist/cjs/cli/commands/auth.d.ts +4 -0
  6. package/dist/cjs/cli/commands/auth.js +122 -0
  7. package/dist/cjs/cli/commands/campaigns.d.ts +6 -0
  8. package/dist/cjs/cli/commands/campaigns.js +229 -0
  9. package/dist/cjs/cli/commands/config.d.ts +3 -0
  10. package/dist/cjs/cli/commands/config.js +51 -0
  11. package/dist/cjs/cli/commands/conversions.d.ts +4 -0
  12. package/dist/cjs/cli/commands/conversions.js +160 -0
  13. package/dist/cjs/cli/commands/links.d.ts +6 -0
  14. package/dist/cjs/cli/commands/links.js +270 -0
  15. package/dist/cjs/cli/commands/webhooks.d.ts +10 -0
  16. package/dist/cjs/cli/commands/webhooks.js +510 -0
  17. package/dist/cjs/cli/configStore.d.ts +10 -0
  18. package/dist/cjs/cli/configStore.js +63 -0
  19. package/dist/cjs/cli/credentials.d.ts +23 -0
  20. package/dist/cjs/cli/credentials.js +235 -0
  21. package/dist/cjs/cli/exitCodes.d.ts +9 -0
  22. package/dist/cjs/cli/exitCodes.js +12 -0
  23. package/dist/cjs/cli/formatting.d.ts +19 -0
  24. package/dist/cjs/cli/formatting.js +110 -0
  25. package/dist/cjs/cli/index.d.ts +3 -0
  26. package/dist/cjs/cli/index.js +278 -0
  27. package/dist/cjs/cli/types.d.ts +13 -0
  28. package/dist/cjs/cli/types.js +2 -0
  29. package/dist/cjs/client.d.ts +89 -0
  30. package/dist/cjs/client.js +126 -0
  31. package/dist/cjs/config.d.ts +49 -0
  32. package/dist/cjs/config.js +67 -0
  33. package/dist/cjs/errors.d.ts +60 -0
  34. package/dist/cjs/errors.js +149 -0
  35. package/dist/cjs/events.d.ts +50 -0
  36. package/dist/cjs/events.js +153 -0
  37. package/dist/cjs/http.d.ts +30 -0
  38. package/dist/cjs/http.js +148 -0
  39. package/dist/cjs/index.d.ts +28 -0
  40. package/dist/cjs/index.js +58 -0
  41. package/dist/cjs/package.json +3 -0
  42. package/dist/cjs/pagination.d.ts +54 -0
  43. package/dist/cjs/pagination.js +111 -0
  44. package/dist/cjs/resources/analytics.d.ts +35 -0
  45. package/dist/cjs/resources/analytics.js +74 -0
  46. package/dist/cjs/resources/campaigns.d.ts +65 -0
  47. package/dist/cjs/resources/campaigns.js +139 -0
  48. package/dist/cjs/resources/conversions.d.ts +37 -0
  49. package/dist/cjs/resources/conversions.js +82 -0
  50. package/dist/cjs/resources/links.d.ts +95 -0
  51. package/dist/cjs/resources/links.js +199 -0
  52. package/dist/cjs/resources/webhooks.d.ts +66 -0
  53. package/dist/cjs/resources/webhooks.js +178 -0
  54. package/dist/cjs/security.d.ts +53 -0
  55. package/dist/cjs/security.js +156 -0
  56. package/dist/cjs/types.d.ts +149 -0
  57. package/dist/cjs/types.js +347 -0
  58. package/dist/cjs/utm.d.ts +36 -0
  59. package/dist/cjs/utm.js +44 -0
  60. package/dist/esm/cli/commands/analytics.d.ts +4 -0
  61. package/dist/esm/cli/commands/analytics.d.ts.map +1 -0
  62. package/dist/esm/cli/commands/analytics.js +77 -0
  63. package/dist/esm/cli/commands/analytics.js.map +1 -0
  64. package/dist/esm/cli/commands/auth.d.ts +5 -0
  65. package/dist/esm/cli/commands/auth.d.ts.map +1 -0
  66. package/dist/esm/cli/commands/auth.js +118 -0
  67. package/dist/esm/cli/commands/auth.js.map +1 -0
  68. package/dist/esm/cli/commands/campaigns.d.ts +7 -0
  69. package/dist/esm/cli/commands/campaigns.d.ts.map +1 -0
  70. package/dist/esm/cli/commands/campaigns.js +223 -0
  71. package/dist/esm/cli/commands/campaigns.js.map +1 -0
  72. package/dist/esm/cli/commands/config.d.ts +4 -0
  73. package/dist/esm/cli/commands/config.d.ts.map +1 -0
  74. package/dist/esm/cli/commands/config.js +48 -0
  75. package/dist/esm/cli/commands/config.js.map +1 -0
  76. package/dist/esm/cli/commands/conversions.d.ts +5 -0
  77. package/dist/esm/cli/commands/conversions.d.ts.map +1 -0
  78. package/dist/esm/cli/commands/conversions.js +156 -0
  79. package/dist/esm/cli/commands/conversions.js.map +1 -0
  80. package/dist/esm/cli/commands/links.d.ts +7 -0
  81. package/dist/esm/cli/commands/links.d.ts.map +1 -0
  82. package/dist/esm/cli/commands/links.js +264 -0
  83. package/dist/esm/cli/commands/links.js.map +1 -0
  84. package/dist/esm/cli/commands/webhooks.d.ts +11 -0
  85. package/dist/esm/cli/commands/webhooks.d.ts.map +1 -0
  86. package/dist/esm/cli/commands/webhooks.js +500 -0
  87. package/dist/esm/cli/commands/webhooks.js.map +1 -0
  88. package/dist/esm/cli/configStore.d.ts +11 -0
  89. package/dist/esm/cli/configStore.d.ts.map +1 -0
  90. package/dist/esm/cli/configStore.js +54 -0
  91. package/dist/esm/cli/configStore.js.map +1 -0
  92. package/dist/esm/cli/credentials.d.ts +24 -0
  93. package/dist/esm/cli/credentials.d.ts.map +1 -0
  94. package/dist/esm/cli/credentials.js +226 -0
  95. package/dist/esm/cli/credentials.js.map +1 -0
  96. package/dist/esm/cli/exitCodes.d.ts +10 -0
  97. package/dist/esm/cli/exitCodes.d.ts.map +1 -0
  98. package/dist/esm/cli/exitCodes.js +10 -0
  99. package/dist/esm/cli/exitCodes.js.map +1 -0
  100. package/dist/esm/cli/formatting.d.ts +20 -0
  101. package/dist/esm/cli/formatting.d.ts.map +1 -0
  102. package/dist/esm/cli/formatting.js +95 -0
  103. package/dist/esm/cli/formatting.js.map +1 -0
  104. package/dist/esm/cli/index.d.ts +4 -0
  105. package/dist/esm/cli/index.d.ts.map +1 -0
  106. package/dist/esm/cli/index.js +276 -0
  107. package/dist/esm/cli/index.js.map +1 -0
  108. package/dist/esm/cli/types.d.ts +14 -0
  109. package/dist/esm/cli/types.d.ts.map +1 -0
  110. package/dist/esm/cli/types.js +2 -0
  111. package/dist/esm/cli/types.js.map +1 -0
  112. package/dist/esm/client.d.ts +90 -0
  113. package/dist/esm/client.d.ts.map +1 -0
  114. package/dist/esm/client.js +123 -0
  115. package/dist/esm/client.js.map +1 -0
  116. package/dist/esm/config.d.ts +50 -0
  117. package/dist/esm/config.d.ts.map +1 -0
  118. package/dist/esm/config.js +64 -0
  119. package/dist/esm/config.js.map +1 -0
  120. package/dist/esm/errors.d.ts +61 -0
  121. package/dist/esm/errors.d.ts.map +1 -0
  122. package/dist/esm/errors.js +130 -0
  123. package/dist/esm/errors.js.map +1 -0
  124. package/dist/esm/events.d.ts +51 -0
  125. package/dist/esm/events.d.ts.map +1 -0
  126. package/dist/esm/events.js +149 -0
  127. package/dist/esm/events.js.map +1 -0
  128. package/dist/esm/http.d.ts +31 -0
  129. package/dist/esm/http.d.ts.map +1 -0
  130. package/dist/esm/http.js +145 -0
  131. package/dist/esm/http.js.map +1 -0
  132. package/dist/esm/index.d.ts +29 -0
  133. package/dist/esm/index.d.ts.map +1 -0
  134. package/dist/esm/index.js +16 -0
  135. package/dist/esm/index.js.map +1 -0
  136. package/dist/esm/pagination.d.ts +55 -0
  137. package/dist/esm/pagination.d.ts.map +1 -0
  138. package/dist/esm/pagination.js +106 -0
  139. package/dist/esm/pagination.js.map +1 -0
  140. package/dist/esm/resources/analytics.d.ts +36 -0
  141. package/dist/esm/resources/analytics.d.ts.map +1 -0
  142. package/dist/esm/resources/analytics.js +71 -0
  143. package/dist/esm/resources/analytics.js.map +1 -0
  144. package/dist/esm/resources/campaigns.d.ts +66 -0
  145. package/dist/esm/resources/campaigns.d.ts.map +1 -0
  146. package/dist/esm/resources/campaigns.js +136 -0
  147. package/dist/esm/resources/campaigns.js.map +1 -0
  148. package/dist/esm/resources/conversions.d.ts +38 -0
  149. package/dist/esm/resources/conversions.d.ts.map +1 -0
  150. package/dist/esm/resources/conversions.js +79 -0
  151. package/dist/esm/resources/conversions.js.map +1 -0
  152. package/dist/esm/resources/links.d.ts +96 -0
  153. package/dist/esm/resources/links.d.ts.map +1 -0
  154. package/dist/esm/resources/links.js +196 -0
  155. package/dist/esm/resources/links.js.map +1 -0
  156. package/dist/esm/resources/webhooks.d.ts +67 -0
  157. package/dist/esm/resources/webhooks.d.ts.map +1 -0
  158. package/dist/esm/resources/webhooks.js +175 -0
  159. package/dist/esm/resources/webhooks.js.map +1 -0
  160. package/dist/esm/security.d.ts +54 -0
  161. package/dist/esm/security.d.ts.map +1 -0
  162. package/dist/esm/security.js +153 -0
  163. package/dist/esm/security.js.map +1 -0
  164. package/dist/esm/types.d.ts +150 -0
  165. package/dist/esm/types.d.ts.map +1 -0
  166. package/dist/esm/types.js +335 -0
  167. package/dist/esm/types.js.map +1 -0
  168. package/dist/esm/utm.d.ts +37 -0
  169. package/dist/esm/utm.d.ts.map +1 -0
  170. package/dist/esm/utm.js +42 -0
  171. package/dist/esm/utm.js.map +1 -0
  172. package/package.json +89 -4
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ TrimLynk Software Development Kit (SDK) End-User License Agreement
2
+
3
+ Copyright (c) 2026 Vivek Gaur, Ashish Kumar Dwivedi / TrimLynk. All rights reserved.
4
+
5
+ 1. GRANT OF USE
6
+ TrimLynk hereby grants you a personal, worldwide, non-exclusive, non-transferable, revocable license to install, import, and execute this software package in your applications solely for the purpose of integrating with and consuming TrimLynk APIs and services.
7
+
8
+ 2. RESTRICTIONS
9
+ Except as expressly permitted by applicable law, you may not:
10
+ (a) Modify, adapt, translate, reverse engineer, decompile, or disassemble any portion of the software;
11
+ (b) Create derivative works based on the software;
12
+ (c) Rent, lease, loan, resell, sublicense, or distribute modified copies of the software to any third party;
13
+ (d) Remove or obscure any proprietary notices, labels, or marks on the software.
14
+
15
+ 3. INTELLECTUAL PROPERTY
16
+ The software, including its architecture, interfaces, and documentation, constitutes proprietary intellectual property of TrimLynk. No ownership rights are transferred to you.
17
+
18
+ 4. DISCLAIMER OF WARRANTIES
19
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE THEREOF.
package/README.md CHANGED
@@ -1,3 +1,388 @@
1
- # Temporary Holding Version
1
+ # TrimLynk — Official Node.js & TypeScript SDK & CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Official Node.js / TypeScript client library and CLI for the **TrimLynk Developer API v1**.
4
+
5
+ TrimLynk is a modern, privacy-first URL shortening, link intelligence, and conversion attribution platform. `@trimlynk/sdk` enables developers to programmatically create branded short links, query click and funnel telemetry, track attributed conversions, organize marketing campaigns, export QR codes, and verify real-time webhooks with **zero runtime dependencies**.
6
+
7
+ [![npm version](https://img.shields.io/npm/v/@trimlynk/sdk.svg)](https://www.npmjs.com/package/@trimlynk/sdk)
8
+ [![Node.js Version](https://img.shields.io/badge/node-%3E%3D22.0.0-brightgreen.svg)](https://nodejs.org)
9
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Included-blue.svg)](https://www.typescriptlang.org/)
10
+ [![Dependencies](https://img.shields.io/badge/dependencies-0-success.svg)](https://www.npmjs.com/package/@trimlynk/sdk)
11
+ [![License: Proprietary](https://img.shields.io/badge/license-Proprietary-red.svg)](https://trimlynk.com/terms)
12
+
13
+ ---
14
+
15
+ > **Hosted SaaS API:** `@trimlynk/sdk` is the official client library and CLI for the hosted TrimLynk Developer API (`https://api.trimlynk.com/api/v1/developer/*`). Installing this package does not start a local URL shortener server; it connects your applications and automation workflows to your TrimLynk workspace using an API key.
16
+
17
+ ---
18
+
19
+ ### Official Resources & Documentation
20
+
21
+ [Platform Dashboard](https://trimlynk.com) · [Developer Hub](https://trimlynk.com/developers) · [SDK Documentation](https://trimlynk.com/developers/sdks) · [API Reference](https://trimlynk.com/api-docs) · [Webhooks Guide](https://trimlynk.com/developers/webhooks) · [CLI Guide](https://trimlynk.com/developers/cli) · [Support](https://trimlynk.com/contact)
22
+
23
+ ---
24
+
25
+ ## Key Capabilities
26
+
27
+ * **Programmatic Branded Short Links**: Create, update, search, and deactivate links with custom slugs, expiration dates, tags, and automatic UTM decoration.
28
+ * **Dual ESM & CommonJS + Strict TypeScript**: Native `import` and `require()` support with full `.d.ts` declarations and a dedicated `@trimlynk/sdk/webhooks` subpath export.
29
+ * **Zero Runtime Dependencies**: Built entirely on native Node.js `fetch`, `node:crypto`, `node:util`, and `node:fs` (Node.js `>=22.0.0`).
30
+ * **Auto-Pagination & Bulk Concurrency**: Stream across all pages with `for await ... of client.links.iter()` and batch-create links with bounded concurrency via `createMany()`.
31
+ * **QR Code Generation & Export**: Save PNG or SVG QR codes directly to disk with `link.saveQr()` or `client.links.downloadQr()`.
32
+ * **Audience Analytics & Funnel Attribution**: Retrieve workspace summaries, per-link telemetry, and Click → Lead → Purchase conversion funnels.
33
+ * **Webhook Verification & Replay Protection**: 1-line HMAC-SHA256 verification and typed event parsing via `client.webhooks.constructEvent()` or `@trimlynk/sdk/webhooks`.
34
+ * **Idempotent Mutations**: Safely retry link, campaign, conversion, and webhook creations with `idempotencyKey` and inspect `result.idempotentReplay`.
35
+ * **Bundled `trimlynk` CLI**: Manage links, analytics, campaigns, conversions, and local webhook tunneling from your terminal with OS keychain credential storage.
36
+
37
+ ---
38
+
39
+ ## Installation
40
+
41
+ ```bash
42
+ npm install @trimlynk/sdk
43
+ ```
44
+
45
+ Or install globally to use the `trimlynk` CLI everywhere:
46
+
47
+ ```bash
48
+ npm install -g @trimlynk/sdk
49
+ ```
50
+
51
+ Requires **Node.js `>=22.0.0`**. Both ESM and CommonJS are supported out of the box:
52
+
53
+ ```ts
54
+ // ESM / TypeScript
55
+ import { TrimLynk } from "@trimlynk/sdk";
56
+ ```
57
+
58
+ ```js
59
+ // CommonJS
60
+ const { TrimLynk } = require("@trimlynk/sdk");
61
+ ```
62
+
63
+ ---
64
+
65
+ ## 30-Second Quickstart
66
+
67
+ ```ts
68
+ import { TrimLynk } from "@trimlynk/sdk";
69
+
70
+ // Reads process.env.TRIMLYNK_API_KEY automatically if apiKey is omitted
71
+ const client = new TrimLynk({
72
+ apiKey: process.env.TRIMLYNK_API_KEY,
73
+ });
74
+
75
+ const link = await client.links.create({
76
+ originalUrl: "https://example.com/pricing",
77
+ customSlug: "pricing-2026",
78
+ title: "Pricing Page",
79
+ tags: ["marketing", "launch"],
80
+ utmSource: "newsletter",
81
+ utmMedium: "email",
82
+ autoDecorateUtm: true,
83
+ });
84
+
85
+ console.log(`Short URL: ${link.shortUrl}`);
86
+ console.log(`Link ID: ${link.id}`);
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Authentication & Configuration
92
+
93
+ Generate an API key in your TrimLynk workspace under **Settings → API Keys** ([Developer Hub](https://trimlynk.com/developers)).
94
+
95
+ ### Environment Variables (Recommended)
96
+
97
+ ```bash
98
+ export TRIMLYNK_API_KEY="tl_live_your_api_key_here"
99
+ ```
100
+
101
+ ```ts
102
+ import { TrimLynk } from "@trimlynk/sdk";
103
+
104
+ const client = new TrimLynk();
105
+ ```
106
+
107
+ ### Explicit Client Options
108
+
109
+ ```ts
110
+ import { TrimLynk } from "@trimlynk/sdk";
111
+
112
+ const client = new TrimLynk({
113
+ apiKey: process.env.TRIMLYNK_API_KEY,
114
+ environment: "live", // "live" (default) or "test"
115
+ baseUrl: "https://api.trimlynk.com", // Optional override (or TRIMLYNK_BASE_URL)
116
+ timeout: 30_000, // Request timeout in ms (default: 30000)
117
+ maxRetries: 2, // Automatic retries on HTTP 429 (default: 0)
118
+ fetch: globalThis.fetch, // Optional custom fetch for edge/test runtimes
119
+ });
120
+ ```
121
+
122
+ ---
123
+
124
+ ## SDK Usage Guide
125
+
126
+ ### 1. Short Links (`client.links`)
127
+
128
+ ```ts
129
+ // Create with expiration Date and idempotency key
130
+ const link = await client.links.create({
131
+ originalUrl: "https://example.com/launch",
132
+ customSlug: "launch-2026",
133
+ tags: ["campaign", "social"],
134
+ expiresAt: new Date("2026-12-31T23:59:59Z"),
135
+ idempotencyKey: "launch-link-2026-v1",
136
+ });
137
+
138
+ // Get, update, or delete
139
+ const fetched = await client.links.get(link.id);
140
+ const updated = await client.links.update(link.id, { isActive: true, title: "Launch" });
141
+
142
+ // Save QR code directly to disk (supports data URI, SVG, or image URL)
143
+ await link.saveQr("./launch-qr.png");
144
+ await client.links.downloadQr(link.id, "./launch-qr-copy.png");
145
+
146
+ // Bulk create concurrently while preserving order
147
+ const created = await client.links.createMany(
148
+ [
149
+ { originalUrl: "https://example.com/a" },
150
+ { originalUrl: "https://example.com/b" },
151
+ ],
152
+ { concurrency: 5 },
153
+ );
154
+
155
+ // Auto-paginate across all links
156
+ for await (const item of client.links.iter({ tag: "campaign", limit: 50 })) {
157
+ console.log(`${item.shortUrl} -> ${item.clicks} clicks`);
158
+ }
159
+
160
+ // Or collect all pages into an array
161
+ const allLinks = await client.links.iter({ search: "launch" }).toArray();
162
+ ```
163
+
164
+ ### 2. Analytics & Funnels (`client.analytics`)
165
+
166
+ ```ts
167
+ // Workspace analytics summary
168
+ const summary = await client.analytics.get({
169
+ startDate: "2026-01-01",
170
+ endDate: "2026-12-31",
171
+ });
172
+ console.log(summary.totalClicks, summary.uniqueVisitors, summary.countries);
173
+
174
+ // Per-link analytics
175
+ const linkStats = await client.analytics.getLink("lnk_123");
176
+
177
+ // Conversion funnel metrics (Click -> Lead -> Sale)
178
+ const funnel = await client.analytics.conversions({ urlId: "lnk_123" });
179
+ console.log(funnel);
180
+ ```
181
+
182
+ ### 3. Conversions (`client.conversions`)
183
+
184
+ ```ts
185
+ const conversion = await client.conversions.create({
186
+ linkId: "lnk_123",
187
+ eventName: "purchase",
188
+ revenue: 99.0,
189
+ currency: "USD",
190
+ orderId: "ord_10492",
191
+ clickId: "tlclid_abc123",
192
+ idempotencyKey: "conv-ord_10492",
193
+ });
194
+
195
+ for await (const item of client.conversions.iter({ eventName: "purchase" })) {
196
+ console.log(item.id, item.eventValue, item.currency);
197
+ }
198
+ ```
199
+
200
+ ### 4. Campaigns (`client.campaigns`)
201
+
202
+ ```ts
203
+ const campaign = await client.campaigns.create({
204
+ name: "Q4 Product Launch",
205
+ utmSource: "newsletter",
206
+ utmMedium: "email",
207
+ utmCampaign: "q4-launch",
208
+ goal: 10_000,
209
+ });
210
+
211
+ const campaignsPage = await client.campaigns.list({ page: 1, limit: 20 });
212
+ await client.campaigns.update(campaign.id, { status: "active" });
213
+ ```
214
+
215
+ ### 5. Webhooks & Signature Verification (`client.webhooks` & `@trimlynk/sdk/webhooks`)
216
+
217
+ Register and manage endpoints:
218
+
219
+ ```ts
220
+ const webhook = await client.webhooks.create({
221
+ url: "https://example.com/webhooks/trimlynk",
222
+ events: ["click.created", "conversion.created"],
223
+ description: "Production billing & analytics listener",
224
+ });
225
+ // Store webhook.secret securely — it is only returned on creation
226
+
227
+ await client.webhooks.test(webhook.id);
228
+ const deliveries = await client.webhooks.deliveries(webhook.id);
229
+ ```
230
+
231
+ Verify incoming webhook payloads without even instantiating a full API client using the lightweight `@trimlynk/sdk/webhooks` subpath export (or `TrimLynk.constructWebhookEvent` / `client.webhooks.constructEvent`):
232
+
233
+ ```ts
234
+ import express from "express";
235
+ import { TrimLynk, SignatureVerificationError } from "@trimlynk/sdk";
236
+ // Or import standalone verification helpers:
237
+ // import { verifyWebhookSignature, validateWebhookSignature } from "@trimlynk/sdk/webhooks";
238
+
239
+ const app = express();
240
+
241
+ app.post(
242
+ "/webhooks/trimlynk",
243
+ express.raw({ type: "application/json" }),
244
+ (req, res) => {
245
+ try {
246
+ const event = TrimLynk.constructWebhookEvent({
247
+ rawPayload: req.body,
248
+ signatureHeader: String(req.headers["x-trimlynk-signature"] ?? ""),
249
+ secret: process.env.TRIMLYNK_WEBHOOK_SECRET!,
250
+ });
251
+
252
+ if (event.isConversion) {
253
+ console.log(`Conversion: ${event.eventName} (${event.eventValue})`);
254
+ } else if (event.isClick) {
255
+ console.log(`Click on ${event.shortCode}`);
256
+ }
257
+
258
+ res.status(200).json({ received: true });
259
+ } catch (err) {
260
+ if (err instanceof SignatureVerificationError) {
261
+ res.status(400).send(`Invalid signature: ${err.message}`);
262
+ return;
263
+ }
264
+ throw err;
265
+ }
266
+ },
267
+ );
268
+ ```
269
+
270
+ ### 6. UTM Builder (`buildUtmUrl`)
271
+
272
+ ```ts
273
+ import { buildUtmUrl } from "@trimlynk/sdk";
274
+
275
+ const taggedUrl = buildUtmUrl("https://example.com/pro?ref=home#pricing", {
276
+ source: "twitter",
277
+ medium: "social",
278
+ campaign: "spring-2026",
279
+ });
280
+ // -> "https://example.com/pro?ref=home&utm_source=twitter&utm_medium=social&utm_campaign=spring-2026#pricing"
281
+ ```
282
+
283
+ ---
284
+
285
+ ## Error Handling
286
+
287
+ All SDK errors extend `TrimLynkError`, making error handling predictable and type-safe:
288
+
289
+ ```ts
290
+ import {
291
+ TrimLynk,
292
+ AuthenticationError,
293
+ InvalidRequestError,
294
+ NotFoundError,
295
+ RateLimitError,
296
+ IdempotencyConflictError,
297
+ TimeoutError,
298
+ NetworkError,
299
+ } from "@trimlynk/sdk";
300
+
301
+ try {
302
+ await client.links.get("lnk_missing");
303
+ } catch (err) {
304
+ if (err instanceof RateLimitError) {
305
+ console.error(`Rate limited. Retry after ${err.retryAfter}s [request_id=${err.requestId}]`);
306
+ } else if (err instanceof NotFoundError) {
307
+ console.error(`Not found: ${err.message}`);
308
+ } else if (err instanceof AuthenticationError) {
309
+ console.error("Invalid or missing API key");
310
+ } else if (err instanceof InvalidRequestError) {
311
+ console.error("Validation error:", err.details);
312
+ } else if (err instanceof IdempotencyConflictError) {
313
+ console.error("Idempotency key reused with different payload");
314
+ } else if (err instanceof TimeoutError || err instanceof NetworkError) {
315
+ console.error("Network failure:", err.message);
316
+ } else {
317
+ throw err;
318
+ }
319
+ }
320
+ ```
321
+
322
+ ---
323
+
324
+ ## CLI Usage (`trimlynk`)
325
+
326
+ The package installs the `trimlynk` CLI binary with native OS keychain credential storage (macOS Keychain, Windows DPAPI, Linux Secret Service) plus `0600` file fallback in `~/.trimlynk`.
327
+
328
+ ```bash
329
+ # Authenticate interactively or check status
330
+ trimlynk auth login
331
+ trimlynk auth status --check
332
+
333
+ # Create, list, update, or delete links
334
+ trimlynk links create https://example.com --slug demo --tag launch --quiet
335
+ trimlynk links list --all --json
336
+ trimlynk links get <linkId>
337
+
338
+ # Analytics, campaigns, and conversions
339
+ trimlynk analytics summary
340
+ trimlynk analytics link <linkId>
341
+ trimlynk campaigns list --json
342
+ trimlynk conversions list --json
343
+
344
+ # Webhooks & local tunnel forwarding
345
+ trimlynk webhooks list
346
+ trimlynk webhooks listen --tunnel-url https://your-tunnel.example.com
347
+
348
+ # Persistent CLI defaults
349
+ trimlynk config set environment live
350
+ trimlynk config get environment
351
+ ```
352
+
353
+ ### Global CLI Flags & Exit Codes
354
+
355
+ * `--json` — Raw machine-readable JSON output
356
+ * `-q`, `--quiet` — Minimal output (primary IDs / short URLs only)
357
+ * `--api-key <KEY>` — Override API key for one command
358
+ * `--environment <ENV>` — `live` or `test`
359
+ * `--base-url <URL>` — Override API base URL
360
+ * `--version` / `-h, --help`
361
+
362
+ | Exit Code | Meaning |
363
+ | :--- | :--- |
364
+ | `0` | Success |
365
+ | `1` | General error |
366
+ | `2` | Invalid arguments / validation error |
367
+ | `3` | Authentication error |
368
+ | `4` | Permission error |
369
+ | `5` | Resource not found |
370
+ | `6` | Rate limited |
371
+ | `7` | API / server error |
372
+ | `8` | Network / timeout error |
373
+
374
+ ---
375
+
376
+ ## Documentation, Support & License
377
+
378
+ | Resource | Link |
379
+ | :--- | :--- |
380
+ | **Developer Hub** | [https://trimlynk.com/developers](https://trimlynk.com/developers) |
381
+ | **SDK Documentation** | [https://trimlynk.com/developers/sdks](https://trimlynk.com/developers/sdks) |
382
+ | **API Reference** | [https://trimlynk.com/api-docs](https://trimlynk.com/api-docs) |
383
+ | **Webhooks Guide** | [https://trimlynk.com/developers/webhooks](https://trimlynk.com/developers/webhooks) |
384
+ | **CLI Guide** | [https://trimlynk.com/developers/cli](https://trimlynk.com/developers/cli) |
385
+ | **Support & Bug Reports** | [https://trimlynk.com/contact](https://trimlynk.com/contact) · `support@trimlynk.com` |
386
+ | **Terms & Privacy** | [Terms of Service](https://trimlynk.com/terms) · [Privacy Policy](https://trimlynk.com/privacy) |
387
+
388
+ Licensed under the TrimLynk Software Development Kit (SDK) End-User License Agreement — see the `LICENSE` file included in this package and [Terms of Service](https://trimlynk.com/terms).
@@ -0,0 +1,3 @@
1
+ import type { ClientFactory, GlobalCliOptions } from "../types.js";
2
+ export declare function cmdAnalyticsSummary(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
3
+ export declare function cmdAnalyticsLink(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cmdAnalyticsSummary = cmdAnalyticsSummary;
4
+ exports.cmdAnalyticsLink = cmdAnalyticsLink;
5
+ const node_util_1 = require("node:util");
6
+ const exitCodes_js_1 = require("../exitCodes.js");
7
+ const formatting_js_1 = require("../formatting.js");
8
+ async function cmdAnalyticsSummary(argv, opts, getClient) {
9
+ const { values } = (0, node_util_1.parseArgs)({
10
+ args: argv,
11
+ allowPositionals: false,
12
+ options: {
13
+ "start-date": { type: "string" },
14
+ "end-date": { type: "string" },
15
+ "url-id": { type: "string" },
16
+ "link-id": { type: "string" },
17
+ },
18
+ });
19
+ const client = getClient();
20
+ const summary = await client.analytics.get({
21
+ startDate: values["start-date"],
22
+ endDate: values["end-date"],
23
+ urlId: values["url-id"] ?? values["link-id"],
24
+ });
25
+ if (opts.quiet) {
26
+ process.stdout.write(`${summary.totalClicks}\n`);
27
+ }
28
+ else if (opts.json) {
29
+ (0, formatting_js_1.outputJson)(summary);
30
+ }
31
+ else {
32
+ (0, formatting_js_1.printDetails)([
33
+ ["Total Clicks:", summary.totalClicks],
34
+ ["Unique Visitors:", summary.uniqueVisitors],
35
+ ["Request ID:", summary.requestId],
36
+ ]);
37
+ const countryRows = Object.entries(summary.countries)
38
+ .slice(0, 10)
39
+ .map(([c, n]) => [c, n]);
40
+ if (countryRows.length > 0) {
41
+ process.stdout.write("\nTop Countries:\n");
42
+ (0, formatting_js_1.printTable)(["COUNTRY", "CLICKS"], countryRows);
43
+ }
44
+ }
45
+ return exitCodes_js_1.EXIT_SUCCESS;
46
+ }
47
+ async function cmdAnalyticsLink(argv, opts, getClient) {
48
+ const { values, positionals } = (0, node_util_1.parseArgs)({
49
+ args: argv,
50
+ allowPositionals: true,
51
+ options: {
52
+ "start-date": { type: "string" },
53
+ "end-date": { type: "string" },
54
+ },
55
+ });
56
+ const linkId = positionals[0];
57
+ if (!linkId) {
58
+ (0, formatting_js_1.printError)("Missing required <link_id> argument.");
59
+ return exitCodes_js_1.EXIT_INVALID_ARGS;
60
+ }
61
+ const client = getClient();
62
+ const data = await client.analytics.getLink(linkId, {
63
+ startDate: values["start-date"],
64
+ endDate: values["end-date"],
65
+ });
66
+ if (opts.quiet) {
67
+ process.stdout.write(`${data.clicks}\n`);
68
+ }
69
+ else if (opts.json) {
70
+ (0, formatting_js_1.outputJson)(data);
71
+ }
72
+ else {
73
+ (0, formatting_js_1.printDetails)([
74
+ ["Link ID:", data.linkId],
75
+ ["Clicks:", data.clicks],
76
+ ["Request ID:", data.requestId],
77
+ ]);
78
+ }
79
+ return exitCodes_js_1.EXIT_SUCCESS;
80
+ }
@@ -0,0 +1,4 @@
1
+ import type { ClientFactory, GlobalCliOptions } from "../types.js";
2
+ export declare function cmdLogin(opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
3
+ export declare function cmdLogout(opts: GlobalCliOptions): Promise<number>;
4
+ export declare function cmdStatus(opts: GlobalCliOptions, getClient: ClientFactory, check: boolean): Promise<number>;
@@ -0,0 +1,122 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.cmdLogin = cmdLogin;
4
+ exports.cmdLogout = cmdLogout;
5
+ exports.cmdStatus = cmdStatus;
6
+ const promises_1 = require("node:readline/promises");
7
+ const errors_js_1 = require("../../errors.js");
8
+ const credentials_js_1 = require("../credentials.js");
9
+ const exitCodes_js_1 = require("../exitCodes.js");
10
+ const formatting_js_1 = require("../formatting.js");
11
+ async function cmdLogin(opts, getClient) {
12
+ let apiKey = opts.apiKey;
13
+ if (!apiKey) {
14
+ if (!process.stdin.isTTY) {
15
+ (0, formatting_js_1.printError)("Cannot prompt for API key in non-interactive environment. Use TRIMLYNK_API_KEY or --api-key.");
16
+ return exitCodes_js_1.EXIT_AUTHENTICATION_ERROR;
17
+ }
18
+ const rl = (0, promises_1.createInterface)({ input: process.stdin, output: process.stdout });
19
+ try {
20
+ apiKey = (await rl.question("TrimLynk API key: ")).trim();
21
+ }
22
+ catch {
23
+ process.stdout.write("\nAborted.\n");
24
+ return exitCodes_js_1.EXIT_GENERAL_ERROR;
25
+ }
26
+ finally {
27
+ rl.close();
28
+ }
29
+ }
30
+ if (!apiKey) {
31
+ (0, formatting_js_1.printError)("API key cannot be empty.");
32
+ return exitCodes_js_1.EXIT_AUTHENTICATION_ERROR;
33
+ }
34
+ try {
35
+ const client = getClient({ apiKey });
36
+ await client.links.list({ limit: 1 });
37
+ }
38
+ catch (err) {
39
+ if (err instanceof errors_js_1.AuthenticationError) {
40
+ (0, formatting_js_1.printError)(`Authentication failed: ${err.message}`, {
41
+ code: err.code,
42
+ requestId: err.requestId,
43
+ });
44
+ return exitCodes_js_1.EXIT_AUTHENTICATION_ERROR;
45
+ }
46
+ if (err instanceof errors_js_1.TrimLynkError) {
47
+ (0, formatting_js_1.printError)(`Failed to verify API key: ${err.message}`);
48
+ return exitCodes_js_1.EXIT_GENERAL_ERROR;
49
+ }
50
+ throw err;
51
+ }
52
+ (0, credentials_js_1.saveApiKey)(apiKey);
53
+ if (opts.json) {
54
+ (0, formatting_js_1.outputJson)({
55
+ authenticated: true,
56
+ masked_key: (0, credentials_js_1.maskApiKey)(apiKey),
57
+ environment: opts.environment ?? "live",
58
+ });
59
+ }
60
+ else if (!opts.quiet) {
61
+ process.stdout.write(`${(0, formatting_js_1.green)("✓ Successfully authenticated with TrimLynk")}\n`);
62
+ process.stdout.write(`Stored API Key: ${(0, credentials_js_1.maskApiKey)(apiKey)}\n`);
63
+ }
64
+ return exitCodes_js_1.EXIT_SUCCESS;
65
+ }
66
+ async function cmdLogout(opts) {
67
+ const removed = (0, credentials_js_1.deleteApiKey)();
68
+ if (opts.json) {
69
+ (0, formatting_js_1.outputJson)({ logged_out: true, credentials_removed: removed });
70
+ }
71
+ else if (!opts.quiet) {
72
+ if (removed) {
73
+ process.stdout.write(`${(0, formatting_js_1.green)("✓ Successfully logged out from TrimLynk")}\n`);
74
+ }
75
+ else {
76
+ process.stdout.write("No stored credentials found.\n");
77
+ }
78
+ }
79
+ return exitCodes_js_1.EXIT_SUCCESS;
80
+ }
81
+ async function cmdStatus(opts, getClient, check) {
82
+ const apiKey = (0, credentials_js_1.resolveApiKey)(opts.apiKey);
83
+ const env = opts.environment ?? "live";
84
+ const source = (0, credentials_js_1.getCredentialSource)(opts.apiKey);
85
+ let remoteStatus = "not checked";
86
+ if (check && apiKey) {
87
+ try {
88
+ const client = getClient({ apiKey });
89
+ await client.links.list({ limit: 1 });
90
+ remoteStatus = "valid";
91
+ }
92
+ catch (err) {
93
+ if (err instanceof errors_js_1.AuthenticationError) {
94
+ remoteStatus = "invalid / expired";
95
+ }
96
+ else {
97
+ remoteStatus = `error checking (${err instanceof Error ? err.message : String(err)})`;
98
+ }
99
+ }
100
+ }
101
+ if (opts.json) {
102
+ (0, formatting_js_1.outputJson)({
103
+ authenticated: Boolean(apiKey),
104
+ environment: env,
105
+ api_key: (0, credentials_js_1.maskApiKey)(apiKey),
106
+ source,
107
+ remote_status: remoteStatus,
108
+ api_version: "1",
109
+ });
110
+ }
111
+ else {
112
+ (0, formatting_js_1.printDetails)([
113
+ ["Authenticated:", apiKey ? "yes" : "no"],
114
+ ["Environment:", env],
115
+ ["API Key:", (0, credentials_js_1.maskApiKey)(apiKey)],
116
+ ["Source:", source],
117
+ ["Remote Status:", remoteStatus],
118
+ ["API Version:", "1"],
119
+ ]);
120
+ }
121
+ return exitCodes_js_1.EXIT_SUCCESS;
122
+ }
@@ -0,0 +1,6 @@
1
+ import type { ClientFactory, GlobalCliOptions } from "../types.js";
2
+ export declare function cmdCampaignsCreate(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
3
+ export declare function cmdCampaignsList(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
4
+ export declare function cmdCampaignsGet(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
5
+ export declare function cmdCampaignsUpdate(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;
6
+ export declare function cmdCampaignsDelete(argv: string[], opts: GlobalCliOptions, getClient: ClientFactory): Promise<number>;