@cshah18/sdk 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,454 @@
1
+ # CoBuy Embedded SDK
2
+
3
+ A lightweight, production-ready TypeScript SDK for embedding CoBuy's collaborative purchasing widget in your web applications. The SDK exposes a global `window.CoBuy` object that can be loaded via a `<script>` tag.
4
+
5
+ ## Features
6
+
7
+ - 📦 **Lightweight**: ~7.5 KB (ESM, minified)
8
+ - 🎯 **Type-Safe**: Full TypeScript support with comprehensive type definitions
9
+ - 🚀 **Easy Integration**: Simple `<script>` tag integration
10
+ - ⚙️ **Configurable**: Support for multiple environments and theme customization
11
+ - 🔧 **Well-Tested**: ESLint + TypeScript strict mode
12
+ - 📝 **Documented**: Comprehensive JSDoc comments and examples
13
+
14
+ ## Installation
15
+
16
+ ### Via Script Tag (Browser)
17
+
18
+ ```html
19
+ <script src="https://cdn.cobuy.app/cobuy-sdk.umd.js"></script>
20
+ <script>
21
+ window.CoBuy.init({
22
+ merchantKey: "your-merchant-key",
23
+ env: "production",
24
+ });
25
+
26
+ window.CoBuy.renderWidget({
27
+ productId: "prod_123",
28
+ container: "#cobuy-widget",
29
+ });
30
+ </script>
31
+ ```
32
+
33
+ ### Via NPM (for Module Bundlers)
34
+
35
+ ```bash
36
+ npm install @cobuy/sdk
37
+ ```
38
+
39
+ ```typescript
40
+ import CoBuy from "@cobuy/sdk";
41
+
42
+ CoBuy.init({
43
+ merchantKey: "your-merchant-key",
44
+ env: "production",
45
+ });
46
+
47
+ CoBuy.renderWidget({
48
+ productId: "prod_123",
49
+ container: "#cobuy-widget",
50
+ });
51
+ ```
52
+
53
+ ## Quick Start
54
+
55
+ ### 1. Initialize the SDK
56
+
57
+ ```typescript
58
+ CoBuy.init({
59
+ merchantKey: "your-unique-merchant-key",
60
+ env: "production", // or "local" for localhost:9000
61
+ debug: false,
62
+ theme: {
63
+ primaryColor: "#4f46e5",
64
+ textColor: "#1f2937",
65
+ },
66
+ });
67
+ ```
68
+
69
+ ### 2. Render the Widget
70
+
71
+ ```typescript
72
+ CoBuy.renderWidget({
73
+ productId: "prod_123",
74
+ container: "#widget-container", // CSS selector or HTMLElement
75
+ onCheckout: (data) => {
76
+ console.log("Checkout initiated:", data);
77
+ },
78
+ onError: (error) => {
79
+ console.error("Widget error:", error);
80
+ },
81
+ onOpen: () => {
82
+ console.log("Widget opened");
83
+ },
84
+ onClose: () => {
85
+ console.log("Widget closed");
86
+ },
87
+ });
88
+ ```
89
+
90
+ ## API Reference
91
+
92
+ ### `CoBuy.init(options: CoBuyInitOptions): void`
93
+
94
+ Initializes the SDK with configuration.
95
+
96
+ **Parameters:**
97
+
98
+ ```typescript
99
+ interface CoBuyInitOptions {
100
+ merchantKey: string; // Required: Your unique merchant key
101
+ env?: "production" | "local"; // Default: "production" (use "local" for localhost:9000)
102
+ theme?: {
103
+ primaryColor?: string; // e.g., "#4f46e5"
104
+ secondaryColor?: string;
105
+ textColor?: string;
106
+ borderRadius?: string;
107
+ fontFamily?: string;
108
+ };
109
+ debug?: boolean; // Default: false
110
+ }
111
+ ```
112
+
113
+ **Example:**
114
+
115
+ ```typescript
116
+ CoBuy.init({
117
+ merchantKey: "pk_live_abc123xyz",
118
+ env: "production",
119
+ debug: false,
120
+ theme: {
121
+ primaryColor: "#4f46e5",
122
+ borderRadius: "8px",
123
+ },
124
+ });
125
+ ```
126
+
127
+ ### `CoBuy.renderWidget(options: RenderWidgetOptions): void`
128
+
129
+ Renders the CoBuy widget into a DOM container.
130
+
131
+ **Parameters:**
132
+
133
+ ```typescript
134
+ interface RenderWidgetOptions {
135
+ productId: string; // Required: The product to display
136
+ container: string | HTMLElement; // CSS selector or element
137
+ onCheckout?: (data: { groupId: string; productId: string }) => void;
138
+ onError?: (error: unknown) => void;
139
+ onOpen?: () => void;
140
+ onClose?: () => void;
141
+ }
142
+ ```
143
+
144
+ **Example:**
145
+
146
+ ```typescript
147
+ CoBuy.renderWidget({
148
+ productId: "prod_456",
149
+ container: "#cobuy-widget",
150
+ onCheckout: (data) => {
151
+ console.log(`Group ${data.groupId} checking out product ${data.productId}`);
152
+ },
153
+ onError: (error) => {
154
+ console.error("Checkout failed:", error);
155
+ },
156
+ });
157
+ ```
158
+
159
+ ### `CoBuy.version: string`
160
+
161
+ Returns the SDK version.
162
+
163
+ ```typescript
164
+ console.log(CoBuy.version); // "1.0.0"
165
+ ```
166
+
167
+ ### `CoBuy.getApiClient(): ApiClient | null`
168
+
169
+ Returns the initialized API client instance for making direct API calls.
170
+
171
+ **Example:**
172
+
173
+ ```typescript
174
+ const apiClient = CoBuy.getApiClient();
175
+ if (apiClient) {
176
+ const rewardResponse = await apiClient.getProductReward("prod_123");
177
+ if (rewardResponse.success) {
178
+ console.log("Reward:", rewardResponse.data.reward);
179
+ }
180
+ }
181
+ ```
182
+
183
+ ### `ApiClient.getProductReward(productId: string): Promise<ApiResponse<ProductRewardData>>`
184
+
185
+ Retrieves reward information for a specific product.
186
+
187
+ **Response Structure:**
188
+
189
+ ```typescript
190
+ interface ProductRewardData {
191
+ productId: string;
192
+ reward: {
193
+ id: string;
194
+ name: string;
195
+ type: "percentage" | "fixed" | "points" | "cashback";
196
+ value: string;
197
+ description: string | null;
198
+ remaining_quantity: number;
199
+ total_quantity: number;
200
+ valid_from: string; // ISO 8601 date
201
+ valid_to: string; // ISO 8601 date
202
+ status: "active" | "inactive" | "expired";
203
+ };
204
+ eligibility: {
205
+ isEligible: boolean;
206
+ reason?: string;
207
+ };
208
+ }
209
+ ```
210
+
211
+ **Example:**
212
+
213
+ ```typescript
214
+ const apiClient = CoBuy.getApiClient();
215
+ const response = await apiClient.getProductReward("prod_123");
216
+
217
+ if (response.success) {
218
+ const { reward, eligibility } = response.data;
219
+ if (eligibility.isEligible) {
220
+ console.log(`${reward.value}% ${reward.name}`);
221
+ console.log(`Valid until: ${reward.valid_to}`);
222
+ }
223
+ } else {
224
+ console.error("Error:", response.error.message);
225
+ }
226
+ ```
227
+
228
+ ## API Base URLs
229
+
230
+ The SDK automatically selects the appropriate API endpoint based on the `env` parameter:
231
+
232
+ | Environment | API URL |
233
+ | ------------ | ------------------------------- |
234
+ | `production` | `https://api.cobuyza.co.za/api` |
235
+ | `local` | `http://localhost:9000/api` |
236
+
237
+ The backend URLs are managed internally by the SDK for security.
238
+
239
+ ## Error Handling
240
+
241
+ The SDK includes custom error classes:
242
+
243
+ ### `CoBuyNotInitializedError`
244
+
245
+ Thrown when attempting to use the SDK before calling `init()`.
246
+
247
+ ```typescript
248
+ try {
249
+ CoBuy.renderWidget({
250
+ /* ... */
251
+ });
252
+ } catch (error) {
253
+ if (error instanceof CoBuyNotInitializedError) {
254
+ console.error("SDK not initialized");
255
+ }
256
+ }
257
+ ```
258
+
259
+ ### `CoBuyInvalidConfigError`
260
+
261
+ Thrown when invalid configuration is provided to `init()`.
262
+
263
+ ```typescript
264
+ try {
265
+ CoBuy.init({ merchantKey: "" }); // Invalid
266
+ } catch (error) {
267
+ if (error instanceof CoBuyInvalidConfigError) {
268
+ console.error("Invalid configuration:", error.message);
269
+ }
270
+ }
271
+ ```
272
+
273
+ ## Debugging
274
+
275
+ Enable debug logging to monitor SDK operations:
276
+
277
+ ```typescript
278
+ CoBuy.init({
279
+ merchantKey: "your-key",
280
+ debug: true, // Enables console logging
281
+ });
282
+ ```
283
+
284
+ When debug mode is enabled, the SDK logs:
285
+
286
+ - SDK initialization details
287
+ - Environment and API base URL
288
+ - Widget rendering operations
289
+
290
+ ## Project Structure
291
+
292
+ ```
293
+ cobuy-sdk/
294
+ ├── src/
295
+ │ ├── index.ts # Entry point, window.CoBuy export
296
+ │ ├── core/
297
+ │ │ ├── cobuy.ts # Main SDK implementation
298
+ │ │ ├── config.ts # Configuration manager
299
+ │ │ ├── logger.ts # Logging utility
300
+ │ │ ├── types.ts # TypeScript type definitions
301
+ │ │ └── errors.ts # Custom error classes
302
+ │ └── ui/
303
+ │ └── widget/
304
+ │ └── widget-root.ts # Widget rendering logic
305
+ ├── dist/ # Compiled output
306
+ │ ├── cobuy-sdk.esm.js # ES Module format
307
+ │ ├── cobuy-sdk.esm.js.map # Source map
308
+ │ ├── cobuy-sdk.umd.js # UMD format (browser globals)
309
+ │ └── cobuy-sdk.umd.js.map # Source map
310
+ ├── package.json
311
+ ├── tsconfig.json
312
+ ├── rollup.config.mjs
313
+ └── eslint.config.js
314
+ ```
315
+
316
+ ## Development
317
+
318
+ ### Prerequisites
319
+
320
+ - Node.js 16+
321
+ - npm or yarn
322
+
323
+ ### Setup
324
+
325
+ ```bash
326
+ npm install
327
+ ```
328
+
329
+ ### Scripts
330
+
331
+ ```bash
332
+ # Build the SDK
333
+ npm run build
334
+
335
+ # Watch mode (rebuilds on file changes)
336
+ npm run build:watch
337
+
338
+ # Run ESLint
339
+ npm run lint
340
+
341
+ # Fix ESLint issues
342
+ npm run lint:fix
343
+
344
+ # Type check + lint
345
+ npm run check
346
+ ```
347
+
348
+ ### Code Quality
349
+
350
+ This project uses:
351
+
352
+ - **TypeScript**: Strict mode enabled for type safety
353
+ - **ESLint**: Enforces code standards
354
+ - **Prettier**: Automatic code formatting
355
+ - **Rollup**: Module bundler for optimized output
356
+
357
+ ### Building
358
+
359
+ The SDK is built with Rollup and produces:
360
+
361
+ 1. **ESM Bundle** (`cobuy-sdk.esm.js`): For use with modern module bundlers
362
+ 2. **UMD Bundle** (`cobuy-sdk.umd.js`): For direct browser inclusion via `<script>` tag
363
+
364
+ Type definitions are generated automatically and included in the `dist/types/` directory.
365
+
366
+ ## Browser Support
367
+
368
+ - Modern browsers with ES2017+ support
369
+ - Chrome 51+
370
+ - Firefox 54+
371
+ - Safari 10+
372
+ - Edge 15+
373
+
374
+ ## TypeScript Support
375
+
376
+ The SDK includes full TypeScript definitions. When using with TypeScript:
377
+
378
+ ```typescript
379
+ import CoBuy from "@cobuy/sdk";
380
+ import type { CoBuySDK, CoBuyInitOptions, RenderWidgetOptions } from "@cobuy/sdk";
381
+
382
+ // All types are available for import
383
+ const options: CoBuyInitOptions = {
384
+ merchantKey: "key",
385
+ env: "production",
386
+ };
387
+
388
+ CoBuy.init(options);
389
+ ```
390
+
391
+ ## Configuration Examples
392
+
393
+ ### Minimal Configuration
394
+
395
+ ```typescript
396
+ CoBuy.init({
397
+ merchantKey: "pk_live_123abc",
398
+ });
399
+ ```
400
+
401
+ ### Full Configuration
402
+
403
+ ```typescript
404
+ CoBuy.init({
405
+ merchantKey: "pk_live_123abc",
406
+ env: "production",
407
+ theme: {
408
+ primaryColor: "#4f46e5",
409
+ secondaryColor: "#e5e7eb",
410
+ textColor: "#1f2937",
411
+ borderRadius: "8px",
412
+ fontFamily: "'Inter', sans-serif",
413
+ },
414
+ debug: true,
415
+ });
416
+ ```
417
+
418
+ ### With Event Handlers
419
+
420
+ ```typescript
421
+ CoBuy.renderWidget({
422
+ productId: "prod_789",
423
+ container: "#my-widget",
424
+ onOpen: () => {
425
+ // Track analytics
426
+ analytics.track("cobuy_widget_opened");
427
+ },
428
+ onCheckout: (data) => {
429
+ // Send to your backend
430
+ api.post("/order/initiate", data);
431
+ },
432
+ onError: (error) => {
433
+ // Handle errors gracefully
434
+ showErrorNotification(error.message);
435
+ },
436
+ onClose: () => {
437
+ // Cleanup
438
+ console.log("Widget closed");
439
+ },
440
+ });
441
+ ```
442
+
443
+ ## License
444
+
445
+ MIT
446
+
447
+ ## Support
448
+
449
+ For issues, feature requests, or questions, please contact support@cobuy.app or create an issue in the repository.
450
+
451
+ ---
452
+
453
+ **Version**: 1.0.0
454
+ **Last Updated**: December 2025