@spacemolt/lib 18.1.3 → 18.2.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/README.md CHANGED
@@ -86,6 +86,8 @@ Every game command is one of two kinds, classified straight from the spec
86
86
  `travel`/`jump`), and the local state cache is already updated by the time it
87
87
  returns. Mutations are serialized per account by default, matching the server's
88
88
  one-action-per-tick rule, and `rate_limited` responses are retried for you.
89
+ A `per_ip` rate limit pauses every account on the same client until its
90
+ `retry_after` passes, so sibling accounts do not escalate it to an IP timeout.
89
91
 
90
92
  Call commands three ways — all equivalent, all paced and cached:
91
93
 
@@ -127,7 +129,8 @@ reuse after its request timed out can settle on the wrong response.
127
129
  ### Local state cache
128
130
 
129
131
  Seeded from `get_status` after auth and updated from the delta on every
130
- mutation outcome. Read it locally:
132
+ mutation outcome. The `gift_received`, `refueled_by` and `repaired_by` pushes
133
+ also update credits, fuel and hull. Read it locally:
131
134
 
132
135
  ```ts
133
136
  // the 9 sections: player, ship, modules, cargo, location, missions, queue, skills, prize_recoveries
package/dist/account.d.ts CHANGED
@@ -117,6 +117,14 @@ export interface AccountOptions {
117
117
  fetchImpl?: typeof fetch;
118
118
  /** Max automatic retries when a command is `rate_limited`. Default 5. */
119
119
  maxRateLimitRetries?: number;
120
+ /**
121
+ * Shared per-IP backoff deadline (epoch ms). A `per_ip` rate limit moves it to
122
+ * `retry_after`, and every account given the same object holds all of its
123
+ * sends until then. `SpacemoltClient` shares one across its accounts.
124
+ */
125
+ ipBackoff?: {
126
+ until: number;
127
+ };
120
128
  /** Stable id this account is managed under (e.g. the credential-store key / username). Exposed as `account.id`. */
121
129
  id?: string;
122
130
  /**
@@ -173,6 +181,7 @@ export interface RegisterResult {
173
181
  /** Full initial game state from the following `logged_in` frame. */
174
182
  state: LoggedInPayload;
175
183
  }
184
+ export declare const delay: (ms: number, signal?: AbortSignal) => Promise<void>;
176
185
  export declare class Account {
177
186
  private socket;
178
187
  private readonly scheduleOpen?;
@@ -193,6 +202,7 @@ export declare class Account {
193
202
  private readonly credentialsProvider?;
194
203
  private readonly fetchImpl?;
195
204
  private readonly maxRateLimitRetries;
205
+ private readonly ipBackoff;
196
206
  private readonly connectTimeoutMs;
197
207
  private readonly queryTimeoutMs;
198
208
  private readonly mutationTimeoutMs;
@@ -227,6 +237,7 @@ export declare class Account {
227
237
  private readonly disconnectedListeners;
228
238
  private readonly rateLimitedListeners;
229
239
  constructor(opts?: AccountOptions);
240
+ private patchFromPush;
230
241
  private makeSocket;
231
242
  /** Live view of the cached game state. Treat as read-only. */
232
243
  get state(): Readonly<GameState>;
@@ -525,6 +536,11 @@ export declare class Account {
525
536
  /** Returns whether the auth exchange was accepted — a caller must not send its frame when it wasn't. */
526
537
  private beginAuth;
527
538
  private sendFrame;
539
+ /**
540
+ * A per-IP limit throttles every account on this IP, so hold until it lifts.
541
+ * Up to 1s of jitter so the fleet does not resume in one burst.
542
+ */
543
+ private waitForIpBackoff;
528
544
  /** Throws unless `socket` is still this account's live, wanted transport. */
529
545
  private assertTransport;
530
546
  private sendFrameNow;
package/dist/client.d.ts CHANGED
@@ -177,6 +177,8 @@ export declare class SpacemoltClient {
177
177
  private readonly opts;
178
178
  private readonly store;
179
179
  private readonly connected;
180
+ /** One per-IP backoff deadline for every managed account; see `AccountOptions.ipBackoff`. */
181
+ private readonly ipBackoff;
180
182
  /** The pending connect or register for each id, and the controller that cancels it. */
181
183
  private readonly pending;
182
184
  /** Reconnect chains in flight, keyed by the exact `Account` they restore. */
package/dist/index.js CHANGED
@@ -4440,7 +4440,21 @@ var DEFAULT_URL = "wss://game.spacemolt.com/ws/v2";
4440
4440
  var DEFAULT_CONNECT_TIMEOUT_MS = 15000;
4441
4441
  var DEFAULT_MUTATION_TIMEOUT_MS = 600000;
4442
4442
  var DEFAULT_FAST_MUTATION_TIMEOUT_MS = 180000;
4443
- var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
4443
+ var delay = (ms, signal) => new Promise((resolve, reject) => {
4444
+ if (signal?.aborted) {
4445
+ reject(signal.reason);
4446
+ return;
4447
+ }
4448
+ const abort = () => {
4449
+ clearTimeout(timer);
4450
+ reject(signal?.reason);
4451
+ };
4452
+ const timer = setTimeout(() => {
4453
+ signal?.removeEventListener("abort", abort);
4454
+ resolve();
4455
+ }, ms);
4456
+ signal?.addEventListener("abort", abort, { once: true });
4457
+ });
4444
4458
  function withTimeout(promise, ms, message) {
4445
4459
  return new Promise((resolve, reject) => {
4446
4460
  const timer = setTimeout(() => reject(new SpacemoltError("connect_timeout", message)), ms);
@@ -4577,6 +4591,7 @@ class Account {
4577
4591
  credentialsProvider;
4578
4592
  fetchImpl;
4579
4593
  maxRateLimitRetries;
4594
+ ipBackoff;
4580
4595
  connectTimeoutMs;
4581
4596
  queryTimeoutMs;
4582
4597
  mutationTimeoutMs;
@@ -4619,6 +4634,7 @@ class Account {
4619
4634
  this.credentialsProvider = opts.credentials;
4620
4635
  this.fetchImpl = opts.fetchImpl;
4621
4636
  this.maxRateLimitRetries = opts.maxRateLimitRetries ?? 5;
4637
+ this.ipBackoff = opts.ipBackoff ?? { until: 0 };
4622
4638
  this.connectTimeoutMs = opts.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
4623
4639
  this.queryTimeoutMs = opts.queryTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
4624
4640
  this.mutationTimeoutMs = opts.mutationTimeoutMs ?? DEFAULT_MUTATION_TIMEOUT_MS;
@@ -4633,6 +4649,29 @@ class Account {
4633
4649
  this.observationActiveScanState = false;
4634
4650
  this.bridgeObservationToLocation();
4635
4651
  });
4652
+ this.emitter.on("gift_received", (payload) => {
4653
+ const credits = this.cache.credits;
4654
+ if (typeof payload.credits === "number" && credits !== undefined) {
4655
+ this.patchFromPush("player", { credits: credits + payload.credits });
4656
+ }
4657
+ });
4658
+ this.emitter.on("refueled_by", (payload) => {
4659
+ if (typeof payload.fuel_now === "number" && typeof payload.fuel_max === "number") {
4660
+ this.patchFromPush("ship", { fuel: payload.fuel_now, max_fuel: payload.fuel_max });
4661
+ }
4662
+ });
4663
+ this.emitter.on("repaired_by", (payload) => {
4664
+ if (typeof payload.hull === "number" && typeof payload.max_hull === "number") {
4665
+ this.patchFromPush("ship", { hull: payload.hull, max_hull: payload.max_hull });
4666
+ }
4667
+ });
4668
+ }
4669
+ patchFromPush(section, patch) {
4670
+ const changed = this.cache.patchSection(section, patch);
4671
+ if (!changed.length)
4672
+ return;
4673
+ this.stateRevision++;
4674
+ this.emitStateChange(changed);
4636
4675
  }
4637
4676
  makeSocket() {
4638
4677
  this.transportAbort?.abort(new ConnectionClosedError("socket replaced"));
@@ -4717,6 +4756,8 @@ class Account {
4717
4756
  const socket = this.socket;
4718
4757
  this._welcome = null;
4719
4758
  const signal = this.transportAbort.signal;
4759
+ if (this.ipBackoff.until > Date.now())
4760
+ await this.waitForIpBackoff(signal);
4720
4761
  await admit(this.scheduleOpen, { accountId: this._id, sessionId: this.sessionId, signal }, () => {
4721
4762
  this.assertTransport(socket, signal);
4722
4763
  return socket.connect();
@@ -5158,12 +5199,19 @@ class Account {
5158
5199
  async sendFrame(tool, action, payload, requestId, beforeSend) {
5159
5200
  const socket = this.socket;
5160
5201
  const signal = this.transportAbort.signal;
5202
+ if (tool !== "spacemolt_auth" && this.ipBackoff.until > Date.now())
5203
+ await this.waitForIpBackoff(signal);
5161
5204
  await admit(this.scheduleSend, { accountId: this._id, sessionId: this.sessionId, signal, tool, action, requestId }, () => {
5162
5205
  this.assertTransport(socket, signal);
5163
5206
  beforeSend?.();
5164
5207
  this.sendFrameNow(socket, tool, action, payload, requestId);
5165
5208
  }, "scheduleSend send()");
5166
5209
  }
5210
+ async waitForIpBackoff(signal) {
5211
+ for (let waitMs = this.ipBackoff.until - Date.now();waitMs > 0; waitMs = this.ipBackoff.until - Date.now()) {
5212
+ await delay(waitMs + Math.random() * 1000, signal);
5213
+ }
5214
+ }
5167
5215
  assertTransport(socket, signal) {
5168
5216
  signal.throwIfAborted();
5169
5217
  if (this.socket !== socket || this.userClosing)
@@ -5262,6 +5310,10 @@ class Account {
5262
5310
  this.warnMalformedFrame(frame);
5263
5311
  return;
5264
5312
  }
5313
+ const details = frame.payload.details;
5314
+ if (details?.scope === "per_ip" && typeof details.retry_after === "number") {
5315
+ this.ipBackoff.until = Math.max(this.ipBackoff.until, Date.now() + details.retry_after * 1000);
5316
+ }
5265
5317
  if (this.correlator.handle(frame))
5266
5318
  return;
5267
5319
  const auth = this.pendingAuth;
@@ -5709,26 +5761,12 @@ async function fetchStations(httpBaseUrl, opts = {}) {
5709
5761
  var DEFAULT_HTTP_BASE = "https://game.spacemolt.com";
5710
5762
  var DEFAULT_CONNECT_RETRY = { maxRetries: 8, baseDelayMs: 2000, maxDelayMs: 60000 };
5711
5763
  var CONNECT_RATE_WINDOW_MS = 60000;
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
- });
5727
5764
 
5728
5765
  class SpacemoltClient {
5729
5766
  opts;
5730
5767
  store;
5731
5768
  connected = new Map;
5769
+ ipBackoff = { until: 0 };
5732
5770
  pending = new Map;
5733
5771
  reconnects = new Map;
5734
5772
  recentStarts = [];
@@ -5858,7 +5896,7 @@ class SpacemoltClient {
5858
5896
  lastErr = err;
5859
5897
  if (i < retry.maxRetries) {
5860
5898
  const retryAfterMs = retryAfterMsFromClose(err);
5861
- await delay3(retryAfterMs ?? Math.min(retry.baseDelayMs * 2 ** i, retry.maxDelayMs), signal);
5899
+ await delay(retryAfterMs ?? Math.min(retry.baseDelayMs * 2 ** i, retry.maxDelayMs), signal);
5862
5900
  }
5863
5901
  }
5864
5902
  }
@@ -6049,7 +6087,7 @@ class SpacemoltClient {
6049
6087
  const wait = Math.max(this.nextConnectStartAt - now, windowWait);
6050
6088
  if (wait <= 0)
6051
6089
  return;
6052
- await delay3(wait);
6090
+ await delay(wait);
6053
6091
  }
6054
6092
  }
6055
6093
  account(id) {
@@ -6137,6 +6175,7 @@ class SpacemoltClient {
6137
6175
  scheduleOpen: this.opts.scheduleOpen,
6138
6176
  scheduleSend: this.opts.scheduleSend,
6139
6177
  maxRateLimitRetries: this.opts.maxRateLimitRetries,
6178
+ ipBackoff: this.ipBackoff,
6140
6179
  reconnect: false,
6141
6180
  fetchImpl: this.opts.fetchImpl,
6142
6181
  connectTimeoutMs: this.opts.connectTimeoutMs,
@@ -6322,5 +6361,5 @@ export {
6322
6361
  retryAfterMsFromClose
6323
6362
  };
6324
6363
 
6325
- //# debugId=44020F73095CD0DF64756E2164756E21
6364
+ //# debugId=0DC60CF7E9EEB1B264756E2164756E21
6326
6365
  //# sourceMappingURL=index.js.map