@spacelr/sdk 0.18.4 → 0.19.1

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
  }
@@ -1171,6 +1175,18 @@ var RealtimeClient = class {
1171
1175
  if (ack.error) {
1172
1176
  const message = ack.message ?? ack.error;
1173
1177
  const err = new SpacelrError(message, ack.error);
1178
+ if (keepOnConnectFailure && ack.error === "disconnected" && !this.disposed) {
1179
+ for (const sibling of [...this.streamSubscriptions.get(subscriptionKey) ?? []]) {
1180
+ try {
1181
+ sibling.options.onError?.(err);
1182
+ } catch {
1183
+ }
1184
+ }
1185
+ return {
1186
+ unsubscribe: () => this.unsubscribeStream(state),
1187
+ ack: syntheticAck
1188
+ };
1189
+ }
1174
1190
  this.evictStreamKey(subscriptionKey, err, state);
1175
1191
  options.onError?.(err);
1176
1192
  throw err;
@@ -1963,12 +1979,14 @@ function mapProfile(u) {
1963
1979
  };
1964
1980
  }
1965
1981
  var AuthModule = class _AuthModule {
1966
- constructor(http, tokenManager, config) {
1982
+ constructor(http, tokenManager, config, hooks = {}) {
1967
1983
  this.stateListeners = /* @__PURE__ */ new Set();
1968
1984
  this.lastEmittedState = null;
1969
1985
  this.http = http;
1970
1986
  this.tokenManager = tokenManager;
1971
1987
  this.config = config;
1988
+ this.beforeLogout = hooks.beforeLogout;
1989
+ this.afterSignIn = hooks.afterSignIn;
1972
1990
  this.tokenManager.setRefreshCallback(async (refreshToken) => {
1973
1991
  const result = await this.refresh(refreshToken);
1974
1992
  const expiresAt = result.expires_in ? Math.floor(Date.now() / 1e3) + result.expires_in : void 0;
@@ -2042,8 +2060,26 @@ var AuthModule = class _AuthModule {
2042
2060
  };
2043
2061
  this.stateListeners.clear();
2044
2062
  this.lastEmittedState = null;
2063
+ this.beforeLogout = void 0;
2064
+ this.afterSignIn = void 0;
2065
+ }
2066
+ /**
2067
+ * Install the tokens of a completed sign-in. Signing in over a live session
2068
+ * (e.g. user B over user A without a logout) first runs `beforeLogout` with
2069
+ * the outgoing session's still-valid token, so this device's push leaves
2070
+ * the previous user before it is re-registered for the new one.
2071
+ */
2072
+ async installSession(tokens) {
2073
+ if (this.beforeLogout && await this.tokenManager.getStoredTokens()) {
2074
+ await this.beforeLogout().catch(() => void 0);
2075
+ }
2076
+ await this.tokenManager.setTokens(tokens);
2077
+ this.emitState("authenticated");
2045
2078
  }
2046
2079
  emitState(state) {
2080
+ if (state === "authenticated") {
2081
+ this.afterSignIn?.().catch(() => void 0);
2082
+ }
2047
2083
  if (state === this.lastEmittedState) return;
2048
2084
  this.lastEmittedState = state;
2049
2085
  for (const listener of this.stateListeners) {
@@ -2093,6 +2129,7 @@ var AuthModule = class _AuthModule {
2093
2129
  return mapProfile(data.user ?? data);
2094
2130
  }
2095
2131
  async logout() {
2132
+ await this.beforeLogout?.().catch(() => void 0);
2096
2133
  try {
2097
2134
  await this.http.request({
2098
2135
  method: "POST",
@@ -2180,12 +2217,11 @@ var AuthModule = class _AuthModule {
2180
2217
  body
2181
2218
  });
2182
2219
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2183
- await this.tokenManager.setTokens({
2220
+ await this.installSession({
2184
2221
  accessToken: response.access_token,
2185
2222
  refreshToken: response.refresh_token,
2186
2223
  expiresAt
2187
2224
  });
2188
- this.emitState("authenticated");
2189
2225
  return response;
2190
2226
  }
2191
2227
  async generatePKCE() {
@@ -2431,12 +2467,11 @@ var AuthModule = class _AuthModule {
2431
2467
  }
2432
2468
  async storeTokensFromLogin(response) {
2433
2469
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2434
- await this.tokenManager.setTokens({
2470
+ await this.installSession({
2435
2471
  accessToken: response.access_token,
2436
2472
  refreshToken: response.refresh_token,
2437
2473
  expiresAt
2438
2474
  });
2439
- this.emitState("authenticated");
2440
2475
  }
2441
2476
  // ─── Recover-with-phrase (#784) ───
2442
2477
  // For an email-less passkey account (#780) that has lost every passkey. The
@@ -2667,12 +2702,11 @@ var AuthModule = class _AuthModule {
2667
2702
  async storeTokensFromRegister(response) {
2668
2703
  if (!response.access_token) return;
2669
2704
  const expiresAt = response.expires_in ? Math.floor(Date.now() / 1e3) + response.expires_in : void 0;
2670
- await this.tokenManager.setTokens({
2705
+ await this.installSession({
2671
2706
  accessToken: response.access_token,
2672
2707
  refreshToken: response.refresh_token,
2673
2708
  expiresAt
2674
2709
  });
2675
- this.emitState("authenticated");
2676
2710
  }
2677
2711
  };
2678
2712
 
@@ -4160,11 +4194,20 @@ var DatabaseModule = class {
4160
4194
 
4161
4195
  // libs/sdk/src/modules/notifications.module.ts
4162
4196
  var DEVICE_ID_KEY = "spacelr_device_id";
4163
- var NotificationsModule = class {
4164
- constructor(http) {
4197
+ var REGISTRATION_KEY_PREFIX = "spacelr_push_registration:";
4198
+ var PUSH_LOGOUT_TIMEOUT_MS = 3e3;
4199
+ var NotificationsModule = class _NotificationsModule {
4200
+ constructor(http, options = {}) {
4165
4201
  this.http = http;
4166
4202
  this.customDeviceId = null;
4167
4203
  this.customDeviceName = null;
4204
+ // Fallback when localStorage is unavailable or refuses writes.
4205
+ this.memoryRegistration = null;
4206
+ // Push register/unregister calls run strictly in call order, so a late
4207
+ // re-register can never land after the logout's unregister (or overwrite a
4208
+ // newer registration the app just made).
4209
+ this.pushQueue = Promise.resolve();
4210
+ this.registrationKey = `${REGISTRATION_KEY_PREFIX}${options.projectId ?? "default"}`;
4168
4211
  }
4169
4212
  /** Set a custom device ID (e.g. from Capacitor Preferences for persistence beyond localStorage) */
4170
4213
  setDeviceId(id) {
@@ -4178,12 +4221,16 @@ var NotificationsModule = class {
4178
4221
  getDeviceId() {
4179
4222
  if (this.customDeviceId) return this.customDeviceId;
4180
4223
  if (typeof localStorage === "undefined") return void 0;
4181
- let id = localStorage.getItem(DEVICE_ID_KEY);
4182
- if (!id) {
4183
- id = crypto.randomUUID();
4184
- localStorage.setItem(DEVICE_ID_KEY, id);
4224
+ try {
4225
+ let id = localStorage.getItem(DEVICE_ID_KEY);
4226
+ if (!id) {
4227
+ id = crypto.randomUUID();
4228
+ localStorage.setItem(DEVICE_ID_KEY, id);
4229
+ }
4230
+ return id;
4231
+ } catch {
4232
+ return void 0;
4185
4233
  }
4186
- return id;
4187
4234
  }
4188
4235
  /** Get device name: custom name > auto-detected from user agent > undefined */
4189
4236
  getDeviceName() {
@@ -4216,9 +4263,19 @@ var NotificationsModule = class {
4216
4263
  authenticated: true
4217
4264
  });
4218
4265
  }
4219
- /** Register a push subscription (web, android, ios, or web-fcm) */
4266
+ /**
4267
+ * Register a push subscription (web, android, ios, or web-fcm).
4268
+ *
4269
+ * The SDK remembers this device's registration. Unless the client was
4270
+ * created with `autoManagePush: false`, it re-registers it after every
4271
+ * login and unregisters it on `auth.logout()`, so the subscription always
4272
+ * belongs to the signed-in user's current session.
4273
+ */
4220
4274
  async subscribe(subscription, deviceName) {
4221
- return this.http.request({
4275
+ return this.enqueue(() => this.register(subscription, deviceName));
4276
+ }
4277
+ async register(subscription, deviceName) {
4278
+ const info = await this.http.request({
4222
4279
  method: "POST",
4223
4280
  path: "/notifications/subscribe",
4224
4281
  body: {
@@ -4228,20 +4285,23 @@ var NotificationsModule = class {
4228
4285
  },
4229
4286
  authenticated: true
4230
4287
  });
4288
+ this.saveRegistration({ id: info?.id, subscription, deviceName });
4289
+ return info;
4231
4290
  }
4232
- /** Unregister a push subscription */
4291
+ /**
4292
+ * Unregister a push subscription. Unregistering this device's own
4293
+ * subscription also stops the SDK from re-registering it after a login.
4294
+ */
4233
4295
  async unsubscribe(platform, identifier) {
4234
- const body = { platform };
4235
- if (platform === "web") {
4236
- body["endpoint"] = identifier;
4237
- } else {
4238
- body["deviceToken"] = identifier;
4239
- }
4240
- return this.http.request({
4241
- method: "DELETE",
4242
- path: "/notifications/subscribe",
4243
- body,
4244
- authenticated: true
4296
+ return this.enqueue(async () => {
4297
+ try {
4298
+ return await this.deleteSubscription(platform, identifier);
4299
+ } finally {
4300
+ const stored = this.loadRegistration();
4301
+ if (stored?.subscription.platform === platform && _NotificationsModule.identifierOf(stored.subscription) === identifier) {
4302
+ this.saveRegistration(null);
4303
+ }
4304
+ }
4245
4305
  });
4246
4306
  }
4247
4307
  /**
@@ -4251,12 +4311,114 @@ var NotificationsModule = class {
4251
4311
  * by the listing and so cannot be passed to {@link unsubscribe}).
4252
4312
  */
4253
4313
  async unsubscribeById(subscriptionId) {
4314
+ return this.enqueue(async () => {
4315
+ try {
4316
+ return await this.http.request({
4317
+ method: "DELETE",
4318
+ path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4319
+ authenticated: true
4320
+ });
4321
+ } finally {
4322
+ if (this.loadRegistration()?.id === subscriptionId) {
4323
+ this.saveRegistration(null);
4324
+ }
4325
+ }
4326
+ });
4327
+ }
4328
+ /**
4329
+ * Re-register this device's remembered subscription for the user who just
4330
+ * signed in, binding it to their new session (#1003). The client calls this
4331
+ * after every sign-in unless `autoManagePush` is false; call it yourself
4332
+ * after signing in via `setTokens()`. No-op when this device never
4333
+ * subscribed. Best-effort: a failure leaves the device without push until
4334
+ * the app subscribes again.
4335
+ */
4336
+ async resubscribeAfterLogin() {
4337
+ await this.enqueue(async () => {
4338
+ const stored = this.loadRegistration();
4339
+ if (!stored) return;
4340
+ try {
4341
+ await this.register(stored.subscription, stored.deviceName);
4342
+ } catch (error) {
4343
+ console.warn("[spacelr] Could not re-register push after login:", error);
4344
+ }
4345
+ });
4346
+ }
4347
+ /**
4348
+ * Unregister this device's subscription while the session is still valid,
4349
+ * so a signed-out device stops receiving the user's pushes. The remembered
4350
+ * registration is kept, so the next sign-in re-registers it. `auth.logout()`
4351
+ * calls this first unless `autoManagePush` is false; call it yourself before
4352
+ * clearing tokens via `clearTokens()`. Best-effort.
4353
+ */
4354
+ async unsubscribeBeforeLogout() {
4355
+ const unregistered = this.enqueue(async () => {
4356
+ const stored = this.loadRegistration();
4357
+ if (!stored) return;
4358
+ await this.deleteSubscription(
4359
+ stored.subscription.platform,
4360
+ _NotificationsModule.identifierOf(stored.subscription)
4361
+ ).catch(() => void 0);
4362
+ });
4363
+ let timer;
4364
+ await Promise.race([
4365
+ unregistered,
4366
+ new Promise((resolve) => {
4367
+ timer = setTimeout(resolve, PUSH_LOGOUT_TIMEOUT_MS);
4368
+ })
4369
+ ]);
4370
+ clearTimeout(timer);
4371
+ }
4372
+ enqueue(op) {
4373
+ const run = this.pushQueue.then(op, op);
4374
+ this.pushQueue = run.catch(() => void 0);
4375
+ return run;
4376
+ }
4377
+ deleteSubscription(platform, identifier) {
4378
+ const body = { platform };
4379
+ if (platform === "web") {
4380
+ body["endpoint"] = identifier;
4381
+ } else {
4382
+ body["deviceToken"] = identifier;
4383
+ }
4254
4384
  return this.http.request({
4255
4385
  method: "DELETE",
4256
- path: `/notifications/subscriptions/${encodeURIComponent(subscriptionId)}`,
4386
+ path: "/notifications/subscribe",
4387
+ body,
4257
4388
  authenticated: true
4258
4389
  });
4259
4390
  }
4391
+ /** The value `unsubscribe()` identifies a subscription by: endpoint for web, token otherwise. */
4392
+ static identifierOf(subscription) {
4393
+ return (subscription.platform === "web" ? subscription.endpoint : subscription.deviceToken) ?? "";
4394
+ }
4395
+ static isStoredRegistration(value) {
4396
+ if (typeof value !== "object" || value === null) return false;
4397
+ const subscription = value.subscription;
4398
+ return typeof subscription === "object" && subscription !== null && typeof subscription.platform === "string";
4399
+ }
4400
+ loadRegistration() {
4401
+ if (typeof localStorage === "undefined") return this.memoryRegistration;
4402
+ try {
4403
+ const raw = localStorage.getItem(this.registrationKey);
4404
+ const parsed = raw ? JSON.parse(raw) : null;
4405
+ return _NotificationsModule.isStoredRegistration(parsed) ? parsed : this.memoryRegistration;
4406
+ } catch {
4407
+ return this.memoryRegistration;
4408
+ }
4409
+ }
4410
+ saveRegistration(registration) {
4411
+ this.memoryRegistration = registration;
4412
+ if (typeof localStorage === "undefined") return;
4413
+ try {
4414
+ if (registration) {
4415
+ localStorage.setItem(this.registrationKey, JSON.stringify(registration));
4416
+ } else {
4417
+ localStorage.removeItem(this.registrationKey);
4418
+ }
4419
+ } catch {
4420
+ }
4421
+ }
4260
4422
  /** Get all subscriptions for the current user */
4261
4423
  async getSubscriptions() {
4262
4424
  return this.http.request({
@@ -4459,10 +4621,21 @@ function createClient(config) {
4459
4621
  getToken: () => tokenManager.getAccessToken(),
4460
4622
  onTokenRefreshed: (listener) => tokenManager.onTokenRefreshed((tokens) => listener(tokens.accessToken))
4461
4623
  });
4462
- const auth = new AuthModule(httpClient, tokenManager, config);
4624
+ const notifications = new NotificationsModule(httpClient, {
4625
+ projectId: config.projectId
4626
+ });
4627
+ const autoManagePush = config.autoManagePush ?? true;
4628
+ const auth = new AuthModule(
4629
+ httpClient,
4630
+ tokenManager,
4631
+ config,
4632
+ autoManagePush ? {
4633
+ beforeLogout: () => notifications.unsubscribeBeforeLogout(),
4634
+ afterSignIn: () => notifications.resubscribeAfterLogin()
4635
+ } : {}
4636
+ );
4463
4637
  const storage = new StorageModule(httpClient, tokenManager, config);
4464
4638
  const db = new DatabaseModule(httpClient, config.projectId, realtime);
4465
- const notifications = new NotificationsModule(httpClient);
4466
4639
  const functions = new FunctionsModule(httpClient);
4467
4640
  const schedule = new ScheduleModule(httpClient, config.projectId);
4468
4641
  return {