@scalemule/sdk 0.0.22 → 0.0.24

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.mjs CHANGED
@@ -3710,6 +3710,44 @@ var SocialService = class extends ServiceModule {
3710
3710
  }
3711
3711
  };
3712
3712
 
3713
+ // src/services/referrals.ts
3714
+ var ReferralsService = class extends ServiceModule {
3715
+ constructor() {
3716
+ super(...arguments);
3717
+ this.basePath = "/v1/referrals";
3718
+ }
3719
+ /**
3720
+ * Get current user's referral code, share link, campaign, and stats.
3721
+ * Requires member auth.
3722
+ */
3723
+ async getMyReferral(options) {
3724
+ return this._get("/me", options);
3725
+ }
3726
+ /**
3727
+ * Generate a tracked share link. The `channel` param records where
3728
+ * the share was initiated (e.g., 'whatsapp', 'email', 'copy').
3729
+ * Requires member auth.
3730
+ */
3731
+ async createShareLink(channel, options) {
3732
+ return this.post("/links", channel ? { channel } : void 0, options);
3733
+ }
3734
+ /**
3735
+ * Get referral analytics for the current user over the last N days.
3736
+ * Requires member auth.
3737
+ */
3738
+ async getMyAnalytics(days, options) {
3739
+ const query = days ? `?days=${days}` : "";
3740
+ return this._get(`/me/analytics${query}`, options);
3741
+ }
3742
+ /**
3743
+ * Resolve a referral code to its campaign info.
3744
+ * Public endpoint — no member auth required, only API key.
3745
+ */
3746
+ async resolveCode(code, options) {
3747
+ return this._get(`/public?rc=${encodeURIComponent(code)}`, options);
3748
+ }
3749
+ };
3750
+
3713
3751
  // src/services/billing.ts
