@spacelr/sdk 0.18.3 → 0.19.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 CHANGED
@@ -440,6 +440,9 @@ var HttpClient = class {
440
440
  };
441
441
 
442
442
  // libs/sdk/src/core/token-storage.ts
443
+ function isStoredTokens(value) {
444
+ return typeof value === "object" && value !== null && "accessToken" in value && typeof value.accessToken === "string";
445
+ }
443
446
  var MemoryTokenStorage = class {
444
447
  constructor() {
445
448
  this.tokens = null;
@@ -462,7 +465,8 @@ var BrowserTokenStorage = class {
462
465
  try {
463
466
  const raw = localStorage.getItem(this.storageKey);
464
467
  if (!raw) return null;
465
- return JSON.parse(raw);
468
+ const parsed = JSON.parse(raw);
469
+ return isStoredTokens(parsed) ? parsed : null;
466
470
  } catch {
467
471
  return null;
468
472
  }
@@ -1348,7 +1352,11 @@ var RealtimeClient = class {
1348
1352
  // rejects on connect_error and they decide whether to retry. Once the
1349
1353
  // first authentication succeeds we re-enable it via the Manager's
1350
1354
  // setters (see authenticated handler).
1351
- reconnection: false
1355
+ reconnection: false,
1356
+ // #1000 — socket.io's 20 s default left a connect that hangs without
1357
+ // a close (browser offline mid-handshake) pending for 20 s before the
1358
+ // retry could start. Also applies to the later auto-reconnects.
1359
+ timeout: 5e3
1352
1360
  });
1353
1361
  this.socket = socket;
1354
1362
  const failInitialConnect = (message) => {
@@ -1959,12 +1967,14 @@ function mapProfile(u) {
1959
1967
  };
1960
1968
  }
1961
1969
  var AuthModule = class _AuthModule {
1962
- constructor(http, tokenManager, config) {
1970
+ constructor(http, tokenManager, config, hooks = {}) {
1963
1971
  this.stateListeners = /* @__PURE__ */ new Set();
1964
1972
  this.lastEmittedState = null;
1965
1973
  this.http = http;
1966
1974
  this.tokenManager = tokenManager;
1967
1975
  this.config = config;
1976
+ this.beforeLogout = hooks.beforeLogout;
1977
+ this.afterSignIn = hooks.afterSignIn;
1968
1978
  this.tokenManager.setRefreshCallback(async (refreshToken) => {
1969
1979
  const result = await this.refresh(refreshToken);
1970
1980
  const expiresAt = result.expires_in ? Math.floor(Date.now() / 1e3) + result.expires_in : void 0;
@@ -2038,8 +2048,26 @@ var AuthModule = class _AuthModule {
2038
2048
  };
2039
2049
  this.stateListeners.clear();
2040
2050
  this.lastEmittedState = null;
2051
+ this.beforeLogout = void 0;
2052
+ this.afterSignIn = void 0;
2053
+ }
2054
+ /**
2055
+ * Install the tokens of a completed sign-in. Signing in over a live session
2056
+ * (e.g. user B over user A without a logout) first runs `beforeLogout` with
2057
+ * the outgoing session's still-valid token, so this device's push leaves
2058
+ * the previous user before it is re-registered for the new one.
2059
+ */
2060
+ async installSession(tokens) {
2061
+ if (this.beforeLogout && await this.tokenManager.getStoredTokens()) {
2062
+ await this.beforeLogout().catch(() => void 0);
2063
+ }
2064
+ await this.tokenManager.setTokens(tokens);
2065
+ this.emitState("authenticated");
2041
2066
  }
2042
2067
  emitState(state) {
2068
+ if (state === "authenticated") {
2069
+ this.afterSignIn?.().catch(() => void 0);
2070
+ }
2043
2071
  if (state === this.lastEmittedState) return;
2044
2072
  this.lastEmittedState = state;
2045
2073
  for (const listener of this.stateListeners) {
@@ -2089,6 +2117,7 @@ var AuthModule = class _AuthModule {
2089
2117
  return mapProfile(data.user ?? data);
2090
2118
  }
2091
2119
  async logout() {
2120
+ await this.beforeLogout?.().catch(() => void 0);
2092
2121
  try {
2093
2122
  await this.http.request({
2094
2123
  method: "POST",
@@ -2176,12 +2205,11 @@ var AuthModule = class _AuthModule {
2176
2205
  body
2177
2206
  });
2178
2207
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2179
- await this.tokenManager.setTokens({
2208
+ await this.installSession({
2180
2209
  accessToken: response.access_token,
2181
2210
  refreshToken: response.refresh_token,
2182
2211
  expiresAt
2183
2212
  });
2184
- this.emitState("authenticated");
2185
2213
  return response;
2186
2214
  }
2187
2215
  async generatePKCE() {
@@ -2427,12 +2455,11 @@ var AuthModule = class _AuthModule {
2427
2455
  }
2428
2456
  async storeTokensFromLogin(response) {
2429
2457
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2430
- await this.tokenManager.setTokens({
2458
+ await this.installSession({
2431
2459
  accessToken: response.access_token,
2432
2460
  refreshToken: response.refresh_token,
2433
2461
  expiresAt
2434
2462
  });
2435
- this.emitState("authenticated");
2436
2463
  }
2437
2464
  // ─── Recover-with-phrase (#784) ───
2438
2465
  // For an email-less passkey account (#780) that has lost every passkey. The
@@ -2663,12 +2690,11 @@ var AuthModule = class _AuthModule {
2663
2690
  async storeTokensFromRegister(response) {
2664
2691
  if (!response.access_token) return;
2665
2692
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2666
- await this.tokenManager.setTokens({
2693
+ await this.installSession({
2667
2694
  accessToken: response.access_token,
2668
2695
  refreshToken: response.refresh_token,
2669
2696
  expiresAt
2670
2697
  });
2671
- this.emitState("authenticated");
2672
2698
  }
2673
2699
  };
2674
2700
 
@@ -4156,11 +4182,20 @@ var DatabaseModule = class {
4156
4182
 
4157
4183
  // libs/sdk/src/modules/notifications.module.ts
4158
4184
  var DEVICE_ID_KEY = "spacelr_device_id";
4159
- var NotificationsModule = class {
4160
- constructor(http) {
4185
+ var REGISTRATION_KEY_PREFIX = "spacelr_push_registration:";
4186
+ var PUSH_LOGOUT_TIMEOUT_MS = 3e3;
4187
+ var NotificationsModule = class _NotificationsModule {
4188
+ constructor(http, options = {}) {
4161
4189
  this.http = http;
4162
4190
  this.customDeviceId = null;
4163
4191
  this.customDeviceName = null;
4192
+ // Fallback when localStorage is unavailable or refuses writes.
4193
+ this.memoryRegistration = null;
4194
+ // Push register/unregister calls run strictly in call order, so a late
4195
+ // re-register can never land after the logout's unregister (or overwrite a
4196
+ // newer registration the app just made).
4197
+ this.pushQueue = Promise.resolve();
4198
+ this.registrationKey = `${REGISTRATION_KEY_PREFIX}${options.projectId ?? "default"}`;
4164
4199
  }
4165
4200
  /** Set a custom device ID (e.g. from Capacitor Preferences for persistence beyond localStorage) */
4166
4201
  setDeviceId(id) {
@@ -4174,12 +4209,16 @@ var NotificationsModule = class {
4174
4209
  getDeviceId() {
4175
4210
  if (this.customDeviceId) return this.customDeviceId;
4176
4211
  if (typeof localStorage === "undefined") return void 0;
4177
- let id = localStorage.getItem(DEVICE_ID_KEY);
4178
- if (!id) {
4179
- id = crypto.randomUUID();
4180
- localStorage.setItem(DEVICE_ID_KEY, id);
4212
+ try {
4213
+ let id = localStorage.getItem(DEVICE_ID_KEY);
4214
+ if (!id) {
4215
+ id = crypto.randomUUID();
4216
+ localStorage.setItem(DEVICE_ID_KEY, id);
4217
+ }
4218
+ return id;
4219
+ } catch {
4220
+ return void 0;
4181
4221
  }
4182
- return id;
4183
4222
  }
4184
4223
  /** Get device name: custom name > auto-detected from user agent > undefined */
4185
4224
  getDeviceName() {
@@ -4212,9 +4251,19 @@ var NotificationsModule = class {
4212
4251
  authenticated: true
4213
4252
  });
4214
4253
  }
4215
- /** Register a push subscription (web, android, ios, or web-fcm) */
4254
+ /**
4255
+ * Register a push subscription (web, android, ios, or web-fcm).
4256
+ *
4257
+ * The SDK remembers this device's registration. Unless the client was
4258
+ * created with `autoManagePush: false`, it re-registers it after every
4259
+ * login and unregisters it on `auth.logout()`, so the subscription always
4260
+ * belongs to the signed-in user's current session.
4261
+ */
4216
4262
  async subscribe(subscription, deviceName) {
4217
- return this.http.request({
4263
+ return this.enqueue(() => this.register(subscription, deviceName));
4264
+ }
4265
+ async register(subscription, deviceName) {
4266
+ const info = await this.http.request({
4218
4267
  method: "POST",
4219
4268
  path: "/notifications/subscribe",
4220
4269
  body: {
@@ -4224,20 +4273,23 @@ var NotificationsModule = class {
4224
4273
  },
4225
4274
  authenticated: true
4226
4275
  });
4276
+ this.saveRegistration({ id: info?.id, subscription, deviceName });
4277
+ return info;
4227
4278
  }
4228
- /** Unregister a push subscription */
4279
+ /**
4280
+ * Unregister a push subscription. Unregistering this device's own
4281
+ * subscription also stops the SDK from re-registering it after a login.
4282
+ */
4229
4283
  async unsubscribe(platform, identifier) {
4230
- const body = { platform };
4231
- if (platform === "web") {
4232
- body["endpoint"] = identifier;
4233
- } else {
4234
- body["deviceToken"] = identifier;
4235
- }
4236
- return this.http.request({
4237
- method: "DELETE",
4238
- path: "/notifications/subscribe",
4239
- body,
4240
- authenticated: true
4284
+ return this.enqueue(async () => {
4285
+ try {
4286
+ return await this.deleteSubscription(platform, identifier);
4287
+ } finally {
4288
+ const stored = this.loadRegistration();
4289
+ if (stored?.subscription.platform === platform && _NotificationsModule.identifierOf(stored.subscription) === identifier) {
4290
+ this.saveRegistration(null);
4291
+ }
4292
+ }
4241
4293
  });
4242
4294
  }
4243
4295
  /**
@@ -4247,12 +4299,114 @@ var NotificationsModule = class {
4247
4299
  * by the listing and so cannot be passed to {@link unsubscribe}).
4248
4300
  */
4249
4301
  async unsubscribeById(subscriptionId) {
4302
+ return this.enqueue(async () => {
4303
+ try {
4304
+ return await this.http.request({
4305
+ method: "DELETE",
4306
+ path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4307
+ authenticated: true
4308
+ });
4309
+ } finally {
4310
+ if (this.loadRegistration()?.id === subscriptionId) {
4311
+ this.saveRegistration(null);
4312
+ }
4313
+ }
4314
+ });
4315
+ }
4316
+ /**
4317
+ * Re-register this device's remembered subscription for the user who just
4318
+ * signed in, binding it to their new session (#1003). The client calls this
4319
+ * after every sign-in unless `autoManagePush` is false; call it yourself
4320
+ * after signing in via `setTokens()`. No-op when this device never
4321
+ * subscribed. Best-effort: a failure leaves the device without push until
4322
+ * the app subscribes again.
4323
+ */
4324
+ async resubscribeAfterLogin() {
4325
+ await this.enqueue(async () => {
4326
+ const stored = this.loadRegistration();
4327
+ if (!stored) return;
4328
+ try {
4329
+ await this.register(stored.subscription, stored.deviceName);
4330
+ } catch (error) {
4331
+ console.warn("[spacelr] Could not re-register push after login:", error);
4332
+ }
4333
+ });
4334
+ }
4335
+ /**
4336
+ * Unregister this device's subscription while the session is still valid,
4337
+ * so a signed-out device stops receiving the user's pushes. The remembered
4338
+ * registration is kept, so the next sign-in re-registers it. `auth.logout()`
4339
+ * calls this first unless `autoManagePush` is false; call it yourself before
4340
+ * clearing tokens via `clearTokens()`. Best-effort.
4341
+ */
4342
+ async unsubscribeBeforeLogout() {
4343
+ const unregistered = this.enqueue(async () => {
4344
+ const stored = this.loadRegistration();
4345
+ if (!stored) return;
4346
+ await this.deleteSubscription(
4347
+ stored.subscription.platform,
4348
+ _NotificationsModule.identifierOf(stored.subscription)
4349
+ ).catch(() => void 0);
4350
+ });
4351
+ let timer;
4352
+ await Promise.race([
4353
+ unregistered,
4354
+ new Promise((resolve) => {
4355
+ timer = setTimeout(resolve, PUSH_LOGOUT_TIMEOUT_MS);
4356
+ })
4357
+ ]);
4358
+ clearTimeout(timer);
4359
+ }
4360
+ enqueue(op) {
4361
+ const run = this.pushQueue.then(op, op);
4362
+ this.pushQueue = run.catch(() => void 0);
4363
+ return run;
4364
+ }
4365
+ deleteSubscription(platform, identifier) {
4366
+ const body = { platform };
4367
+ if (platform === "web") {
4368
+ body["endpoint"] = identifier;
4369
+ } else {
4370
+ body["deviceToken"] = identifier;
4371
+ }
4250
4372
  return this.http.request({
4251
4373
  method: "DELETE",
4252
- path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4374
+ path: "/notifications/subscribe",
4375
+ body,
4253
4376
  authenticated: true
4254
4377
  });
4255
4378
  }
4379
+ /** The value `unsubscribe()` identifies a subscription by: endpoint for web, token otherwise. */
4380
+ static identifierOf(subscription) {
4381
+ return (subscription.platform === "web" ? subscription.endpoint : subscription.deviceToken) ?? "";
4382
+ }
4383
+ static isStoredRegistration(value) {
4384
+ if (typeof value !== "object" || value === null) return false;
4385
+ const subscription = value.subscription;
4386
+ return typeof subscription === "object" && subscription !== null && typeof subscription.platform === "string";
4387
+ }
4388
+ loadRegistration() {
4389
+ if (typeof localStorage === "undefined") return this.memoryRegistration;
4390
+ try {
4391
+ const raw = localStorage.getItem(this.registrationKey);
4392
+ const parsed = raw ? JSON.parse(raw) : null;
4393
+ return _NotificationsModule.isStoredRegistration(parsed) ? parsed : this.memoryRegistration;
4394
+ } catch {
4395
+ return this.memoryRegistration;
4396
+ }
4397
+ }
4398
+ saveRegistration(registration) {
4399
+ this.memoryRegistration = registration;
4400
+ if (typeof localStorage === "undefined") return;
4401
+ try {
4402
+ if (registration) {
4403
+ localStorage.setItem(this.registrationKey, JSON.stringify(registration));
4404
+ } else {
4405
+ localStorage.removeItem(this.registrationKey);
4406
+ }
4407
+ } catch {
4408
+ }
4409
+ }
4256
4410
  /** Get all subscriptions for the current user */
4257
4411
  async getSubscriptions() {
4258
4412
  return this.http.request({
@@ -4455,10 +4609,21 @@ function createClient(config) {
4455
4609
  getToken: () => tokenManager.getAccessToken(),
4456
4610
  onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
4457
4611
  });
4458
- const auth = new AuthModule(httpClient, tokenManager, config);
4612
+ const notifications = new NotificationsModule(httpClient, {
4613
+ projectId: config.projectId
4614
+ });
4615
+ const autoManagePush = config.autoManagePush ?? true;
4616
+ const auth = new AuthModule(
4617
+ httpClient,
4618
+ tokenManager,
4619
+ config,
4620
+ autoManagePush ? {
4621
+ beforeLogout: () => notifications.unsubscribeBeforeLogout(),
4622
+ afterSignIn: () => notifications.resubscribeAfterLogin()
4623
+ } : {}
4624
+ );
4459
4625
  const storage = new StorageModule(httpClient, tokenManager, config);
4460
4626
  const db = new DatabaseModule(httpClient, config.projectId, realtime);
4461
- const notifications = new NotificationsModule(httpClient);
4462
4627
  const functions = new FunctionsModule(httpClient);
4463
4628
  const schedule = new ScheduleModule(httpClient, config.projectId);
4464
4629
  return {