@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.mjs CHANGED
@@ -393,6 +393,9 @@ var HttpClient = class {
393
393
  };
394
394
 
395
395
  // libs/sdk/src/core/token-storage.ts
396
+ function isStoredTokens(value) {
397
+ return typeof value === "object" && value !== null && "accessToken" in value && typeof value.accessToken === "string";
398
+ }
396
399
  var MemoryTokenStorage = class {
397
400
  constructor() {
398
401
  this.tokens = null;
@@ -415,7 +418,8 @@ var BrowserTokenStorage = class {
415
418
  try {
416
419
  const raw = localStorage.getItem(this.storageKey);
417
420
  if (!raw) return null;
418
- return JSON.parse(raw);
421
+ const parsed = JSON.parse(raw);
422
+ return isStoredTokens(parsed) ? parsed : null;
419
423
  } catch {
420
424
  return null;
421
425
  }
@@ -1301,7 +1305,11 @@ var RealtimeClient = class {
1301
1305
  // rejects on connect_error and they decide whether to retry. Once the
1302
1306
  // first authentication succeeds we re-enable it via the Manager's
1303
1307
  // setters (see authenticated handler).
1304
- reconnection: false
1308
+ reconnection: false,
1309
+ // #1000 — socket.io's 20 s default left a connect that hangs without
1310
+ // a close (browser offline mid-handshake) pending for 20 s before the
1311
+ // retry could start. Also applies to the later auto-reconnects.
1312
+ timeout: 5e3
1305
1313
  });
1306
1314
  this.socket = socket;
1307
1315
  const failInitialConnect = (message) => {
@@ -1912,12 +1920,14 @@ function mapProfile(u) {
1912
1920
  };
1913
1921
  }
1914
1922
  var AuthModule = class _AuthModule {
1915
- constructor(http, tokenManager, config) {
1923
+ constructor(http, tokenManager, config, hooks = {}) {
1916
1924
  this.stateListeners = /* @__PURE__ */ new Set();
1917
1925
  this.lastEmittedState = null;
1918
1926
  this.http = http;
1919
1927
  this.tokenManager = tokenManager;
1920
1928
  this.config = config;
1929
+ this.beforeLogout = hooks.beforeLogout;
1930
+ this.afterSignIn = hooks.afterSignIn;
1921
1931
  this.tokenManager.setRefreshCallback(async (refreshToken) => {
1922
1932
  const result = await this.refresh(refreshToken);
1923
1933
  const expiresAt = result.expires_in ? Math.floor(Date.now() / 1e3) + result.expires_in : void 0;
@@ -1991,8 +2001,26 @@ var AuthModule = class _AuthModule {
1991
2001
  };
1992
2002
  this.stateListeners.clear();
1993
2003
  this.lastEmittedState = null;
2004
+ this.beforeLogout = void 0;
2005
+ this.afterSignIn = void 0;
2006
+ }
2007
+ /**
2008
+ * Install the tokens of a completed sign-in. Signing in over a live session
2009
+ * (e.g. user B over user A without a logout) first runs `beforeLogout` with
2010
+ * the outgoing session's still-valid token, so this device's push leaves
2011
+ * the previous user before it is re-registered for the new one.
2012
+ */
2013
+ async installSession(tokens) {
2014
+ if (this.beforeLogout && await this.tokenManager.getStoredTokens()) {
2015
+ await this.beforeLogout().catch(() => void 0);
2016
+ }
2017
+ await this.tokenManager.setTokens(tokens);
2018
+ this.emitState("authenticated");
1994
2019
  }
1995
2020
  emitState(state) {
2021
+ if (state === "authenticated") {
2022
+ this.afterSignIn?.().catch(() => void 0);
2023
+ }
1996
2024
  if (state === this.lastEmittedState) return;
1997
2025
  this.lastEmittedState = state;
1998
2026
  for (const listener of this.stateListeners) {
@@ -2042,6 +2070,7 @@ var AuthModule = class _AuthModule {
2042
2070
  return mapProfile(data.user ?? data);
2043
2071
  }
2044
2072
  async logout() {
2073
+ await this.beforeLogout?.().catch(() => void 0);
2045
2074
  try {
2046
2075
  await this.http.request({
2047
2076
  method: "POST",
@@ -2129,12 +2158,11 @@ var AuthModule = class _AuthModule {
2129
2158
  body
2130
2159
  });
2131
2160
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2132
- await this.tokenManager.setTokens({
2161
+ await this.installSession({
2133
2162
  accessToken: response.access_token,
2134
2163
  refreshToken: response.refresh_token,
2135
2164
  expiresAt
2136
2165
  });
2137
- this.emitState("authenticated");
2138
2166
  return response;
2139
2167
  }
2140
2168
  async generatePKCE() {
@@ -2380,12 +2408,11 @@ var AuthModule = class _AuthModule {
2380
2408
  }
2381
2409
  async storeTokensFromLogin(response) {
2382
2410
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2383
- await this.tokenManager.setTokens({
2411
+ await this.installSession({
2384
2412
  accessToken: response.access_token,
2385
2413
  refreshToken: response.refresh_token,
2386
2414
  expiresAt
2387
2415
  });
2388
- this.emitState("authenticated");
2389
2416
  }
2390
2417
  // ─── Recover-with-phrase (#784) ───
2391
2418
  // For an email-less passkey account (#780) that has lost every passkey. The
@@ -2616,12 +2643,11 @@ var AuthModule = class _AuthModule {
2616
2643
  async storeTokensFromRegister(response) {
2617
2644
  if (!response.access_token) return;
2618
2645
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2619
- await this.tokenManager.setTokens({
2646
+ await this.installSession({
2620
2647
  accessToken: response.access_token,
2621
2648
  refreshToken: response.refresh_token,
2622
2649
  expiresAt
2623
2650
  });
2624
- this.emitState("authenticated");
2625
2651
  }
2626
2652
  };
2627
2653
 
@@ -4109,11 +4135,20 @@ var DatabaseModule = class {
4109
4135
 
4110
4136
  // libs/sdk/src/modules/notifications.module.ts
4111
4137
  var DEVICE_ID_KEY = "spacelr_device_id";
4112
- var NotificationsModule = class {
4113
- constructor(http) {
4138
+ var REGISTRATION_KEY_PREFIX = "spacelr_push_registration:";
4139
+ var PUSH_LOGOUT_TIMEOUT_MS = 3e3;
4140
+ var NotificationsModule = class _NotificationsModule {
4141
+ constructor(http, options = {}) {
4114
4142
  this.http = http;
4115
4143
  this.customDeviceId = null;
4116
4144
  this.customDeviceName = null;
4145
+ // Fallback when localStorage is unavailable or refuses writes.
4146
+ this.memoryRegistration = null;
4147
+ // Push register/unregister calls run strictly in call order, so a late
4148
+ // re-register can never land after the logout's unregister (or overwrite a
4149
+ // newer registration the app just made).
4150
+ this.pushQueue = Promise.resolve();
4151
+ this.registrationKey = `${REGISTRATION_KEY_PREFIX}${options.projectId ?? "default"}`;
4117
4152
  }
4118
4153
  /** Set a custom device ID (e.g. from Capacitor Preferences for persistence beyond localStorage) */
4119
4154
  setDeviceId(id) {
@@ -4127,12 +4162,16 @@ var NotificationsModule = class {
4127
4162
  getDeviceId() {
4128
4163
  if (this.customDeviceId) return this.customDeviceId;
4129
4164
  if (typeof localStorage === "undefined") return void 0;
4130
- let id = localStorage.getItem(DEVICE_ID_KEY);
4131
- if (!id) {
4132
- id = crypto.randomUUID();
4133
- localStorage.setItem(DEVICE_ID_KEY, id);
4165
+ try {
4166
+ let id = localStorage.getItem(DEVICE_ID_KEY);
4167
+ if (!id) {
4168
+ id = crypto.randomUUID();
4169
+ localStorage.setItem(DEVICE_ID_KEY, id);
4170
+ }
4171
+ return id;
4172
+ } catch {
4173
+ return void 0;
4134
4174
  }
4135
- return id;
4136
4175
  }
4137
4176
  /** Get device name: custom name > auto-detected from user agent > undefined */
4138
4177
  getDeviceName() {
@@ -4165,9 +4204,19 @@ var NotificationsModule = class {
4165
4204
  authenticated: true
4166
4205
  });
4167
4206
  }
4168
- /** Register a push subscription (web, android, ios, or web-fcm) */
4207
+ /**
4208
+ * Register a push subscription (web, android, ios, or web-fcm).
4209
+ *
4210
+ * The SDK remembers this device's registration. Unless the client was
4211
+ * created with `autoManagePush: false`, it re-registers it after every
4212
+ * login and unregisters it on `auth.logout()`, so the subscription always
4213
+ * belongs to the signed-in user's current session.
4214
+ */
4169
4215
  async subscribe(subscription, deviceName) {
4170
- return this.http.request({
4216
+ return this.enqueue(() => this.register(subscription, deviceName));
4217
+ }
4218
+ async register(subscription, deviceName) {
4219
+ const info = await this.http.request({
4171
4220
  method: "POST",
4172
4221
  path: "/notifications/subscribe",
4173
4222
  body: {
@@ -4177,20 +4226,23 @@ var NotificationsModule = class {
4177
4226
  },
4178
4227
  authenticated: true
4179
4228
  });
4229
+ this.saveRegistration({ id: info?.id, subscription, deviceName });
4230
+ return info;
4180
4231
  }
4181
- /** Unregister a push subscription */
4232
+ /**
4233
+ * Unregister a push subscription. Unregistering this device's own
4234
+ * subscription also stops the SDK from re-registering it after a login.
4235
+ */
4182
4236
  async unsubscribe(platform, identifier) {
4183
- const body = { platform };
4184
- if (platform === "web") {
4185
- body["endpoint"] = identifier;
4186
- } else {
4187
- body["deviceToken"] = identifier;
4188
- }
4189
- return this.http.request({
4190
- method: "DELETE",
4191
- path: "/notifications/subscribe",
4192
- body,
4193
- authenticated: true
4237
+ return this.enqueue(async () => {
4238
+ try {
4239
+ return await this.deleteSubscription(platform, identifier);
4240
+ } finally {
4241
+ const stored = this.loadRegistration();
4242
+ if (stored?.subscription.platform === platform && _NotificationsModule.identifierOf(stored.subscription) === identifier) {
4243
+ this.saveRegistration(null);
4244
+ }
4245
+ }
4194
4246
  });
4195
4247
  }
4196
4248
  /**
@@ -4200,12 +4252,114 @@ var NotificationsModule = class {
4200
4252
  * by the listing and so cannot be passed to {@link unsubscribe}).
4201
4253
  */
4202
4254
  async unsubscribeById(subscriptionId) {
4255
+ return this.enqueue(async () => {
4256
+ try {
4257
+ return await this.http.request({
4258
+ method: "DELETE",
4259
+ path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4260
+ authenticated: true
4261
+ });
4262
+ } finally {
4263
+ if (this.loadRegistration()?.id === subscriptionId) {
4264
+ this.saveRegistration(null);
4265
+ }
4266
+ }
4267
+ });
4268
+ }
4269
+ /**
4270
+ * Re-register this device's remembered subscription for the user who just
4271
+ * signed in, binding it to their new session (#1003). The client calls this
4272
+ * after every sign-in unless `autoManagePush` is false; call it yourself
4273
+ * after signing in via `setTokens()`. No-op when this device never
4274
+ * subscribed. Best-effort: a failure leaves the device without push until
4275
+ * the app subscribes again.
4276
+ */
4277
+ async resubscribeAfterLogin() {
4278
+ await this.enqueue(async () => {
4279
+ const stored = this.loadRegistration();
4280
+ if (!stored) return;
4281
+ try {
4282
+ await this.register(stored.subscription, stored.deviceName);
4283
+ } catch (error) {
4284
+ console.warn("[spacelr] Could not re-register push after login:", error);
4285
+ }
4286
+ });
4287
+ }
4288
+ /**
4289
+ * Unregister this device's subscription while the session is still valid,
4290
+ * so a signed-out device stops receiving the user's pushes. The remembered
4291
+ * registration is kept, so the next sign-in re-registers it. `auth.logout()`
4292
+ * calls this first unless `autoManagePush` is false; call it yourself before
4293
+ * clearing tokens via `clearTokens()`. Best-effort.
4294
+ */
4295
+ async unsubscribeBeforeLogout() {
4296
+ const unregistered = this.enqueue(async () => {
4297
+ const stored = this.loadRegistration();
4298
+ if (!stored) return;
4299
+ await this.deleteSubscription(
4300
+ stored.subscription.platform,
4301
+ _NotificationsModule.identifierOf(stored.subscription)
4302
+ ).catch(() => void 0);
4303
+ });
4304
+ let timer;
4305
+ await Promise.race([
4306
+ unregistered,
4307
+ new Promise((resolve) => {
4308
+ timer = setTimeout(resolve, PUSH_LOGOUT_TIMEOUT_MS);
4309
+ })
4310
+ ]);
4311
+ clearTimeout(timer);
4312
+ }
4313
+ enqueue(op) {
4314
+ const run = this.pushQueue.then(op, op);
4315
+ this.pushQueue = run.catch(() => void 0);
4316
+ return run;
4317
+ }
4318
+ deleteSubscription(platform, identifier) {
4319
+ const body = { platform };
4320
+ if (platform === "web") {
4321
+ body["endpoint"] = identifier;
4322
+ } else {
4323
+ body["deviceToken"] = identifier;
4324
+ }
4203
4325
  return this.http.request({
4204
4326
  method: "DELETE",
4205
- path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4327
+ path: "/notifications/subscribe",
4328
+ body,
4206
4329
  authenticated: true
4207
4330
  });
4208
4331
  }
4332
+ /** The value `unsubscribe()` identifies a subscription by: endpoint for web, token otherwise. */
4333
+ static identifierOf(subscription) {
4334
+ return (subscription.platform === "web" ? subscription.endpoint : subscription.deviceToken) ?? "";
4335
+ }
4336
+ static isStoredRegistration(value) {
4337
+ if (typeof value !== "object" || value === null) return false;
4338
+ const subscription = value.subscription;
4339
+ return typeof subscription === "object" && subscription !== null && typeof subscription.platform === "string";
4340
+ }
4341
+ loadRegistration() {
4342
+ if (typeof localStorage === "undefined") return this.memoryRegistration;
4343
+ try {
4344
+ const raw = localStorage.getItem(this.registrationKey);
4345
+ const parsed = raw ? JSON.parse(raw) : null;
4346
+ return _NotificationsModule.isStoredRegistration(parsed) ? parsed : this.memoryRegistration;
4347
+ } catch {
4348
+ return this.memoryRegistration;
4349
+ }
4350
+ }
4351
+ saveRegistration(registration) {
4352
+ this.memoryRegistration = registration;
4353
+ if (typeof localStorage === "undefined") return;
4354
+ try {
4355
+ if (registration) {
4356
+ localStorage.setItem(this.registrationKey, JSON.stringify(registration));
4357
+ } else {
4358
+ localStorage.removeItem(this.registrationKey);
4359
+ }
4360
+ } catch {
4361
+ }
4362
+ }
4209
4363
  /** Get all subscriptions for the current user */
4210
4364
  async getSubscriptions() {
4211
4365
  return this.http.request({
@@ -4408,10 +4562,21 @@ function createClient(config) {
4408
4562
  getToken: () => tokenManager.getAccessToken(),
4409
4563
  onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
4410
4564
  });
4411
- const auth = new AuthModule(httpClient, tokenManager, config);
4565
+ const notifications = new NotificationsModule(httpClient, {
4566
+ projectId: config.projectId
4567
+ });
4568
+ const autoManagePush = config.autoManagePush ?? true;
4569
+ const auth = new AuthModule(
4570
+ httpClient,
4571
+ tokenManager,
4572
+ config,
4573
+ autoManagePush ? {
4574
+ beforeLogout: () => notifications.unsubscribeBeforeLogout(),
4575
+ afterSignIn: () => notifications.resubscribeAfterLogin()
4576
+ } : {}
4577
+ );
4412
4578
  const storage = new StorageModule(httpClient, tokenManager, config);
4413
4579
  const db = new DatabaseModule(httpClient, config.projectId, realtime);
4414
- const notifications = new NotificationsModule(httpClient);
4415
4580
  const functions = new FunctionsModule(httpClient);
4416
4581
  const schedule = new ScheduleModule(httpClient, config.projectId);
4417
4582
  return {