3714
3752
  var BillingService = class extends ServiceModule {
3715
3753
  constructor() {
@@ -4094,17 +4132,68 @@ var CommunicationService = class extends ServiceModule {
4094
4132
  return this.post(`/sms/templates/${template}/send`, data, options);
4095
4133
  }
4096
4134
  // --------------------------------------------------------------------------
4097
- // Push Notifications
4135
+ // Push Notifications — Send
4098
4136
  // --------------------------------------------------------------------------
4099
4137
  async sendPush(data, options) {
4100
4138
  return this.post("/push/send", data, options);
4101
4139
  }
4140
+ // --------------------------------------------------------------------------
4141
+ // Push Notifications — Token Management
4142
+ // --------------------------------------------------------------------------
4102
4143
  async registerPushToken(data, options) {
4103
4144
  return this.post("/push/register", data, options);
4104
4145
  }
4146
+ /** @deprecated Use unregisterPushTokenById() for web push tokens */
4105
4147
  async unregisterPushToken(token, options) {
4106
4148
  return this.del(`/push/tokens/${token}`, options);
4107
4149
  }
4150
+ async unregisterPushTokenById(id, options) {
4151
+ const result = await this.del(`/push/tokens/by-id/${id}`, options);
4152
+ if (result.data && typeof result.data === "object" && !("id" in result.data)) {
4153
+ return { data: void 0, error: null };
4154
+ }
4155
+ return result;
4156
+ }
4157
+ async associatePushTokenUserById(id, options) {
4158
+ return this.put(`/push/tokens/by-id/${id}/user`, {}, options);
4159
+ }
4160
+ async disassociatePushTokenUser(id, options) {
4161
+ const result = await this.del(`/push/tokens/by-id/${id}/user`, options);
4162
+ if (result.data && typeof result.data === "object" && !("id" in result.data)) {
4163
+ return { data: void 0, error: null };
4164
+ }
4165
+ return result;
4166
+ }
4167
+ // --------------------------------------------------------------------------
4168
+ // Push Notifications — Settings
4169
+ // --------------------------------------------------------------------------
4170
+ async getMyPushSettings(options) {
4171
+ return this._get("/push/settings/me", options);
4172
+ }
4173
+ // --------------------------------------------------------------------------
4174
+ // Push Notifications — Topics & Subscriptions
4175
+ // --------------------------------------------------------------------------
4176
+ async listTopics(options) {
4177
+ return this._get("/push/topics", options);
4178
+ }
4179
+ async subscribeTopic(topicId, data, options) {
4180
+ return this.post(`/push/topics/${topicId}/subscribe`, data || {}, options);
4181
+ }
4182
+ async unsubscribeTopic(topicId, options) {
4183
+ return this.del(`/push/topics/${topicId}/subscribe`, options);
4184
+ }
4185
+ async listSubscriptions(options) {
4186
+ return this._get("/push/subscriptions", options);
4187
+ }
4188
+ // --------------------------------------------------------------------------
4189
+ // Push Notifications — Preferences
4190
+ // --------------------------------------------------------------------------
4191
+ async getPushPreferences(options) {
4192
+ return this._get("/push/preferences", options);
4193
+ }
4194
+ async updatePushPreferences(data, options) {
4195
+ return this.put("/push/preferences", data, options);
4196
+ }
4108
4197
  // --------------------------------------------------------------------------
4109
4198
  // Message Status
4110
4199
  // --------------------------------------------------------------------------
@@ -4124,6 +4213,258 @@ var CommunicationService = class extends ServiceModule {
4124
4213
  }
4125
4214
  };
4126
4215
 
4216
+ // src/web-push.ts
4217
+ var STORAGE_KEY = "scalemule_push_state";
4218
+ var WebPushManager = class {
4219
+ constructor(options) {
4220
+ this.state = null;
4221
+ this.registration = null;
4222
+ if (typeof window === "undefined") {
4223
+ throw new Error("WebPushManager can only be used in a browser environment");
4224
+ }
4225
+ this.fetcher = options.fetcher;
4226
+ this.swUrl = options.serviceWorkerUrl || "/sw.js";
4227
+ try {
4228
+ const stored = localStorage.getItem(STORAGE_KEY);
4229
+ if (stored) {
4230
+ this.state = JSON.parse(stored);
4231
+ }
4232
+ } catch {
4233
+ }
4234
+ }
4235
+ /** Whether the browser supports Web Push */
4236
+ isSupported() {
4237
+ return typeof window !== "undefined" && "serviceWorker" in navigator && "PushManager" in window && "Notification" in window;
4238
+ }
4239
+ /** Current notification permission state */
4240
+ getPermissionState() {
4241
+ if (!this.isSupported()) return "unsupported";
4242
+ return Notification.permission;
4243
+ }
4244
+ /** Request notification permission from the user */
4245
+ async requestPermission() {
4246
+ if (!this.isSupported()) return "denied";
4247
+ return Notification.requestPermission();
4248
+ }
4249
+ /**
4250
+ * Full subscribe flow:
4251
+ * 1. Check browser support
4252
+ * 2. Request notification permission
4253
+ * 3. Register service worker
4254
+ * 4. Fetch VAPID public key from backend
4255
+ * 5. PushManager.subscribe() with VAPID key
4256
+ * 6. Register token with backend
4257
+ *
4258
+ * @param deviceId Optional device identifier for anonymous users.
4259
+ * If not provided, generates a random UUID stored in localStorage.
4260
+ */
4261
+ async subscribe(deviceId) {
4262
+ if (!this.isSupported()) return null;
4263
+ const permission = await this.requestPermission();
4264
+ if (permission !== "granted") return null;
4265
+ this.registration = await navigator.serviceWorker.register(this.swUrl);
4266
+ await navigator.serviceWorker.ready;
4267
+ const settings = await this.fetcher.getSettings();
4268
+ if (!settings.webpush_enabled || !settings.vapid_public_key) {
4269
+ throw new Error("Web Push is not enabled for this application");
4270
+ }
4271
+ const applicationServerKey = urlBase64ToUint8Array(settings.vapid_public_key);
4272
+ const pushSubscription = await this.registration.pushManager.subscribe({
4273
+ userVisibleOnly: true,
4274
+ applicationServerKey: applicationServerKey.buffer
4275
+ });
4276
+ const endpoint = pushSubscription.endpoint;
4277
+ const p256dh = arrayBufferToBase64url(pushSubscription.getKey("p256dh"));
4278
+ const auth = arrayBufferToBase64url(pushSubscription.getKey("auth"));
4279
+ const subscription = {
4280
+ endpoint,
4281
+ keys: { p256dh, auth }
4282
+ };
4283
+ const resolvedDeviceId = deviceId || this.state?.deviceId || generateDeviceId();
4284
+ const result = await this.fetcher.registerToken({
4285
+ token: endpoint,
4286
+ platform: "web",
4287
+ device_id: resolvedDeviceId,
4288
+ subscription
4289
+ });
4290
+ this.state = {
4291
+ endpoint,
4292
+ tokenId: result.id,
4293
+ deviceId: resolvedDeviceId
4294
+ };
4295
+ this.persistState();
4296
+ return { tokenId: result.id, endpoint };
4297
+ }
4298
+ /** Unsubscribe from browser push and deregister token */
4299
+ async unsubscribe() {
4300
+ const sub = await this.getSubscription();
4301
+ if (sub) {
4302
+ await sub.unsubscribe();
4303
+ }
4304
+ if (this.state?.tokenId) {
4305
+ try {
4306
+ await this.fetcher.unregisterToken(this.state.tokenId);
4307
+ } catch {
4308
+ }
4309
+ }
4310
+ this.state = null;
4311
+ this.clearState();
4312
+ }
4313
+ /** Link push token to the currently authenticated user (call after login) */
4314
+ async associateUser() {
4315
+ if (!this.state?.tokenId) return;
4316
+ await this.fetcher.associateUser(this.state.tokenId);
4317
+ }
4318
+ /** Clear user association from push token (call before logout) */
4319
+ async disassociateUser() {
4320
+ if (!this.state?.tokenId) return;
4321
+ await this.fetcher.disassociateUser(this.state.tokenId);
4322
+ }
4323
+ /** Check if currently subscribed to push notifications */
4324
+ async isSubscribed() {
4325
+ if (!this.isSupported()) return false;
4326
+ const sub = await this.getSubscription();
4327
+ return sub !== null && this.state !== null;
4328
+ }
4329
+ /** Get the active PushSubscription from the service worker */
4330
+ async getSubscription() {
4331
+ if (!this.isSupported()) return null;
4332
+ try {
4333
+ const reg = await navigator.serviceWorker.getRegistration(this.swUrl);
4334
+ if (!reg) return null;
4335
+ return reg.pushManager.getSubscription();
4336
+ } catch {
4337
+ return null;
4338
+ }
4339
+ }
4340
+ /** Get the stored token ID (for external use) */
4341
+ getTokenId() {
4342
+ return this.state?.tokenId || null;
4343
+ }
4344
+ persistState() {
4345
+ if (this.state) {
4346
+ try {
4347
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(this.state));
4348
+ } catch {
4349
+ }
4350
+ }
4351
+ }
4352
+ clearState() {
4353
+ try {
4354
+ localStorage.removeItem(STORAGE_KEY);
4355
+ } catch {
4356
+ }
4357
+ }
4358
+ };
4359
+ function urlBase64ToUint8Array(base64String) {
4360
+ const padding = "=".repeat((4 - base64String.length % 4) % 4);
4361
+ const base64 = (base64String + padding).replace(/-/g, "+").replace(/_/g, "/");
4362
+ const rawData = atob(base64);
4363
+ const outputArray = new Uint8Array(rawData.length);
4364
+ for (let i = 0; i < rawData.length; ++i) {
4365
+ outputArray[i] = rawData.charCodeAt(i);
4366
+ }
4367
+ return outputArray;
4368
+ }
4369
+ function arrayBufferToBase64url(buffer) {
4370
+ const bytes = new Uint8Array(buffer);
4371
+ const binary = Array.from(bytes, (b) => String.fromCharCode(b)).join("");
4372
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
4373
+ }
4374
+ function generateDeviceId() {
4375
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
4376
+ return crypto.randomUUID();
4377
+ }
4378
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
4379
+ const r = Math.random() * 16 | 0;
4380
+ const v = c === "x" ? r : r & 3 | 8;
4381
+ return v.toString(16);
4382
+ });
4383
+ }
4384
+
4385
+ // src/web-push-sw.ts
4386
+ var WEB_PUSH_SERVICE_WORKER = `
4387
+ // ScaleMule Push Notification Service Worker
4388
+
4389
+ self.addEventListener('push', function(event) {
4390
+ if (!event.data) return;
4391
+
4392
+ var data;
4393
+ try {
4394
+ data = event.data.json();
4395
+ } catch (e) {
4396
+ data = { title: 'New Notification', body: event.data.text() };
4397
+ }
4398
+
4399
+ var title = data.title || 'Notification';
4400
+ var options = {
4401
+ body: data.body || '',
4402
+ icon: data.icon || undefined,
4403
+ image: data.image || undefined,
4404
+ badge: data.badge || undefined,
4405
+ data: data.data || data,
4406
+ tag: data.tag || undefined,
4407
+ actions: data.actions || undefined,
4408
+ requireInteraction: data.requireInteraction || false,
4409
+ };
4410
+
4411
+ // Show the notification
4412
+ event.waitUntil(
4413
+ self.registration.showNotification(title, options)
4414
+ .then(function() {
4415
+ // Post message to all client pages for foreground handling
4416
+ return self.clients.matchAll({ type: 'window', includeUncontrolled: true });
4417
+ })
4418
+ .then(function(clients) {
4419
+ clients.forEach(function(client) {
4420
+ client.postMessage({
4421
+ type: 'push-received',
4422
+ payload: data,
4423
+ });
4424
+ });
4425
+ })
4426
+ );
4427
+ });
4428
+
4429
+ self.addEventListener('notificationclick', function(event) {
4430
+ event.notification.close();
4431
+
4432
+ var url = '/';
4433
+ if (event.notification.data && event.notification.data.url) {
4434
+ url = event.notification.data.url;
4435
+ }
4436
+
4437
+ // Handle action button clicks
4438
+ if (event.action && event.notification.data && event.notification.data.actions) {
4439
+ var action = event.notification.data.actions.find(function(a) {
4440
+ return a.action === event.action;
4441
+ });
4442
+ if (action && action.url) {
4443
+ url = action.url;
4444
+ }
4445
+ }
4446
+
4447
+ event.waitUntil(
4448
+ self.clients.matchAll({ type: 'window', includeUncontrolled: true })
4449
+ .then(function(clientList) {
4450
+ // Try to focus an existing window
4451
+ for (var i = 0; i < clientList.length; i++) {
4452
+ var client = clientList[i];
4453
+ if (client.url.indexOf(self.registration.scope) !== -1 && 'focus' in client) {
4454
+ client.focus();
4455
+ client.navigate(url);
4456
+ return;
4457
+ }
4458
+ }
4459
+ // Open a new window if none exists
4460
+ if (self.clients.openWindow) {
4461
+ return self.clients.openWindow(url);
4462
+ }
4463
+ })
4464
+ );
4465
+ });
4466
+ `;
4467
+
4127
4468
  // src/services/scheduler.ts
