@spacemolt/lib 18.0.1 → 18.1.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
@@ -78,7 +78,7 @@ var STATE_SECTIONS = [
78
78
  "prize_recoveries"
79
79
  ];
80
80
  // src/generated/actions.gen.ts
81
- var GENERATED_SPEC_VERSION = "v0.712.0";
81
+ var GENERATED_SPEC_VERSION = "v0.715.2";
82
82
  var ACTIONS = {
83
83
  "spacemolt_arena/accept": {
84
84
  tool: "spacemolt_arena",
@@ -1310,7 +1310,7 @@ var ACTIONS = {
1310
1310
  summary: "Prepare an inter-system jump for your faction mobile base",
1311
1311
  detailsType: "FactionMobileBaseResponse",
1312
1312
  params: [
1313
- { name: "id", type: "string", required: true, description: "Adjacent destination system personally known by the commander", positional: 0 }
1313
+ { name: "id", type: "string", required: true, description: "Adjacent destination system (a frontier system must be charted by the commander or the faction)", positional: 0 }
1314
1314
  ]
1315
1315
  },
1316
1316
  "spacemolt_faction/kick": {
@@ -3858,6 +3858,9 @@ var CLOSE_CODE = {
3858
3858
  AUTH_TIMEOUT: 4002,
3859
3859
  CONNECTION_RATE_LIMITED: 4003
3860
3860
  };
3861
+ function isTerminalClose(err) {
3862
+ return err instanceof ConnectionClosedError && (err.code === CLOSE_CODE.SESSION_REPLACED || err.code === CLOSE_CODE.AUTH_TIMEOUT);
3863
+ }
3861
3864
  function retryAfterMsFromClose(err) {
3862
3865
  if (!(err instanceof ConnectionClosedError) || err.code !== CLOSE_CODE.CONNECTION_RATE_LIMITED)
3863
3866
  return;
@@ -3866,6 +3869,15 @@ function retryAfterMsFromClose(err) {
3866
3869
  }
3867
3870
 
3868
3871
  // src/events/emitter.ts
3872
+ function callHook(hook, label, ...args) {
3873
+ if (!hook)
3874
+ return;
3875
+ try {
3876
+ hook(...args);
3877
+ } catch (err) {
3878
+ console.warn(`[spacemolt] ${label} hook threw: ${err}`);
3879
+ }
3880
+ }
3869
3881
  function notifyListeners(listeners, label, ...args) {
3870
3882
  for (const listener of listeners) {
3871
3883
  try {
@@ -4441,6 +4453,56 @@ function withTimeout(promise, ms, message) {
4441
4453
  });
4442
4454
  });
4443
4455
  }
4456
+ async function admit(schedule, request, op, label) {
4457
+ if (!schedule) {
4458
+ await op();
4459
+ return;
4460
+ }
4461
+ let called = false;
4462
+ let done = false;
4463
+ let failure;
4464
+ const once = () => {
4465
+ if (called)
4466
+ throw new Error(`${label} was called more than once`);
4467
+ called = true;
4468
+ try {
4469
+ const result = op();
4470
+ if (!(result instanceof Promise)) {
4471
+ done = true;
4472
+ return result;
4473
+ }
4474
+ return result.then(() => {
4475
+ done = true;
4476
+ }, (err) => {
4477
+ failure = err;
4478
+ throw err;
4479
+ });
4480
+ } catch (err) {
4481
+ failure = err;
4482
+ throw err;
4483
+ }
4484
+ };
4485
+ try {
4486
+ await schedule(request, once);
4487
+ } catch (err) {
4488
+ if (!done)
4489
+ throw err;
4490
+ console.warn(`[spacemolt] ${label} scheduler threw after it ran: ${err}`);
4491
+ }
4492
+ if (!done)
4493
+ throw failure ?? new Error(`${label} scheduler resolved without running it`);
4494
+ }
4495
+ function anySignal(signals) {
4496
+ const controller = new AbortController;
4497
+ for (const signal of signals) {
4498
+ if (signal.aborted) {
4499
+ controller.abort(signal.reason);
4500
+ break;
4501
+ }
4502
+ signal.addEventListener("abort", () => controller.abort(signal.reason), { once: true });
4503
+ }
4504
+ return controller.signal;
4505
+ }
4444
4506
  function normalizeReconnect(opt) {
4445
4507
  if (!opt)
4446
4508
  return null;
@@ -4451,9 +4513,6 @@ function normalizeReconnect(opt) {
4451
4513
  maxDelayMs: o.maxDelayMs ?? 30000
4452
4514
  };
4453
4515
  }
4454
- function isTerminalClose(err) {
4455
- return err.code === CLOSE_CODE.SESSION_REPLACED || err.code === CLOSE_CODE.AUTH_TIMEOUT;
4456
- }
4457
4516
  function retryAfterMs(err) {
4458
4517
  const retryAfter = err.details?.retry_after;
4459
4518
  const fromDetails = typeof retryAfter === "number" ? retryAfter : undefined;
@@ -4500,6 +4559,10 @@ function requireStructuredContent(result, command) {
4500
4559
 
4501
4560
  class Account {
4502
4561
  socket;
4562
+ scheduleOpen;
4563
+ scheduleSend;
4564
+ transportAbort;
4565
+ sessionId;
4503
4566
  correlator = new Correlator;
4504
4567
  cache = new StateCache;
4505
4568
  emitter = new TypedEmitter;
@@ -4533,6 +4596,7 @@ class Account {
4533
4596
  reconnecting = false;
4534
4597
  attemptClose = null;
4535
4598
  mutationLane = Promise.resolve();
4599
+ serializeMutations;
4536
4600
  marketSubscribedState = false;
4537
4601
  subscribedMarketBaseId;
4538
4602
  observationSubscribedState = false;
@@ -4544,6 +4608,9 @@ class Account {
4544
4608
  disconnectedListeners = new Set;
4545
4609
  rateLimitedListeners = new Set;
4546
4610
  constructor(opts = {}) {
4611
+ this.serializeMutations = opts.serializeMutations ?? true;
4612
+ this.scheduleOpen = opts.scheduleOpen;
4613
+ this.scheduleSend = opts.scheduleSend;
4547
4614
  this.seedState = opts.seedState ?? true;
4548
4615
  this.url = opts.url ?? DEFAULT_URL;
4549
4616
  this.webSocketFactory = opts.webSocketFactory;
@@ -4568,6 +4635,9 @@ class Account {
4568
4635
  });
4569
4636
  }
4570
4637
  makeSocket() {
4638
+ this.transportAbort?.abort(new ConnectionClosedError("socket replaced"));
4639
+ this.transportAbort = new AbortController;
4640
+ this.sessionId = globalThis.crypto?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
4571
4641
  const socket = new Socket({ url: this.url, webSocketFactory: this.webSocketFactory });
4572
4642
  socket.onFrame = (frame) => {
4573
4643
  if (this.socket === socket)
@@ -4646,7 +4716,11 @@ class Account {
4646
4716
  async open() {
4647
4717
  const socket = this.socket;
4648
4718
  this._welcome = null;
4649
- await socket.connect();
4719
+ const signal = this.transportAbort.signal;
4720
+ await admit(this.scheduleOpen, { accountId: this._id, sessionId: this.sessionId, signal }, () => {
4721
+ this.assertTransport(socket, signal);
4722
+ return socket.connect();
4723
+ }, "scheduleOpen open()");
4650
4724
  if (this._welcome)
4651
4725
  return this._welcome;
4652
4726
  let waiter;
@@ -4676,11 +4750,12 @@ class Account {
4676
4750
  }, reject);
4677
4751
  if (accepted)
4678
4752
  authEntry = this.pendingAuth ?? undefined;
4679
- if (accepted)
4680
- this.sendFrame("spacemolt_auth", "register", { ...params }, this.nextRequestId());
4681
4753
  });
4754
+ registerPromise.catch(() => {});
4682
4755
  let result;
4683
4756
  try {
4757
+ if (authEntry)
4758
+ await this.sendFrame("spacemolt_auth", "register", { ...params }, this.nextRequestId());
4684
4759
  result = await withTimeout(registerPromise, this.connectTimeoutMs, `No register response received within ${this.connectTimeoutMs}ms`);
4685
4760
  } catch (err) {
4686
4761
  if (authEntry && this.pendingAuth === authEntry)
@@ -4713,7 +4788,14 @@ class Account {
4713
4788
  httpBaseUrl: creds.httpBaseUrl,
4714
4789
  apiKey: creds.apiKey,
4715
4790
  playerId: creds.playerId,
4716
- fetchImpl: this.fetchImpl
4791
+ fetchImpl: Object.assign((input, init) => (this.fetchImpl ?? fetch)(input, {
4792
+ ...init,
4793
+ signal: anySignal([
4794
+ this.transportAbort.signal,
4795
+ AbortSignal.timeout(this.connectTimeoutMs),
4796
+ ...init?.signal ? [init.signal] : []
4797
+ ])
4798
+ }), { preconnect: (this.fetchImpl ?? fetch).preconnect })
4717
4799
  });
4718
4800
  await this.loginToken(token);
4719
4801
  return;
@@ -4759,8 +4841,9 @@ class Account {
4759
4841
  return this.withRateLimitRetry(`${tool}.${action}`, async () => {
4760
4842
  const id = this.claimRequestId(requestId);
4761
4843
  const promise = this.correlator.awaitQuery(id);
4844
+ promise.catch(() => {});
4762
4845
  try {
4763
- this.sendFrame(tool, action, payload, id);
4846
+ await this.sendFrame(tool, action, payload, id);
4764
4847
  return await withTimeout(promise, this.queryTimeoutMs, `No response to ${tool}/${action} within ${this.queryTimeoutMs}ms`);
4765
4848
  } catch (err) {
4766
4849
  this.correlator.cancel(id);
@@ -4772,7 +4855,7 @@ class Account {
4772
4855
  const mutationTimeoutMs = TRANSIT_ACTIONS.has(`${tool}/${action}`) ? this.mutationTimeoutMs : this.fastMutationTimeoutMs;
4773
4856
  return this.enqueueMutation(() => this.withRateLimitRetry(`${tool}.${action}`, () => {
4774
4857
  const id = this.claimRequestId(requestId);
4775
- return this.awaitMutationWithTimeout(id, mutationTimeoutMs, () => this.sendFrame(tool, action, payload, id), onAck);
4858
+ return this.awaitMutationWithTimeout(id, mutationTimeoutMs, (beforeSend) => this.sendFrame(tool, action, payload, id, beforeSend), onAck);
4776
4859
  }));
4777
4860
  }
4778
4861
  awaitMutationWithTimeout(requestId, mutationTimeoutMs, send, onAck) {
@@ -4786,7 +4869,6 @@ class Account {
4786
4869
  reject(new SpacemoltError("mutation_timeout", message));
4787
4870
  }, ms);
4788
4871
  };
4789
- arm(this.queryTimeoutMs, `No response to mutation ${requestId} within ${this.queryTimeoutMs}ms`);
4790
4872
  this.correlator.awaitMutation(requestId, (ack) => {
4791
4873
  arm(mutationTimeoutMs, `No action_result for mutation ${requestId} within ${mutationTimeoutMs}ms of its ack`);
4792
4874
  onAck?.(ack);
@@ -4799,14 +4881,12 @@ class Account {
4799
4881
  clearTimeout(timer);
4800
4882
  reject(err instanceof Error ? err : new Error(String(err)));
4801
4883
  });
4802
- try {
4803
- send();
4804
- } catch (err) {
4884
+ send(() => arm(this.queryTimeoutMs, `No response to mutation ${requestId} within ${this.queryTimeoutMs}ms`)).catch((err) => {
4805
4885
  if (timer)
4806
4886
  clearTimeout(timer);
4807
4887
  this.correlator.cancel(requestId);
4808
4888
  reject(err instanceof Error ? err : new Error(String(err)));
4809
- }
4889
+ });
4810
4890
  });
4811
4891
  }
4812
4892
  send(tool, action, payload, requestId) {
@@ -5007,6 +5087,7 @@ class Account {
5007
5087
  }
5008
5088
  close() {
5009
5089
  this.userClosing = true;
5090
+ this.failPendingWork(new ConnectionClosedError("account was closed"));
5010
5091
  this.socket.close();
5011
5092
  }
5012
5093
  onReconnected(listener) {
@@ -5039,11 +5120,12 @@ class Account {
5039
5120
  const accepted = this.beginAuth(resolve, reject);
5040
5121
  if (accepted)
5041
5122
  authEntry = this.pendingAuth ?? undefined;
5042
- if (accepted)
5043
- this.sendFrame("spacemolt_auth", action, payload, this.nextRequestId());
5044
5123
  });
5124
+ authPromise.catch(() => {});
5045
5125
  let state;
5046
5126
  try {
5127
+ if (authEntry)
5128
+ await this.sendFrame("spacemolt_auth", action, payload, this.nextRequestId());
5047
5129
  state = await withTimeout(authPromise, this.connectTimeoutMs, `No auth response received within ${this.connectTimeoutMs}ms`);
5048
5130
  } catch (err) {
5049
5131
  if (authEntry && this.pendingAuth === authEntry)
@@ -5073,23 +5155,28 @@ class Account {
5073
5155
  this.pendingAuth = { onLoggedIn, onError };
5074
5156
  return true;
5075
5157
  }
5076
- sendFrame(tool, action, payload, requestId) {
5158
+ async sendFrame(tool, action, payload, requestId, beforeSend) {
5159
+ const socket = this.socket;
5160
+ const signal = this.transportAbort.signal;
5161
+ await admit(this.scheduleSend, { accountId: this._id, sessionId: this.sessionId, signal, tool, action, requestId }, () => {
5162
+ this.assertTransport(socket, signal);
5163
+ beforeSend?.();
5164
+ this.sendFrameNow(socket, tool, action, payload, requestId);
5165
+ }, "scheduleSend send()");
5166
+ }
5167
+ assertTransport(socket, signal) {
5168
+ signal.throwIfAborted();
5169
+ if (this.socket !== socket || this.userClosing)
5170
+ throw new ConnectionClosedError("account was closed");
5171
+ }
5172
+ sendFrameNow(socket, tool, action, payload, requestId) {
5077
5173
  const isAuthHandshake = tool === "spacemolt_auth" && action !== "logout";
5078
5174
  if (this.reconnectsPending > 0 && !this._authenticated && !isAuthHandshake) {
5079
5175
  throw new ConnectionClosedError("cannot send: account is reconnecting");
5080
5176
  }
5081
5177
  const frame = { tool, action, ...payload ? { payload } : {}, request_id: requestId };
5082
- this.callHook(this.onSend, "onSend", redactForOnSend(frame));
5083
- this.socket.send(frame);
5084
- }
5085
- callHook(hook, label, ...args) {
5086
- if (!hook)
5087
- return;
5088
- try {
5089
- hook(...args);
5090
- } catch (err) {
5091
- console.warn(`[spacemolt] ${label} hook threw: ${err}`);
5092
- }
5178
+ callHook(this.onSend, "onSend", redactForOnSend(frame));
5179
+ socket.send(frame);
5093
5180
  }
5094
5181
  nextRequestId() {
5095
5182
  let id = `r${++this.requestSeq}`;
@@ -5106,7 +5193,7 @@ class Account {
5106
5193
  return requestId;
5107
5194
  }
5108
5195
  routeFrame(frame) {
5109
- this.callHook(this.onReceive, "onReceive", redactForOnReceive(frame));
5196
+ callHook(this.onReceive, "onReceive", redactForOnReceive(frame));
5110
5197
  if (isRecord(frame.payload))
5111
5198
  this.observeTick(frame.payload.tick);
5112
5199
  switch (frame.type) {
@@ -5195,6 +5282,7 @@ class Account {
5195
5282
  console.warn(`[spacemolt] dropped malformed ${frame.type} frame`);
5196
5283
  }
5197
5284
  failPendingWork(err) {
5285
+ this.transportAbort.abort(err);
5198
5286
  this._authenticated = false;
5199
5287
  this.correlator.rejectAll(err);
5200
5288
  if (this.welcomeWaiter) {
@@ -5315,6 +5403,8 @@ class Account {
5315
5403
  }
5316
5404
  }
5317
5405
  enqueueMutation(task) {
5406
+ if (!this.serializeMutations)
5407
+ return task();
5318
5408
  const run = this.mutationLane.then(task, task);
5319
5409
  this.mutationLane = run.then(() => {
5320
5410
  return;
@@ -5619,12 +5709,31 @@ async function fetchStations(httpBaseUrl, opts = {}) {
5619
5709
  var DEFAULT_HTTP_BASE = "https://game.spacemolt.com";
5620
5710
  var DEFAULT_CONNECT_RETRY = { maxRetries: 8, baseDelayMs: 2000, maxDelayMs: 60000 };
5621
5711
  var CONNECT_RATE_WINDOW_MS = 60000;
5622
- var delay3 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5712
+ var delay3 = (ms, signal) => new Promise((resolve, reject) => {
5713
+ if (signal?.aborted) {
5714
+ reject(signal.reason);
5715
+ return;
5716
+ }
5717
+ const abort = () => {
5718
+ clearTimeout(timer);
5719
+ reject(signal?.reason);
5720
+ };
5721
+ const timer = setTimeout(() => {
5722
+ signal?.removeEventListener("abort", abort);
5723
+ resolve();
5724
+ }, ms);
5725
+ signal?.addEventListener("abort", abort, { once: true });
5726
+ });
5623
5727
 
5624
5728
  class SpacemoltClient {
5625
5729
  opts;
5626
5730
  store;
5627
5731
  connected = new Map;
5732
+ pending = new Map;
5733
+ reconnects = new Map;
5734
+ recentStarts = [];
5735
+ nextConnectStartAt = 0;
5736
+ storeWrites = new Map;
5628
5737
  catalogCache;
5629
5738
  catalogFetchedAt = 0;
5630
5739
  mapCache;
@@ -5632,9 +5741,8 @@ class SpacemoltClient {
5632
5741
  accountConnectedListeners = new Set;
5633
5742
  accountReconnectedListeners = new Set;
5634
5743
  accountDisconnectedListeners = new Set;
5635
- rateLimitedQueue = [];
5636
- rateLimitedQueueDraining = false;
5637
- reconnectingIds = new Set;
5744
+ startQueue = [];
5745
+ startQueueDraining = false;
5638
5746
  constructor(opts = {}) {
5639
5747
  this.opts = opts;
5640
5748
  this.store = opts.store ?? new MemoryCredentialStore;
@@ -5699,22 +5807,31 @@ class SpacemoltClient {
5699
5807
  return id;
5700
5808
  }
5701
5809
  async register(params) {
5702
- const account = this.createAccount(params.username);
5703
- this.connected.set(params.username, account);
5810
+ const id = params.username;
5811
+ if (this.pending.has(id) || this.connected.has(id))
5812
+ throw new Error(`account "${id}" is already connecting or connected`);
5813
+ return this.trackPending(id, (signal) => this.scheduleConnection(id, () => this.registerAccount(params, signal), signal), ({ account }) => account);
5814
+ }
5815
+ async registerAccount(params, signal) {
5816
+ const id = params.username;
5817
+ const account = this.createAccount(id);
5818
+ this.connected.set(id, account);
5704
5819
  try {
5705
5820
  await account.connect();
5706
5821
  const result = await account.register(params);
5707
- await this.store.put({
5708
- id: params.username,
5709
- credentials: { kind: "login", username: params.username, password: result.password },
5822
+ await this.persist({
5823
+ id,
5824
+ credentials: { kind: "login", username: id, password: result.password },
5710
5825
  playerId: result.player_id
5711
5826
  });
5712
- account.onDisconnected((err) => this.handleAccountDisconnected(params.username, account, err));
5827
+ this.assertCandidate(id, account, signal);
5828
+ account.onDisconnected((err) => this.handleAccountDisconnected(id, account, err));
5713
5829
  this.notifyAccountConnected(account);
5714
5830
  return { account, result };
5715
5831
  } catch (error) {
5716
5832
  account.close();
5717
- this.connected.delete(params.username);
5833
+ if (this.connected.get(id) === account)
5834
+ this.connected.delete(id);
5718
5835
  throw error;
5719
5836
  }
5720
5837
  }
@@ -5724,49 +5841,118 @@ class SpacemoltClient {
5724
5841
  return { maxRetries: 0, baseDelayMs: 0, maxDelayMs: 0 };
5725
5842
  return { ...DEFAULT_CONNECT_RETRY, ...retryOpt === true ? {} : retryOpt };
5726
5843
  }
5727
- async withConnectRetry(attempt) {
5844
+ async withConnectRetry(attempt, { signal, paced = false } = {}) {
5728
5845
  const retry = this.connectRetryConfig();
5729
5846
  let lastErr;
5730
5847
  for (let i = 0;i <= retry.maxRetries; i++) {
5848
+ if (paced)
5849
+ await this.startSlot(signal);
5850
+ else
5851
+ signal?.throwIfAborted();
5731
5852
  try {
5732
5853
  return await attempt();
5733
5854
  } catch (err) {
5855
+ signal?.throwIfAborted();
5856
+ if (isTerminalClose(err))
5857
+ throw err;
5734
5858
  lastErr = err;
5735
5859
  if (i < retry.maxRetries) {
5736
5860
  const retryAfterMs = retryAfterMsFromClose(err);
5737
- await delay3(retryAfterMs ?? Math.min(retry.baseDelayMs * 2 ** i, retry.maxDelayMs));
5861
+ await delay3(retryAfterMs ?? Math.min(retry.baseDelayMs * 2 ** i, retry.maxDelayMs), signal);
5738
5862
  }
5739
5863
  }
5740
5864
  }
5741
5865
  throw lastErr;
5742
5866
  }
5743
5867
  async connect(id) {
5868
+ return this.connectTracked(id, false);
5869
+ }
5870
+ connectTracked(id, paced) {
5871
+ return this.pending.get(id)?.task ?? this.trackPending(id, (signal) => this.connectAccount(id, signal, paced), (account) => account);
5872
+ }
5873
+ async trackPending(id, run, toAccount) {
5874
+ const controller = new AbortController;
5875
+ const result = run(controller.signal);
5876
+ const task = result.then(toAccount);
5877
+ task.catch(() => {});
5878
+ this.pending.set(id, { task, controller });
5879
+ try {
5880
+ return await result;
5881
+ } finally {
5882
+ if (this.pending.get(id)?.task === task)
5883
+ this.pending.delete(id);
5884
+ }
5885
+ }
5886
+ async connectAccount(id, signal, paced) {
5744
5887
  const existing = this.connected.get(id);
5745
5888
  if (existing)
5746
5889
  return existing;
5747
5890
  const stored = await this.store.get(id);
5748
5891
  if (!stored)
5749
5892
  throw new Error(`no stored credentials for account "${id}"`);
5750
- return this.withConnectRetry(async () => {
5751
- const account = this.createAccount(id);
5752
- this.connected.set(id, account);
5753
- try {
5754
- await account.connect();
5755
- await account.authenticate(stored.credentials);
5756
- await this.capturePlayerId(stored);
5757
- account.onDisconnected((err) => this.handleAccountDisconnected(id, account, err));
5758
- this.notifyAccountConnected(account);
5759
- return account;
5760
- } catch (err) {
5893
+ return this.withConnectRetry(() => this.scheduleConnection(id, () => this.connectCandidate(id, stored, signal), signal), { signal, paced });
5894
+ }
5895
+ async connectCandidate(id, stored, signal) {
5896
+ const account = this.createAccount(id);
5897
+ this.connected.set(id, account);
5898
+ let closed;
5899
+ const stopWatchingClose = account.onDisconnected((err) => {
5900
+ closed = err;
5901
+ });
5902
+ let stage = "connection_open";
5903
+ try {
5904
+ this.connectionStage(account, stage);
5905
+ await account.connect();
5906
+ stage = "authentication";
5907
+ this.connectionStage(account, stage);
5908
+ await account.authenticate(stored.credentials);
5909
+ this.assertCandidate(id, account, signal, closed);
5910
+ stage = "authenticated";
5911
+ this.connectionStage(account, stage);
5912
+ await this.capturePlayerId(stored);
5913
+ this.assertCandidate(id, account, signal, closed);
5914
+ stopWatchingClose();
5915
+ account.onDisconnected((err) => this.handleAccountDisconnected(id, account, err));
5916
+ this.notifyAccountConnected(account);
5917
+ return account;
5918
+ } catch (err) {
5919
+ stopWatchingClose();
5920
+ this.connectionStage(account, stage, err);
5921
+ if (this.connected.get(id) === account)
5761
5922
  this.connected.delete(id);
5762
- account.close();
5763
- throw err;
5764
- }
5923
+ account.close();
5924
+ throw err;
5925
+ }
5926
+ }
5927
+ assertCandidate(id, account, signal, closed) {
5928
+ signal.throwIfAborted();
5929
+ if (this.connected.get(id) !== account || !account.authenticated)
5930
+ throw closed ?? new ConnectionClosedError("connection candidate cancelled");
5931
+ }
5932
+ connectionStage(account, stage, error) {
5933
+ callHook(this.opts.onConnectionStage, "onConnectionStage", account, stage, error);
5934
+ }
5935
+ async scheduleConnection(id, attempt, signal) {
5936
+ signal.throwIfAborted();
5937
+ const run = () => {
5938
+ signal.throwIfAborted();
5939
+ return attempt();
5940
+ };
5941
+ const operation = this.opts.scheduleConnection ? this.opts.scheduleConnection(id, run, signal) : run();
5942
+ let abort = () => {};
5943
+ const cancelled = new Promise((_resolve, reject) => {
5944
+ abort = () => reject(signal.reason);
5945
+ signal.addEventListener("abort", abort, { once: true });
5765
5946
  });
5947
+ try {
5948
+ return await Promise.race([operation, cancelled]);
5949
+ } finally {
5950
+ signal.removeEventListener("abort", abort);
5951
+ }
5766
5952
  }
5767
5953
  async connectAll(opts = {}) {
5768
5954
  const stored = await this.store.list();
5769
- return this.connectIds(stored.map((s) => s.id), opts.onConnect);
5955
+ return this.connectIds(stored.map((s) => s.id), opts.onConnect, opts.onError);
5770
5956
  }
5771
5957
  async listOwnedPlayers() {
5772
5958
  return this.requireClerkAuth().source.listPlayers();
@@ -5789,7 +5975,7 @@ class SpacemoltClient {
5789
5975
  });
5790
5976
  ids.push(player.username);
5791
5977
  }
5792
- return this.connectIds(ids, opts.onConnect);
5978
+ return this.connectIds(ids, opts.onConnect, opts.onError);
5793
5979
  }
5794
5980
  requireClerkAuth() {
5795
5981
  const apiKey = this.opts.clerkApiKey;
@@ -5803,54 +5989,68 @@ class SpacemoltClient {
5803
5989
  });
5804
5990
  return { source: this.clerkSource, apiKey };
5805
5991
  }
5806
- async connectIds(ids, onConnect) {
5992
+ async connectIds(ids, onConnect, onError) {
5807
5993
  const accounts = [];
5808
- await Promise.all(ids.map((id) => this.enqueueRateLimited(() => this.connect(id)).then((account) => {
5994
+ await Promise.all(ids.map((id) => this.connectTracked(id, !this.opts.scheduleConnection).then((account) => {
5809
5995
  accounts.push(account);
5810
5996
  onConnect?.(account);
5811
5997
  }).catch((err) => {
5812
5998
  console.warn(`[spacemolt] failed to connect "${id}": ${err}`);
5999
+ callHook(onError, "onError", id, err);
5813
6000
  })));
5814
6001
  return accounts;
5815
6002
  }
5816
- enqueueRateLimited(task) {
6003
+ startSlot(signal) {
5817
6004
  return new Promise((resolve, reject) => {
5818
- this.rateLimitedQueue.push(async () => {
5819
- try {
5820
- resolve(await task());
5821
- } catch (err) {
5822
- reject(err);
6005
+ const abort = () => reject(signal?.reason);
6006
+ if (signal?.aborted) {
6007
+ abort();
6008
+ return;
6009
+ }
6010
+ signal?.addEventListener("abort", abort, { once: true });
6011
+ this.startQueue.push({
6012
+ signal,
6013
+ start: () => {
6014
+ signal?.removeEventListener("abort", abort);
6015
+ resolve();
5823
6016
  }
5824
6017
  });
5825
- this.drainRateLimitedQueue();
6018
+ this.drainStartQueue();
5826
6019
  });
5827
6020
  }
5828
- async drainRateLimitedQueue() {
5829
- if (this.rateLimitedQueueDraining)
6021
+ async drainStartQueue() {
6022
+ if (this.startQueueDraining)
5830
6023
  return;
5831
- this.rateLimitedQueueDraining = true;
6024
+ this.startQueueDraining = true;
5832
6025
  const batchSize = this.opts.connectBatchSize ?? 100;
5833
6026
  const stagger = this.opts.connectStaggerMs ?? (batchSize > 0 ? Math.ceil(CONNECT_RATE_WINDOW_MS / batchSize) : 250);
5834
- const batchWaitMs = this.opts.connectBatchWaitMs ?? 65000;
5835
- let ranInCurrentBatch = 0;
5836
- let isFirst = true;
5837
- while (this.rateLimitedQueue.length > 0) {
5838
- if (!isFirst) {
5839
- if (batchSize > 0 && ranInCurrentBatch >= batchSize) {
5840
- await delay3(batchWaitMs);
5841
- ranInCurrentBatch = 0;
5842
- } else if (stagger > 0) {
5843
- await delay3(stagger);
5844
- }
5845
- }
5846
- isFirst = false;
5847
- const task = this.rateLimitedQueue.shift();
5848
- if (!task)
5849
- break;
5850
- ranInCurrentBatch++;
5851
- await task();
6027
+ const windowMs = this.opts.connectBatchWaitMs ?? 65000;
6028
+ for (let next = this.startQueue.shift();next; next = this.startQueue.shift()) {
6029
+ if (next.signal?.aborted)
6030
+ continue;
6031
+ await this.waitForStartBudget(batchSize, windowMs);
6032
+ if (next.signal?.aborted)
6033
+ continue;
6034
+ const now = Date.now();
6035
+ this.nextConnectStartAt = now + stagger;
6036
+ if (batchSize > 0)
6037
+ this.recentStarts.push(now);
6038
+ next.start();
6039
+ }
6040
+ this.startQueueDraining = false;
6041
+ }
6042
+ async waitForStartBudget(batchSize, windowMs) {
6043
+ for (;; ) {
6044
+ const now = Date.now();
6045
+ while ((this.recentStarts[0] ?? now) <= now - windowMs)
6046
+ this.recentStarts.shift();
6047
+ const oldest = this.recentStarts[0] ?? now;
6048
+ const windowWait = batchSize > 0 && this.recentStarts.length >= batchSize ? oldest + windowMs - now : 0;
6049
+ const wait = Math.max(this.nextConnectStartAt - now, windowWait);
6050
+ if (wait <= 0)
6051
+ return;
6052
+ await delay3(wait);
5852
6053
  }
5853
- this.rateLimitedQueueDraining = false;
5854
6054
  }
5855
6055
  account(id) {
5856
6056
  return this.connected.get(id);
@@ -5861,29 +6061,57 @@ class SpacemoltClient {
5861
6061
  ids() {
5862
6062
  return [...this.connected.keys()];
5863
6063
  }
6064
+ async cancelConnection(id) {
6065
+ const pending = this.pending.get(id);
6066
+ pending?.controller.abort(new ConnectionClosedError("connection cancelled"));
6067
+ this.pending.delete(id);
6068
+ const account = this.connected.get(id);
6069
+ if (account)
6070
+ this.releaseAccount(account);
6071
+ await pending?.task.catch(() => {});
6072
+ }
6073
+ releaseAccount(account) {
6074
+ const { id } = account;
6075
+ if (id !== undefined && this.connected.get(id) === account) {
6076
+ this.pending.get(id)?.controller.abort(new ConnectionClosedError("account released"));
6077
+ this.connected.delete(id);
6078
+ }
6079
+ this.reconnects.get(account)?.abort(new ConnectionClosedError("account released"));
6080
+ account.close();
6081
+ }
5864
6082
  async remove(id) {
5865
- this.connected.get(id)?.close();
5866
- this.connected.delete(id);
6083
+ await this.cancelConnection(id);
6084
+ await this.storeWrites.get(id)?.catch(() => {});
5867
6085
  await this.store.remove(id);
5868
6086
  }
5869
6087
  closeAll() {
6088
+ const err = new ConnectionClosedError("client closed");
6089
+ for (const { controller } of this.pending.values())
6090
+ controller.abort(err);
6091
+ for (const controller of this.reconnects.values())
6092
+ controller.abort(err);
6093
+ this.pending.clear();
5870
6094
  for (const account of this.connected.values())
5871
6095
  account.close();
5872
6096
  this.connected.clear();
5873
6097
  }
5874
6098
  handleAccountDisconnected(id, account, err) {
5875
- if (this.connected.get(id) !== account || this.reconnectingIds.has(id)) {
6099
+ if (this.connected.get(id) !== account || this.reconnects.has(account)) {
5876
6100
  return;
5877
6101
  }
5878
- const terminal = err.code === CLOSE_CODE.SESSION_REPLACED || err.code === CLOSE_CODE.AUTH_TIMEOUT;
5879
- if (terminal || this.opts.reconnect === false) {
6102
+ if (isTerminalClose(err) || this.opts.reconnect === false) {
5880
6103
  this.connected.delete(id);
5881
6104
  this.notifyAccountDisconnected(id, err);
5882
6105
  return;
5883
6106
  }
5884
- this.reconnectingIds.add(id);
5885
- const wanted = () => this.connected.get(id) === account;
5886
- this.enqueueRateLimited(() => this.withConnectRetry(async () => wanted() ? account.reconnectOnce() : undefined)).then(() => {
6107
+ const controller = new AbortController;
6108
+ this.reconnects.set(account, controller);
6109
+ const { signal } = controller;
6110
+ const wanted = () => !signal.aborted && this.connected.get(id) === account;
6111
+ this.withConnectRetry(() => this.scheduleConnection(id, async () => {
6112
+ if (wanted())
6113
+ await account.reconnectOnce();
6114
+ }, signal), { signal, paced: !this.opts.scheduleConnection }).then(() => {
5887
6115
  if (wanted())
5888
6116
  this.notifyAccountReconnected(account);
5889
6117
  }).catch((reconnectErr) => {
@@ -5891,8 +6119,11 @@ class SpacemoltClient {
5891
6119
  return;
5892
6120
  console.warn(`[spacemolt] failed to reconnect "${id}": ${reconnectErr}`);
5893
6121
  this.connected.delete(id);
5894
- this.notifyAccountDisconnected(id, err);
5895
- }).finally(() => this.reconnectingIds.delete(id));
6122
+ this.notifyAccountDisconnected(id, reconnectErr instanceof ConnectionClosedError && isTerminalClose(reconnectErr) ? reconnectErr : err);
6123
+ }).finally(() => {
6124
+ if (this.reconnects.get(account) === controller)
6125
+ this.reconnects.delete(account);
6126
+ });
5896
6127
  }
5897
6128
  createAccount(id) {
5898
6129
  const account = new Account({
@@ -5902,6 +6133,10 @@ class SpacemoltClient {
5902
6133
  onSend: this.opts.onSend && ((f) => this.opts.onSend?.(id, f)),
5903
6134
  onReceive: this.opts.onReceive && ((f) => this.opts.onReceive?.(id, f)),
5904
6135
  seedState: this.opts.seedState,
6136
+ serializeMutations: this.opts.serializeMutations,
6137
+ scheduleOpen: this.opts.scheduleOpen,
6138
+ scheduleSend: this.opts.scheduleSend,
6139
+ maxRateLimitRetries: this.opts.maxRateLimitRetries,
5905
6140
  reconnect: false,
5906
6141
  fetchImpl: this.opts.fetchImpl,
5907
6142
  connectTimeoutMs: this.opts.connectTimeoutMs,
@@ -5914,14 +6149,25 @@ class SpacemoltClient {
5914
6149
  return stored.credentials;
5915
6150
  }
5916
6151
  });
6152
+ callHook(this.opts.onAccountCreated, "onAccountCreated", account);
5917
6153
  return account;
5918
6154
  }
5919
6155
  async capturePlayerId(stored) {
5920
6156
  const playerId = this.connected.get(stored.id)?.player?.id;
5921
6157
  if (playerId && playerId !== stored.playerId) {
5922
- await this.store.put({ ...stored, playerId });
6158
+ await this.persist({ ...stored, playerId });
5923
6159
  }
5924
6160
  }
6161
+ persist(stored) {
6162
+ const write = this.store.put(stored);
6163
+ this.storeWrites.set(stored.id, write);
6164
+ const forget = () => {
6165
+ if (this.storeWrites.get(stored.id) === write)
6166
+ this.storeWrites.delete(stored.id);
6167
+ };
6168
+ write.then(forget, forget);
6169
+ return write;
6170
+ }
5925
6171
  }
5926
6172
  // src/generated/notifications.gen.ts
5927
6173
  var TYPED_NOTIFICATION_TYPES = [
@@ -6076,5 +6322,5 @@ export {
6076
6322
  retryAfterMsFromClose
6077
6323
  };
6078
6324
 
6079
- //# debugId=233A5B316B131F3F64756E2164756E21
6325
+ //# debugId=D0BB7959B891E5F664756E2164756E21
6080
6326
  //# sourceMappingURL=index.js.map