4128
4469
  var SchedulerService = class extends ServiceModule {
4129
4470
  constructor() {
@@ -5559,6 +5900,7 @@ var ScaleMule = class {
5559
5900
  this.data = new DataService(this._client);
5560
5901
  this.chat = new ChatService(this._client);
5561
5902
  this.social = new SocialService(this._client);
5903
+ this.referrals = new ReferralsService(this._client);
5562
5904
  this.billing = new BillingService(this._client);
5563
5905
  this.analytics = new AnalyticsService(this._client);
5564
5906
  this.flags = new FlagsService(this._client);
@@ -5712,6 +6054,7 @@ export {
5712
6054
  PhotoService,
5713
6055
  QueueService,
5714
6056
  RealtimeService,
6057
+ ReferralsService,
5715
6058
  ScaleMule,
5716
6059
  ScaleMuleClient,
5717
6060
  SchedulerService,
@@ -5723,6 +6066,8 @@ export {
5723
6066
  UploadResumeStore,
5724
6067
  UploadTelemetry,
5725
6068
  VideoService,
6069
+ WEB_PUSH_SERVICE_WORKER,
6070
+ WebPushManager,
5726
6071
  WebhooksService,
5727
6072
  WorkspacesService,
5728
6073
  buildClientContextHeaders,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scalemule/sdk",
3
- "version": "0.0.22",
3
+ "version": "0.0.24",
4
4
  "description": "Official TypeScript/JavaScript SDK for ScaleMule Backend-as-a-Service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
@@ -65,7 +65,7 @@
65
65
  "semver": "^7.7.4"
66
66
  },
67
67
  "peerDependencies": {
68
- "@scalemule/ui": "^0.0.1",
68
+ "@scalemule/ui": ">=0.0.1",
69
69
  "browser-image-compression": ">=2.0.0"
70
70
  },
71
71
  "peerDependenciesMeta": {
@@ -77,7 +77,7 @@
77
77
  }
78
78
  },
79
79
  "devDependencies": {
80
- "@scalemule/ui": "^0.0.1",
80
+ "@scalemule/ui": ">=0.0.1",
81
81
  "@types/node": "^20.10.0",
82
82
  "@typescript-eslint/eslint-plugin": "^6.13.0",
83
83
  "@typescript-eslint/parser": "^6.13.0",