@zimmerstack/connect 0.7.0 → 0.9.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.
Files changed (51) hide show
  1. package/AGENTS.md +305 -25
  2. package/README.md +572 -56
  3. package/dist/cjs/client.d.ts +528 -13
  4. package/dist/cjs/client.js +778 -46
  5. package/dist/cjs/doctor.d.ts +86 -0
  6. package/dist/cjs/doctor.js +689 -0
  7. package/dist/cjs/errors.d.ts +6 -2
  8. package/dist/cjs/errors.js +7 -2
  9. package/dist/cjs/generated.d.ts +2873 -203
  10. package/dist/cjs/generated.js +222 -8
  11. package/dist/cjs/grid.d.ts +6 -1
  12. package/dist/cjs/grid.js +8 -0
  13. package/dist/cjs/index.d.ts +14 -5
  14. package/dist/cjs/index.js +41 -1
  15. package/dist/cjs/key.d.ts +39 -0
  16. package/dist/cjs/key.js +85 -0
  17. package/dist/cjs/money.d.ts +81 -0
  18. package/dist/cjs/money.js +172 -0
  19. package/dist/cjs/notices.d.ts +44 -0
  20. package/dist/cjs/notices.js +64 -0
  21. package/dist/cjs/shownOnce.d.ts +42 -0
  22. package/dist/cjs/shownOnce.js +83 -0
  23. package/dist/cjs/webhooks.d.ts +182 -3
  24. package/dist/cjs/webhooks.js +75 -1
  25. package/dist/esm/client.d.ts +528 -13
  26. package/dist/esm/client.js +776 -46
  27. package/dist/esm/doctor.d.ts +86 -0
  28. package/dist/esm/doctor.js +685 -0
  29. package/dist/esm/errors.d.ts +6 -2
  30. package/dist/esm/errors.js +7 -2
  31. package/dist/esm/generated.d.ts +2873 -203
  32. package/dist/esm/generated.js +221 -7
  33. package/dist/esm/grid.d.ts +6 -1
  34. package/dist/esm/grid.js +7 -0
  35. package/dist/esm/index.d.ts +14 -5
  36. package/dist/esm/index.js +8 -3
  37. package/dist/esm/key.d.ts +39 -0
  38. package/dist/esm/key.js +81 -0
  39. package/dist/esm/mcp/cli.js +95 -11
  40. package/dist/esm/mcp/reference.generated.js +5741 -1008
  41. package/dist/esm/mcp/server.d.ts +14 -6
  42. package/dist/esm/mcp/server.js +451 -25
  43. package/dist/esm/money.d.ts +81 -0
  44. package/dist/esm/money.js +161 -0
  45. package/dist/esm/notices.d.ts +44 -0
  46. package/dist/esm/notices.js +56 -0
  47. package/dist/esm/shownOnce.d.ts +42 -0
  48. package/dist/esm/shownOnce.js +77 -0
  49. package/dist/esm/webhooks.d.ts +182 -3
  50. package/dist/esm/webhooks.js +69 -0
  51. package/package.json +2 -2
@@ -1,10 +1,31 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ZimmerStack = void 0;
3
+ exports.ZimmerStack = exports.KEYED_WRITES = exports.BEFORE_GO_LIVE_HEADER = void 0;
4
+ exports.aboutHowLong = aboutHowLong;
5
+ exports.readBudgets = readBudgets;
4
6
  exports.attemptTimeoutMs = attemptTimeoutMs;
5
7
  const errors_ts_1 = require("./errors.js");
6
8
  const generated_ts_1 = require("./generated.js");
9
+ const key_ts_1 = require("./key.js");
7
10
  const grid_ts_1 = require("./grid.js");
11
+ /** The header a company key sends with what it writes ahead of go-live (`beforeGoLive: true` on a call). */
12
+ exports.BEFORE_GO_LIVE_HEADER = "x-zs-before-go-live";
13
+ /**
14
+ * The body of a real close or reopen. A caller without types may have put `dryRun` in it, meaning "do not
15
+ * do it": that is refused here, never silently done for real.
16
+ */
17
+ function realOnly(method, body) {
18
+ if (body !== null && typeof body === "object" && "dryRun" in body) {
19
+ throw new errors_ts_1.ZimmerStackUsageError(`zs.availability.${method} does it for real and takes no dryRun. To see what it would do, call zs.availability.${method}DryRun with the same room type and nights. Nothing was sent.`);
20
+ }
21
+ return body;
22
+ }
23
+ /** A dry run that came back as anything but a preview is never passed on as one. */
24
+ function previewOnly(operation, answer) {
25
+ if (answer?.dryRun === true)
26
+ return answer;
27
+ throw new Error(`${operation} was sent as a dry run and the answer is not a preview. Treat it as a real write: read zs.sync.get() and the calendar before you send anything else.`);
28
+ }
8
29
  /** One entity was sent, so the answer names exactly one. */
9
30
  function savedOne(result) {
10
31
  const item = result.items[0];
@@ -13,13 +34,45 @@ function savedOne(result) {
13
34
  return { ...item, channelManager: result.channelManager };
14
35
  }
15
36
  /* ───────────────────────────── the shared core ───────────────────────────── */
16
- /** Requests in flight at once. Writes go one at a time on top of that. */
37
+ /** Requests in flight at once. Writes go one at a time per hotel on top of that. */
17
38
  const PARALLEL = 4;
18
39
  const KEY_SHAPE = /^zsk_(live|test)_[A-Za-z0-9_-]{16,}$/;
19
40
  const IDEMPOTENCY_SHAPE = /^[A-Za-z0-9_-]{10,64}$/;
20
41
  /** After one of these the key will never work again: every later call is refused here, not sent. */
21
42
  const KEY_IS_DEAD = new Set(["API_KEY_INVALID", "API_KEY_REVOKED", "API_KEY_EXPIRED"]);
22
43
  const CATALOG_TTL_MS = 10 * 60_000;
44
+ /**
45
+ * Writes whose route keeps an idempotency key on the server although the contract copy this package was
46
+ * generated from did not say so yet (the API booking's cancel, the sandbox booking's cancel and modify).
47
+ * The client sends a key for them, so a cancel whose answer was lost can be sent again and never lands
48
+ * twice. Once the generated table (`OPERATIONS`) says the same, this list changes nothing.
49
+ */
50
+ exports.KEYED_WRITES = new Set(["POST /bookings/{bookingId}/cancel", "POST /sandbox/bookings/{bookingId}/cancel", "POST /sandbox/bookings/{bookingId}/modify"]);
51
+ /** Routes about the partner's own company: they read no X-ZS-Property, so the client sends none. */
52
+ const COMPANY_ROUTES = ["/webhook-endpoints", "/connect-links", "/billing", "/support-tickets"];
53
+ /** The three writes that name cells: the `cells` budget counts every night of every row they carry. */
54
+ const CELL_WRITES = new Set(["PUT /availability", "PUT /rates", "PUT /restrictions"]);
55
+ /**
56
+ * Whose budget a name in the `RateLimit` headers is.
57
+ *
58
+ * Under a company key every hotel runs under its own key and property budgets, so those belong to that
59
+ * hotel alone: when one hotel's budget is nearly out, only that hotel's calls wait. What every hotel of the
60
+ * client shares waits for everyone: the company's budget, everyone's ceiling and the address's budgets.
61
+ */
62
+ const SHARED_BUDGETS = new Set(["company", "global", "ip", "ip-auth", "key-auth", "global-unauthenticated", "api-address"]);
63
+ /** Budgets that count every request, and the two that count every write. Any other budget is its own operation's. */
64
+ const EVERY_REQUEST = new Set(["key", "property", ...SHARED_BUDGETS]);
65
+ const EVERY_WRITE = new Set(["key-writes", "property-writes"]);
66
+ /** What a refusal's `data.scope` is called in the headers: only the key's own two differ. */
67
+ const HEADER_OF_SCOPE = { requests: "key", writes: "key-writes" };
68
+ /**
69
+ * The channel shield's budgets over an hour and a day, and its pause. A write that only CLOSES inventory is
70
+ * still accepted while they are used up (the safety lane), and only the server can tell which write that
71
+ * is. So the client never holds a write back for one of these: it sends, and reports what the API answers.
72
+ */
73
+ const NEVER_HELD_BACK = new Set(["cells-hour", "cells-day", "vendor-cells-day", "shield-pause", "shield-lane"]);
74
+ /** A wait this long or shorter is the pace of a minute's budget: always waited out, whatever `maxWaitSeconds` says. */
75
+ const SHORT_WAIT_MS = 65_000;
23
76
  function sleep(ms, signal) {
24
77
  return new Promise((resolve, reject) => {
25
78
  if (signal?.aborted)
@@ -57,6 +110,40 @@ function resolveBase(baseUrl) {
57
110
  }
58
111
  return url.origin;
59
112
  }
113
+ /** "about 40 seconds", "about 2 minutes", "about 3 hours": how long a wait is, for a person. */
114
+ function aboutHowLong(ms) {
115
+ const seconds = Math.max(1, Math.round(ms / 1000));
116
+ if (seconds < 90)
117
+ return `about ${seconds} second${seconds === 1 ? "" : "s"}`;
118
+ const minutes = Math.round(seconds / 60);
119
+ if (minutes < 90)
120
+ return `about ${minutes} minutes`;
121
+ const hours = Math.round(minutes / 60);
122
+ return `about ${hours} hour${hours === 1 ? "" : "s"}`;
123
+ }
124
+ /** Read `RateLimit-Policy` and `RateLimit` into one list. Unknown names are kept: a new budget is paced like any other. */
125
+ function readBudgets(policy, state) {
126
+ const quotas = new Map();
127
+ for (const part of (policy ?? "").split(",")) {
128
+ const name = /"([^"]+)"/.exec(part)?.[1];
129
+ if (!name)
130
+ continue;
131
+ const q = /;\s*q=(\d+)/.exec(part);
132
+ const w = /;\s*w=(\d+)/.exec(part);
133
+ quotas.set(name, { quota: q ? Number(q[1]) : undefined, windowSeconds: w ? Number(w[1]) : 60 });
134
+ }
135
+ const out = [];
136
+ for (const part of (state ?? "").split(",")) {
137
+ const name = /"([^"]+)"/.exec(part)?.[1];
138
+ const left = /;\s*r=(\d+)/.exec(part);
139
+ const refill = /;\s*t=(\d+)/.exec(part);
140
+ if (!name || !left || !refill)
141
+ continue;
142
+ const known = quotas.get(name);
143
+ out.push({ name, quota: known?.quota, windowSeconds: known?.windowSeconds ?? 60, remaining: Number(left[1]), resetSeconds: Number(refill[1]) });
144
+ }
145
+ return out;
146
+ }
60
147
  /**
61
148
  * Operations that do a long thing while you wait: adding a hotel creates its account, and removing one takes
62
149
  * it off its booking sites one step at a time. One attempt of these is given at least this long, however
@@ -71,6 +158,50 @@ const PATIENCE_MS = {
71
158
  function attemptTimeoutMs(operation, timeoutMs) {
72
159
  return Math.max(timeoutMs, PATIENCE_MS[operation] ?? 0);
73
160
  }
161
+ /**
162
+ * A wait too long to hold a call open for (a day's budget that is used up) is trusted this long after it
163
+ * was learned: calls it holds are not sent, and come back saying when the budget frees. After that one call
164
+ * goes out again, so a budget that was raised or freed early is noticed.
165
+ */
166
+ const LONG_HOLD_TRUST_MS = 5 * 60_000;
167
+ /**
168
+ * The pace of one hotel, or of what every hotel of the client shares. A hold says "nothing of this kind
169
+ * before `until`": on every request, on every write, or on one operation.
170
+ */
171
+ class Pace {
172
+ all;
173
+ writes;
174
+ operations = new Map();
175
+ /** The cells budget as last seen, less what this client has sent since: a write of more cells than are left waits for the window. */
176
+ cells;
177
+ /** Writes of this hotel go one after another. */
178
+ writeTail = Promise.resolve();
179
+ hold(kind, hold) {
180
+ // Fresh news of the same budget replaces what was known; between two budgets the later one decides.
181
+ const pick = (current) => (!current || current.budget === hold.budget || hold.until >= current.until ? hold : current);
182
+ if (kind === "all")
183
+ this.all = pick(this.all);
184
+ else if (kind === "writes")
185
+ this.writes = pick(this.writes);
186
+ else
187
+ this.operations.set(kind, pick(this.operations.get(kind)));
188
+ }
189
+ /** The latest hold that applies to this call. */
190
+ holdFor(wire, now) {
191
+ let latest;
192
+ const consider = (h) => {
193
+ if (h && h.until > now && (!latest || h.until > latest.until))
194
+ latest = h;
195
+ };
196
+ consider(this.all);
197
+ if (wire.write)
198
+ consider(this.writes);
199
+ consider(this.operations.get(wire.operation));
200
+ if (wire.cells > 0 && this.cells && this.cells.until > now && wire.cells > this.cells.remaining)
201
+ consider({ until: this.cells.until, budget: "cells", learnedAt: now });
202
+ return latest;
203
+ }
204
+ }
74
205
  class Core {
75
206
  #key;
76
207
  mode;
@@ -81,21 +212,24 @@ class Core {
81
212
  #maxWaitSeconds;
82
213
  #allowLiveWritesInTests;
83
214
  #onEvent;
84
- #resumeAll = 0;
85
- #resumeWrites = 0;
215
+ /** What every hotel of this client shares: the company's budget, everyone's ceiling, the address. */
216
+ #shared = new Pace();
217
+ /** One pace and one queue of writes per hotel, so one hotel's budget never holds up another's calls. */
218
+ #hotels = new Map();
86
219
  #active = 0;
87
220
  #queue = [];
88
- #writeTail = Promise.resolve();
89
221
  #dead;
90
222
  catalogs = new Map();
91
223
  /** A sandbox company key's one hotel, found once when a call asked for a hotel and none was named. */
92
224
  soleSandboxProperty;
93
225
  /** The same, once known: sent with every later call that names no hotel, so the refusal is met once. */
94
226
  soleSandboxId;
227
+ /** What the key's own checksum says is wrong with it, when something is (never the key). */
228
+ keyHint;
95
229
  constructor(options) {
96
230
  const g = globalThis;
97
231
  if ((typeof g.window !== "undefined" && typeof g.window.document !== "undefined") || g.navigator?.product === "ReactNative") {
98
- throw new errors_ts_1.ZimmerStackUsageError("@zimmerstack/connect runs on a server only. A key in a browser or a mobile app can be read by anyone and can change a hotel's prices on every channel: call your own server from here, and ZimmerStack from your server (https://docs.zimmerstack.com/sdk#no-server shows the smallest one). If a key was built into this page, anyone can read it now: revoke it and make a new one.");
232
+ throw new errors_ts_1.ZimmerStackUsageError("@zimmerstack/connect runs on a server only. A key in a browser or a mobile app can be read by anyone and can change a hotel's prices on every channel: call your own server from here, and ZimmerStack from your server (https://docs.zimmerstack.com/guides/node-package#no-server shows the smallest one). If a key was built into this page, anyone can read it now: revoke it and make a new one.");
99
233
  }
100
234
  const key = options.apiKey ?? env("ZIMMERSTACK_CONNECT_KEY");
101
235
  if (!key)
@@ -104,6 +238,10 @@ class Core {
104
238
  if (!shape)
105
239
  throw new errors_ts_1.ZimmerStackUsageError("The API key does not look like a ZimmerStack key (zsk_test_… or zsk_live_…). It was not sent anywhere.");
106
240
  this.#key = key.trim();
241
+ // Checked offline, by the key's own checksum (src/key.ts): kept for the day the API refuses the key, so
242
+ // the refusal can say "it was mistyped" instead of leaving the person to guess. Never the key itself.
243
+ const check = (0, key_ts_1.checkKey)(this.#key);
244
+ this.keyHint = check.ok ? undefined : check.message;
107
245
  this.mode = shape[1];
108
246
  this.base = resolveBase(options.baseUrl);
109
247
  const f = options.fetch ?? globalThis.fetch;
@@ -127,6 +265,14 @@ class Core {
127
265
  /* a logger must never break a request */
128
266
  }
129
267
  }
268
+ #hotel(id) {
269
+ let pace = this.#hotels.get(id);
270
+ if (!pace) {
271
+ pace = new Pace();
272
+ this.#hotels.set(id, pace);
273
+ }
274
+ return pace;
275
+ }
130
276
  send(wire) {
131
277
  if (this.#dead) {
132
278
  const d = this.#dead;
@@ -149,11 +295,12 @@ class Core {
149
295
  }
150
296
  if (!wire.write)
151
297
  return this.#attempts(wire);
152
- // Writes go one after another: a burst spends the write budget at once, and two writes to one
153
- // night must reach the record in the order they were made.
298
+ // Writes to one hotel go one after another: a burst spends its write budget at once, and two writes to
299
+ // one night must reach the record in the order they were made. Another hotel's writes do not wait for these.
300
+ const hotel = this.#hotel(wire.hotel);
154
301
  const run = () => this.#attempts(wire);
155
- const result = this.#writeTail.then(run, run);
156
- this.#writeTail = result.catch(() => undefined);
302
+ const result = hotel.writeTail.then(run, run);
303
+ hotel.writeTail = result.catch(() => undefined);
157
304
  return result;
158
305
  }
159
306
  #slot() {
@@ -172,30 +319,102 @@ class Core {
172
319
  return Promise.resolve(take());
173
320
  return new Promise((resolve) => this.#queue.push(() => resolve(take())));
174
321
  }
175
- /** Wait until the budgets the last answers reported have room again, instead of earning a 429. */
322
+ #maxWaitMs(wire) {
323
+ return Math.max(0, wire.maxWaitSeconds ?? this.#maxWaitSeconds) * 1000;
324
+ }
325
+ /** What a call that will not be held open comes back as: the API's own refusal shape, saying when the budget frees. */
326
+ #notNow(wire, budget, waitMs, sent) {
327
+ const retryAfterSeconds = Math.max(1, Math.ceil(waitMs / 1000));
328
+ const message = `${wire.operation} ${sent ? "was refused" : "was not sent"}: the ${budget} budget is used up and has room again in ${aboutHowLong(waitMs)}. Send it again then.`;
329
+ this.#emit({ type: "deferred", operation: wire.operation, scope: budget, retryAfterSeconds, freesAt: new Date(Date.now() + waitMs).toISOString(), message });
330
+ return new errors_ts_1.ZimmerStackError({ status: 429, code: "RATE_LIMITED", message, operation: wire.operation, scope: budget, retryAfterSeconds, retryable: true });
331
+ }
332
+ /**
333
+ * Wait until every budget the last answers reported has room again, instead of earning a 429: the hotel's
334
+ * own budgets and what every hotel shares. The pace of a minute's budget is always waited out. A longer
335
+ * wait (a day's budget that is used up) is waited out only inside `maxWaitSeconds`; past that the call is
336
+ * not sent and comes back as a retryable RATE_LIMITED that says when the budget frees.
337
+ */
176
338
  async #pace(wire) {
177
339
  for (;;) {
178
- const wait = Math.max(this.#resumeAll, wire.write ? this.#resumeWrites : 0) - Date.now();
179
- if (wait <= 0)
340
+ const now = Date.now();
341
+ const own = this.#hotel(wire.hotel).holdFor(wire, now);
342
+ const shared = this.#shared.holdFor(wire, now);
343
+ const hold = own && shared ? (own.until >= shared.until ? own : shared) : (own ?? shared);
344
+ if (!hold)
180
345
  return;
181
- this.#emit({ type: "pace", operation: wire.operation, waitMs: wait });
346
+ const wait = hold.until - now;
347
+ if (wait > SHORT_WAIT_MS && wait > this.#maxWaitMs(wire)) {
348
+ // Too long to hold the call open. While the news is fresh the call is not sent; once it is older,
349
+ // this one goes out to learn whether the budget is still used up.
350
+ if (now - hold.learnedAt < LONG_HOLD_TRUST_MS)
351
+ throw this.#notNow(wire, hold.budget, wait, false);
352
+ hold.until = 0;
353
+ continue;
354
+ }
355
+ this.#emit({ type: "pace", operation: wire.operation, waitMs: wait, scope: hold.budget });
356
+ if (wait > SHORT_WAIT_MS)
357
+ this.#lands(wire, hold.budget, wait);
182
358
  await sleep(wait, wire.signal);
183
359
  }
184
360
  }
185
- /** RateLimit: "key";r=117;t=42, "key-writes";r=29;t=42 (r = requests left, t = seconds until the window has room). */
186
- #notePace(res) {
187
- for (const part of (res.headers.get("ratelimit") ?? "").split(",")) {
188
- const left = /;\s*r=(\d+)/.exec(part);
189
- const refill = /;\s*t=(\d+)/.exec(part);
190
- if (!left || !refill || Number(left[1]) > PARALLEL)
361
+ /** A wait worth telling a person about: the call is held and lands when the budget frees. */
362
+ #lands(wire, budget, waitMs) {
363
+ this.#emit({
364
+ type: "wait",
365
+ operation: wire.operation,
366
+ scope: budget,
367
+ waitMs,
368
+ landsAt: new Date(Date.now() + waitMs).toISOString(),
369
+ message: `${wire.operation} lands in ${aboutHowLong(waitMs)}${budget ? ` (waiting for the ${budget} budget)` : ""}.`,
370
+ });
371
+ }
372
+ /** Whose pace a budget moves: what every hotel shares, or this call's hotel alone. */
373
+ #paceOf(budget, wire) {
374
+ return SHARED_BUDGETS.has(budget) ? this.#shared : this.#hotel(wire.hotel);
375
+ }
376
+ /** Which calls a budget holds: every request, every write, or the one operation it was reported on. */
377
+ #holds(budget, wire) {
378
+ return EVERY_REQUEST.has(budget) ? "all" : EVERY_WRITE.has(budget) ? "writes" : wire.operation;
379
+ }
380
+ /**
381
+ * Read every budget of the answer's headers.
382
+ * RateLimit-Policy: "key";q=120;w=60, "key-writes";q=30;w=60, "property";q=300;w=60, "cells";q=20000;w=60
383
+ * RateLimit: "key";r=117;t=42, "key-writes";r=29;t=42, "property";r=296;t=42, "cells";r=20000;t=0
384
+ * A minute's budget that is nearly out holds the calls it counts until it refills. A budget with a longer
385
+ * window, should the headers carry one, holds only once nothing is left. The cells budget is counted in cells, so it is
386
+ * remembered with what this write just used and compared with the size of the next one.
387
+ */
388
+ #notePace(res, wire) {
389
+ const now = Date.now();
390
+ for (const b of readBudgets(res.headers.get("ratelimit-policy"), res.headers.get("ratelimit"))) {
391
+ if (NEVER_HELD_BACK.has(b.name))
392
+ continue;
393
+ const pace = this.#paceOf(b.name, wire);
394
+ if (b.name === "cells") {
395
+ // The header was read before this write's own cells were counted: take them off.
396
+ const used = res.ok ? wire.cells : 0;
397
+ pace.cells = { remaining: Math.max(0, b.remaining - used), until: now + (b.resetSeconds > 0 ? Math.min(b.resetSeconds, 65) : Math.min(b.windowSeconds, 65)) * 1000 };
191
398
  continue;
192
- const at = Date.now() + Math.min(Number(refill[1]), 65) * 1000;
193
- if (/"[^"]*(writes|bookings|cells)[^"]*"/.test(part))
194
- this.#resumeWrites = Math.max(this.#resumeWrites, at);
195
- else
196
- this.#resumeAll = Math.max(this.#resumeAll, at);
399
+ }
400
+ if (b.windowSeconds <= 60) {
401
+ if (b.remaining > PARALLEL)
402
+ continue;
403
+ pace.hold(this.#holds(b.name, wire), { until: now + Math.min(Math.max(b.resetSeconds, 1), 65) * 1000, budget: b.name, learnedAt: now });
404
+ }
405
+ else if (b.remaining <= 0 && b.resetSeconds > 0) {
406
+ pace.hold(this.#holds(b.name, wire), { until: now + b.resetSeconds * 1000, budget: b.name, learnedAt: now });
407
+ }
197
408
  }
198
409
  }
410
+ /** A refusal names its budget and its wait: later calls of the same kind do not go out to earn the same 429. */
411
+ #noteRefusal(wire, scope, retryAfterSeconds) {
412
+ if (!scope || !retryAfterSeconds || NEVER_HELD_BACK.has(scope))
413
+ return;
414
+ const budget = HEADER_OF_SCOPE[scope] ?? scope;
415
+ const now = Date.now();
416
+ this.#paceOf(budget, wire).hold(this.#holds(budget, wire), { until: now + retryAfterSeconds * 1000, budget, learnedAt: now });
417
+ }
199
418
  async #attempts(wire) {
200
419
  for (let attempt = 1;; attempt++) {
201
420
  await this.#pace(wire);
@@ -238,7 +457,7 @@ class Core {
238
457
  continue;
239
458
  }
240
459
  release();
241
- this.#notePace(res);
460
+ this.#notePace(res, wire);
242
461
  this.#emit({ type: "response", operation: wire.operation, status: res.status, attempt, ms: Date.now() - started });
243
462
  if (res.ok)
244
463
  return json && typeof json === "object" ? json.data : undefined;
@@ -246,6 +465,7 @@ class Core {
246
465
  const code = typeof data.code === "string" ? data.code : `HTTP_${res.status}`;
247
466
  const headerSeconds = Number(res.headers.get("retry-after"));
248
467
  const retryAfter = Number.isFinite(headerSeconds) && headerSeconds > 0 ? headerSeconds : typeof data.retryAfterSeconds === "number" ? data.retryAfterSeconds : undefined;
468
+ const scope = typeof data.scope === "string" ? data.scope : undefined;
249
469
  // What passes with time: a used-up budget, a fault on ZimmerStack's side, a duplicate of a request
250
470
  // still running. Every other answer is a verdict on the request itself.
251
471
  const passesWithTime = res.status === 429 || res.status >= 500 || code === "IDEMPOTENCY_IN_FLIGHT";
@@ -255,21 +475,41 @@ class Core {
255
475
  message: typeof json?.message === "string" && json.message ? json.message : `${wire.operation} answered ${res.status}`,
256
476
  operation: wire.operation,
257
477
  details: data.details,
258
- scope: typeof data.scope === "string" ? data.scope : undefined,
478
+ scope,
259
479
  retryAfterSeconds: retryAfter,
260
480
  retryable: passesWithTime,
261
481
  });
262
482
  if (KEY_IS_DEAD.has(code)) {
263
- this.#dead = error;
264
- throw error;
483
+ // A key the API does not know, whose own checksum does not hold: say so, it is the likeliest reason.
484
+ const refused = code === "API_KEY_INVALID" && this.keyHint
485
+ ? new errors_ts_1.ZimmerStackError({ status: error.status, code, message: `${error.message} ${this.keyHint}`, operation: wire.operation, details: error.details, retryable: false })
486
+ : error;
487
+ this.#dead = refused;
488
+ throw refused;
265
489
  }
490
+ if (res.status === 429)
491
+ this.#noteRefusal(wire, scope, retryAfter);
266
492
  // A 429 was refused before anything ran, so sending it again is always safe. A 5xx may have run.
267
493
  const safeToResend = res.status === 429 || code === "IDEMPOTENCY_IN_FLIGHT" || wire.resendable;
268
- // A long Retry-After (an hourly or daily budget, a pause) is not worth holding a request open for.
269
- if (!passesWithTime || !safeToResend || attempt > this.#maxRetries || (retryAfter ?? 0) > this.#maxWaitSeconds)
494
+ if (!passesWithTime || !safeToResend || attempt > this.#maxRetries)
495
+ throw error;
496
+ // A long Retry-After (an hour's or a day's budget, a pause) is held open only inside maxWaitSeconds;
497
+ // past that the refusal comes back with the time the budget frees, and an event says so.
498
+ if ((retryAfter ?? 0) * 1000 > this.#maxWaitMs(wire)) {
499
+ this.#emit({
500
+ type: "deferred",
501
+ operation: wire.operation,
502
+ scope,
503
+ retryAfterSeconds: retryAfter,
504
+ freesAt: new Date(Date.now() + retryAfter * 1000).toISOString(),
505
+ message: `${wire.operation} was refused${scope ? ` by the ${scope} budget` : ""}: it can pass in ${aboutHowLong(retryAfter * 1000)}. Send it again then.`,
506
+ });
270
507
  throw error;
508
+ }
271
509
  const waitMs = ((retryAfter ?? 2 ** (attempt - 1)) + Math.random()) * 1000;
272
510
  this.#emit({ type: "retry", operation: wire.operation, attempt, waitMs, reason: code });
511
+ if (waitMs > SHORT_WAIT_MS)
512
+ this.#lands(wire, scope, waitMs);
273
513
  await sleep(waitMs, wire.signal);
274
514
  }
275
515
  }
@@ -312,8 +552,9 @@ class ZimmerStack {
312
552
  this.propertyId = propertyId;
313
553
  }
314
554
  /**
315
- * A software vendor's company key: the same client, acting on one hotel. Shares this client's pace,
316
- * so make as many as you have hotels.
555
+ * A software vendor's company key: the same client, acting on one hotel. Each hotel has its own queue
556
+ * of writes and its own pace, so one hotel's budget never holds up another's calls; what all your hotels
557
+ * share (your company's budget) is paced for all of them together. Make as many as you have hotels.
317
558
  *
318
559
  * @example
319
560
  * const { properties } = await zs.properties.list();
@@ -343,10 +584,15 @@ class ZimmerStack {
343
584
  * const sync = await zs.request("GET /sync");
344
585
  */
345
586
  async request(operation, ...rest) {
346
- const args = (rest[0] ?? {});
347
587
  const meta = generated_ts_1.OPERATIONS[operation];
348
588
  if (!meta)
349
589
  throw new errors_ts_1.ZimmerStackUsageError(`"${operation}" is not an operation of the Connect API`);
590
+ return (await this.#call(operation, meta.idempotent || exports.KEYED_WRITES.has(operation), rest[0] ?? {}));
591
+ }
592
+ /** One call of the API. `keyed`: the route keeps an idempotency key, so the write may be sent again after a lost answer. */
593
+ async #call(operation, keyed, args) {
594
+ if (args.beforeGoLive !== undefined && typeof args.beforeGoLive !== "boolean")
595
+ throw new errors_ts_1.ZimmerStackUsageError("beforeGoLive is true or false");
350
596
  const [method = "", template = ""] = operation.split(" ");
351
597
  const path = template.replace(/\{(\w+)\}/g, (_m, name) => {
352
598
  const value = args.path?.[name];
@@ -361,23 +607,39 @@ class ZimmerStack {
361
607
  const headers = { authorization: this.#core.authorization(), accept: "application/json", "user-agent": `zimmerstack-connect-node/${generated_ts_1.SDK_VERSION}` };
362
608
  // Adding a hotel and removing one name no hotel in the header: the one to add does not exist yet, and the
363
609
  // one to remove is in the path. Listing them sends the header only when this client was made for one hotel.
364
- const aboutTheList = operation === "POST /properties" || operation === "DELETE /properties/{propertyId}";
610
+ // A company webhook endpoint belongs to the partner, not to a hotel: those routes read no hotel either.
611
+ // So are your links, your bills and your support tickets; and a hotel's keys name their hotel in the path.
612
+ const aboutTheList = operation === "POST /properties" || template.startsWith("/properties/") || COMPANY_ROUTES.some((prefix) => template === prefix || template.startsWith(prefix + "/"));
365
613
  const hotel = aboutTheList ? undefined : (this.propertyId ?? (operation === "GET /properties" ? undefined : this.#core.soleSandboxId));
366
614
  if (hotel)
367
615
  headers[generated_ts_1.PROPERTY_HEADER] = String(hotel);
616
+ if (args.beforeGoLive === true)
617
+ headers[exports.BEFORE_GO_LIVE_HEADER] = "true";
368
618
  const body = args.body === undefined ? undefined : JSON.stringify(args.body);
369
619
  if (body !== undefined)
370
620
  headers["content-type"] = "application/json";
371
- if (meta.idempotent) {
621
+ if (keyed) {
372
622
  // One key per write, reused on every retry of it, so a write that timed out can never land twice.
373
623
  if (args.idempotencyKey !== undefined && !IDEMPOTENCY_SHAPE.test(args.idempotencyKey)) {
374
624
  throw new errors_ts_1.ZimmerStackUsageError("idempotencyKey must be 10 to 64 characters of A-Z a-z 0-9 _ -");
375
625
  }
376
626
  headers[generated_ts_1.IDEMPOTENCY_HEADER] = args.idempotencyKey ?? crypto.randomUUID();
377
627
  }
378
- const wire = { operation, method, url, headers, body, write: method !== "GET", resendable: method === "GET" || meta.idempotent, signal: args.signal };
628
+ const wire = {
629
+ operation,
630
+ method,
631
+ url,
632
+ headers,
633
+ body,
634
+ write: method !== "GET",
635
+ resendable: method === "GET" || keyed,
636
+ hotel: hotel ? String(hotel) : "",
637
+ cells: CELL_WRITES.has(operation) ? (0, grid_ts_1.cellsOf)(args.body?.updates ?? []) : 0,
638
+ maxWaitSeconds: args.maxWaitSeconds,
639
+ signal: args.signal,
640
+ };
379
641
  try {
380
- return (await this.#core.send(wire));
642
+ return await this.#core.send(wire);
381
643
  }
382
644
  catch (err) {
383
645
  // A company key that named no hotel. The API refused before anything ran, so sending again is safe.
@@ -395,7 +657,7 @@ class ZimmerStack {
395
657
  });
396
658
  }
397
659
  // The same request (same idempotency key) naming the hotel, on its own copy of the headers.
398
- return (await this.#core.send({ ...wire, headers: { ...headers, [generated_ts_1.PROPERTY_HEADER]: String(sole) } }));
660
+ return await this.#core.send({ ...wire, hotel: String(sole), headers: { ...headers, [generated_ts_1.PROPERTY_HEADER]: String(sole) } });
399
661
  }
400
662
  }
401
663
  /**
@@ -447,6 +709,35 @@ class ZimmerStack {
447
709
  this.#forgetWhichHotels();
448
710
  return created;
449
711
  },
712
+ /**
713
+ * Change a hotel YOU ADDED: its name, its address, or both. A company key with the scope properties:write.
714
+ *
715
+ * Send only what changes: `name`, and under `address` any of `line1`, `city`, `state` and `postalCode`. A
716
+ * field you leave out stays as it is. It never changes the hotel's country, currency, time zone, owner or
717
+ * tax id (sending one is refused with VALIDATION), and it changes the hotel's record in ZimmerStack, not
718
+ * the name of its listing on a booking site.
719
+ *
720
+ * The answer is the hotel with its `address` and `changed`: the fields whose stored value moved. An empty
721
+ * `changed` means everything you sent was already stored. A hotel whose owner let you in is refused with
722
+ * PROPERTY_NOT_CHANGEABLE: its owner changes it. With a test key it changes one of your sandboxes, whose
723
+ * name keeps its ending, "(sandbox)". Safe to retry: the call carries an idempotency key.
724
+ *
725
+ * After a new name, `zs.properties.delete` wants that new name in `confirm`.
726
+ *
727
+ * @example
728
+ * const hotel = await zs.properties.update(61, { name: "Sea Breeze Suites", address: { line1: "14 Beach Road" } });
729
+ * hotel.changed; // ["name", "address.line1"]
730
+ */
731
+ update: async (propertyId, changes, options) => {
732
+ if (!Number.isInteger(propertyId) || propertyId <= 0) {
733
+ throw new errors_ts_1.ZimmerStackUsageError("zs.properties.update needs the hotel's numeric id (zs.properties.list() names them)");
734
+ }
735
+ const sent = changes?.name !== undefined || Object.values(changes?.address ?? {}).some((value) => value !== undefined);
736
+ if (!sent) {
737
+ throw new errors_ts_1.ZimmerStackUsageError("zs.properties.update needs something to change: name, or line1, city, state or postalCode under address.");
738
+ }
739
+ return this.request("PATCH /properties/{propertyId}", { path: { propertyId }, body: changes, ...options });
740
+ },
450
741
  /**
451
742
  * Remove a hotel YOU ADDED, for good. A company key with the scope properties:write.
452
743
  *
@@ -497,6 +788,300 @@ class ZimmerStack {
497
788
  /** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
498
789
  get: (options) => this.request("GET /property", options),
499
790
  };
791
+ limits = {
792
+ /**
793
+ * Every budget this key sits under, with what is left and when it refills: the key's, its hotel's and,
794
+ * on a company key, your company's, plus the budgets over an hour and a day with this hotel's own
795
+ * figures. Any key may call it, and reading uses up nothing but one request.
796
+ *
797
+ * You do not need it to stay inside the limits: the client paces itself from every answer. Use it to
798
+ * size a job before you start it, or to show a person why something waits.
799
+ *
800
+ * @example
801
+ * const { budgets, shield } = await zs.limits.get();
802
+ * const cells = shield?.budgets.find((b) => b.scope === "cells-day");
803
+ * if (cells?.remaining != null && cells.remaining < plannedCells) console.log(`Room again in ${cells.resetSeconds} s`);
804
+ */
805
+ get: (options) => this.request("GET /limits", options),
806
+ };
807
+ /* ── what this key did: its own request log ── */
808
+ requests = {
809
+ /**
810
+ * This key's own requests of the last 7 days, newest first: when, the route's pattern, the status, the
811
+ * error code, the address it came from, how long it took and the request id. Never a body, a query or a
812
+ * guest's data. Any key may call it. A company key reads every call made with it across its hotels, or
813
+ * one hotel's through `zs.forProperty(id)`.
814
+ *
815
+ * `since` defaults to the last 24 hours. `status` is one code ("429"), a family ("4xx") or "errors"
816
+ * (400 and above). Use it to answer "did my push arrive" yourself, and to look for an address that is
817
+ * not yours: that is the first sign of a leaked key.
818
+ *
819
+ * @example
820
+ * const { items } = await zs.requests.list({ status: "errors" });
821
+ * for (const r of items) console.log(r.at, r.method, r.route, r.status, r.errorCode, r.requestId);
822
+ */
823
+ list: (query, options) => this.request("GET /requests", { query, ...options }),
824
+ /**
825
+ * The same, page by page to the last one: every request since `since`, newest first.
826
+ *
827
+ * @example
828
+ * for await (const r of zs.requests.all({ status: "errors", since: yesterday })) count[r.errorCode ?? r.status]++;
829
+ */
830
+ all: (query, options) => this.#pages((cursor) => this.requests.list({ limit: 200, ...query, cursor }, options)),
831
+ };
832
+ /* ── the hotel's ordered event log: the webhooks are the nudge, this is the truth ── */
833
+ events = {
834
+ /**
835
+ * One page of the hotel's event log: every event a webhook can carry for it (OTA bookings, website
836
+ * bookings, channel alerts, drift), once, oldest first, starting after the sequence you pass. Each item
837
+ * is the webhook's own envelope with its `sequence`, so one parser serves both.
838
+ *
839
+ * Keep `nextAfter` as your place. `more: true` means ask again at once. When `earliestSequence` is more
840
+ * than one above the `after` you sent, the events in between are older than the log keeps (90 days):
841
+ * reconcile with `zs.channelBookings.all` and `zs.directBookings.all`, then carry on. Scope
842
+ * channel-bookings:read (the channel events) or direct-bookings:read (the website's). `all` does the paging.
843
+ *
844
+ * @example
845
+ * const page = await zs.events.list({ after: lastSequence });
846
+ */
847
+ list: (query, options) => this.request("GET /events", { query, ...options }),
848
+ /**
849
+ * Every event after a sequence you saved, in order, to the end of the log. Apply each one, then save its
850
+ * `sequence`: that is your place, and the next run starts from it. A webhook only tells you there is
851
+ * something to read; nothing depends on it having arrived, or on the order deliveries arrived in.
852
+ *
853
+ * `onGap` is called once, before the first event, when the log no longer holds what follows `after`
854
+ * (events are kept 90 days): read the bookings again with `zs.channelBookings.all({ since })` and
855
+ * `zs.directBookings.all({ since })` before you go on. A first run with `after: 0` is told too.
856
+ *
857
+ * @example
858
+ * for await (const event of zs.events.all({ after: await loadPlace() })) {
859
+ * await apply(event); // dedupe on event.id if your apply is not idempotent
860
+ * await savePlace(event.sequence);
861
+ * }
862
+ */
863
+ all: (query, options) => this.#eventsAfter(query?.after ?? 0, query?.limit, options),
864
+ };
865
+ async *#eventsAfter(after, limit, options) {
866
+ if (!Number.isInteger(after) || after < 0)
867
+ throw new errors_ts_1.ZimmerStackUsageError("zs.events.all needs the last sequence you applied as its after: a whole number, 0 to read from the beginning of what is kept");
868
+ let place = after;
869
+ let first = true;
870
+ for (;;) {
871
+ const page = await this.events.list({ after: place, limit: limit ?? 100 }, { signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds });
872
+ if (first && page.earliestSequence !== null && page.earliestSequence > after + 1)
873
+ options?.onGap?.({ after, earliestSequence: page.earliestSequence });
874
+ first = false;
875
+ yield* page.items;
876
+ // nextAfter moves past events this key's scopes do not show, so an empty page can still move the place.
877
+ if (!page.more || page.nextAfter <= place)
878
+ return;
879
+ place = page.nextAfter;
880
+ }
881
+ }
882
+ /* ── your company webhook endpoints (a software partner's company key, scope webhooks:manage) ── */
883
+ webhookEndpoints = {
884
+ /** Your company webhook endpoints of this key's mode (a live key: live ones; a test key: test ones), each with its health. */
885
+ list: (options) => this.request("GET /webhook-endpoints", options),
886
+ /**
887
+ * Create a company webhook endpoint. `dataAck: true` confirms that guest booking details will be sent
888
+ * to that address. Guest contact (phone, email) is off unless `includeGuestContact` is true.
889
+ *
890
+ * THE ANSWER'S `secret` IS SHOWN ONCE: store it in your server's settings at once (never in code or a
891
+ * log). No call reads it back; `rotateSecret` makes a new one. The call carries an idempotency key, so
892
+ * a retry after a lost answer gets the same endpoint and the same secret, never a second endpoint.
893
+ *
894
+ * @example
895
+ * const { endpoint, secret } = await zs.webhookEndpoints.create({ url: "https://pms.example/zimmerstack", dataAck: true });
896
+ */
897
+ create: (body, options) => this.request("POST /webhook-endpoints", { body, ...options }),
898
+ get: (endpointId, options) => this.request("GET /webhook-endpoints/{endpointId}", { path: { endpointId }, ...options }),
899
+ /** Change an endpoint: its address, its event types, the notify email or the guest-contact switch. Send only what changes. */
900
+ update: (endpointId, body, options) => this.request("PATCH /webhook-endpoints/{endpointId}", { path: { endpointId }, body, ...options }),
901
+ /**
902
+ * Delete an endpoint for good; its deliveries and their log go with it. THERE IS NO UNDO: call it when
903
+ * a person chose to, never from a loop or a cleanup script. To stop events for a while, `pause`.
904
+ */
905
+ delete: (endpointId, options) => this.request("DELETE /webhook-endpoints/{endpointId}", { path: { endpointId }, ...options }),
906
+ /** Hold an endpoint's events (before planned downtime). Nothing is dropped: `resume` sends them, oldest first. */
907
+ pause: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/pause", { path: { endpointId }, ...options }),
908
+ /** Resume a paused endpoint. `heldEvents` says how many held events are going out now. */
909
+ resume: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/resume", { path: { endpointId }, ...options }),
910
+ /**
911
+ * A new signing secret, in this answer only. Both secrets sign every delivery until `previousExpiresAt`
912
+ * (24 hours), so switch your receiver to the new one inside that day and nothing is lost.
913
+ */
914
+ rotateSecret: (endpointId, options) => this.request("POST /webhook-endpoints/{endpointId}/rotate-secret", { path: { endpointId }, ...options }),
915
+ /**
916
+ * Send the endpoint a signed sample of any event type (`zimmerstack.ping` when none is named). The
917
+ * sample says `mode: "test"` and has no `sequence`: it is in no log. On a sandbox, make a real event
918
+ * instead with `zs.sandbox.bookings.create` and `zs.sandbox.syncEvents.create`.
919
+ *
920
+ * @example
921
+ * const { deliveryId } = await zs.webhookEndpoints.test(endpoint.id, { eventType: "channel.booking.created" });
922
+ * const delivery = await zs.webhookEndpoints.deliveries.get(endpoint.id, deliveryId); // what your receiver answered
923
+ */
924
+ test: (endpointId, body = {}, options) => this.request("POST /webhook-endpoints/{endpointId}/test", { path: { endpointId }, body, ...options }),
925
+ /**
926
+ * Queue again every subscribed event since an instant that failed or never had a delivery: at most 90
927
+ * days back and 10,000 events a run (`truncated: true` means run it again for the rest). Reading the
928
+ * log with `zs.events.all` is the other way to catch up, and needs no endpoint.
929
+ */
930
+ recover: (endpointId, since, options) => this.request("POST /webhook-endpoints/{endpointId}/recover", { path: { endpointId }, body: { since: since instanceof Date ? since.toISOString() : since }, ...options }),
931
+ deliveries: {
932
+ /** An endpoint's delivery log, newest first. Filter with status, eventType, mode (TEST: what a test made), from and to. */
933
+ list: (endpointId, query, options) => this.request("GET /webhook-endpoints/{endpointId}/deliveries", { path: { endpointId }, query, ...options }),
934
+ /** One delivery: the body as it was sent, and every attempt with what your receiver answered. */
935
+ get: (endpointId, deliveryId, options) => this.request("GET /webhook-endpoints/{endpointId}/deliveries/{deliveryId}", { path: { endpointId, deliveryId }, ...options }),
936
+ /** Send one delivery again: the same event, the same id and sequence. */
937
+ redeliver: (endpointId, deliveryId, options) => this.request("POST /webhook-endpoints/{endpointId}/deliveries/{deliveryId}/redeliver", { path: { endpointId, deliveryId }, ...options }),
938
+ },
939
+ };
940
+ /* ── one-time connect links: the hotel's own person connects a booking site (company key, scope channels:connect) ── */
941
+ connectLinks = {
942
+ /** Your connect links, newest first; `propertyId` narrows them to one hotel. */
943
+ list: (query, options) => this.request("GET /connect-links", { query, ...options }),
944
+ /**
945
+ * Make a one-time link for ONE hotel and ONE booking site. Only Airbnb is connected from the link alone
946
+ * (the host signs in on Airbnb's own page). Every other booking site must FIRST accept our connectivity
947
+ * partner for the hotel, in its extranet or through its support: send `hotelStep` to the hotel first, and
948
+ * the answer's `url` once that step is done. On ZimmerStack's hosted page the hotel's own person types
949
+ * the hotel's id at the booking site (MakeMyTrip also its access token), confirms every room and rate
950
+ * match and presses Start selling. The call takes no booking-site detail and no match. You hear
951
+ * `channel.connect.completed`, or `channel.connect.expired` if the link ran out.
952
+ *
953
+ * THE `url` IS SHOWN ONCE: it is in this answer only, and null on a replay of the same request
954
+ * (`shownOnce(answer)` returns it or says what to do). `hotelStep` is what the hotel does at the booking
955
+ * site first (null for Airbnb), for your own screen or message; it can take days. A LIVE key only: a
956
+ * sandbox has no booking site, so a test key is refused (LIVE_KEY_REQUIRED). The hotel is `propertyId`
957
+ * in the body; `forProperty` is not read.
958
+ *
959
+ * @example
960
+ * const made = await zs.connectLinks.create({ propertyId: 61, channel: "bookingcom", returnUrl: "https://pms.example/hotels/61" });
961
+ * await tellTheHotel(made.hotelStep); // first
962
+ * await sendOnceTheStepIsDone(shownOnce(made)); // then the link
963
+ */
964
+ create: (body, options) => this.request("POST /connect-links", { body, ...options }),
965
+ /** Where one link stands: pending, opened, completed, expired or revoked. Never its address again. */
966
+ get: (linkId, options) => this.request("GET /connect-links/{linkId}", { path: { linkId }, ...options }),
967
+ /** Withdraw a link. A page that is open stops at its next step. */
968
+ revoke: (linkId, options) => this.request("POST /connect-links/{linkId}/revoke", { path: { linkId }, ...options }),
969
+ };
970
+ /* ── going live: is this hotel ready for your software to be its source of truth ── */
971
+ readiness = {
972
+ /**
973
+ * Is this hotel ready for your software to be its source of truth? Four checks, each passed or not,
974
+ * with a sentence and what to do: it is on the channel manager, every room type and rate plan is
975
+ * linked, ZimmerStack's own pricing will not overwrite your prices, and nothing stale would go out
976
+ * (the record matches the channels, or you sent a price for every rate plan and night of the year
977
+ * first). Room counts are no part of it: the report only says how many room-type nights your software
978
+ * has not written yet. Any key may read it, as often as you like. A hotel you added yourself is live
979
+ * from the start (`live: true`).
980
+ *
981
+ * @example
982
+ * const report = await zs.forProperty(61).readiness.get();
983
+ * for (const check of report.checks) if (!check.passed) console.log(check.id, check.summary, check.action);
984
+ */
985
+ get: (options) => this.request("GET /readiness", options),
986
+ /**
987
+ * Make your software this hotel's source of truth: from then on every price, stay rule and room count
988
+ * you send is pushed to its booking sites, and what you sent ahead (`beforeGoLive: true`) goes out.
989
+ * Scope ari:write. Not ready is 409 NOT_READY with the checks that did not pass in `error.details`;
990
+ * that refusal is never kept under an idempotency key, so call again once they pass. Already live
991
+ * answers `replay: true`. Call it when a person decided to; only ZimmerStack support switches a hotel back.
992
+ *
993
+ * @example
994
+ * const hotel = zs.forProperty(61);
995
+ * await hotel.rates.set(aYearOfPrices, { beforeGoLive: true }); // stored, and waits
996
+ * // Room counts are not sent ahead: until go-live a count may only lower what is on sale (it goes out at once), and a higher one is refused.
997
+ * if ((await hotel.readiness.get()).ready) await hotel.readiness.goLive();
998
+ * await hotel.availability.set(aYearOfCounts); // right after going live: your room counts
999
+ */
1000
+ goLive: (options) => this.request("POST /go-live", options),
1001
+ };
1002
+ /* ── the keys you made on a hotel (company key, scope keys:manage) ── */
1003
+ hotelKeys = {
1004
+ /** The keys YOU made on a hotel you added. The hotel's own keys are its owner's and are never listed here. */
1005
+ list: (propertyId, options) => this.request("GET /properties/{propertyId}/keys", { path: { propertyId }, ...options }),
1006
+ /**
1007
+ * Mint a key on a hotel you added (or, with a test key, on one of your sandboxes): any scope a
1008
+ * hotel's own key may hold, never a company key's own.
1009
+ *
1010
+ * THE ANSWER'S `key` IS SHOWN ONCE: store it in the server's settings at once, never in code or a log.
1011
+ * It is null on a replay of the same request: `shownOnce(answer)` returns it or says to rotate.
1012
+ *
1013
+ * @example
1014
+ * const minted = await zs.hotelKeys.create(61, { name: "Night audit job", scopes: ["ari:read", "channel-bookings:read"] });
1015
+ * await vault.put(`zimmerstack/hotel-61`, shownOnce(minted));
1016
+ */
1017
+ create: (propertyId, body, options) => this.request("POST /properties/{propertyId}/keys", { path: { propertyId }, body, ...options }),
1018
+ /**
1019
+ * A new key with the same name, scopes, addresses and expiry, its secret shown once; the old key keeps
1020
+ * answering for 24 hours (`retired.retireAt`), so switch inside that day and nothing stops.
1021
+ */
1022
+ rotate: (propertyId, keyId, options) => this.request("POST /properties/{propertyId}/keys/{keyId}/rotate", { path: { propertyId, keyId }, ...options }),
1023
+ /** Revoke a key you made: it stops at once. `reason` (3 to 500 characters) is written on the key and on the hotel's activity log. */
1024
+ revoke: (propertyId, keyId, body, options) => this.request("POST /properties/{propertyId}/keys/{keyId}/revoke", { path: { propertyId, keyId }, body, ...options }),
1025
+ };
1026
+ /* ── your bills, read only (company key, scope billing:read) ── */
1027
+ billing = {
1028
+ /**
1029
+ * Your bills at a glance: what is owed, the one-time onboarding fee, your hotel quota and what opens
1030
+ * the next level, what is left of money paid ahead, the days of an unpaid invoice, and `atCost`: what
1031
+ * the channel manager charged above its included room types and rate plans for a hotel whose limit
1032
+ * ZimmerStack raised. An at-cost line is a record: `status` says RECORDED until ZimmerStack's team has
1033
+ * put it on one of your invoices (INVOICED) or waived it. Nothing here pays or changes anything.
1034
+ */
1035
+ get: (options) => this.request("GET /billing", options),
1036
+ /** Your 24 most recent issued invoices, newest first, each before and after tax with its lines, then the recent payments. */
1037
+ invoices: (options) => this.request("GET /billing/invoices", options),
1038
+ /**
1039
+ * What your next monthly invoice is made of, hotel by hotel, read today: the rooms counted, the room
1040
+ * band, the price list, the unit price. The invoice reads rooms, prices and the exchange rate again on
1041
+ * the day it is made, and that is the bill.
1042
+ */
1043
+ nextInvoice: (options) => this.request("GET /billing/next-invoice", options),
1044
+ };
1045
+ /* ── support tickets (company key, scope support:write) ── */
1046
+ supportTickets = {
1047
+ /** Your tickets of this key's mode, newest first. `status`: OPEN (waiting for ZimmerStack), ANSWERED (waiting for you), CLOSED. */
1048
+ list: (query, options) => this.request("GET /support-tickets", { query, ...options }),
1049
+ /** The same, page by page to the last one. */
1050
+ all: (query, options) => this.#pages((cursor) => this.supportTickets.list({ limit: 100, ...query, cursor }, options)),
1051
+ /**
1052
+ * Open a support ticket. `severity` follows from the hotels you name: `many_hotels` needs two or more
1053
+ * `propertyIds` or `allProperties: true`, `one_hotel` exactly one, `question` any or none. ZimmerStack
1054
+ * attaches what its own records show at that moment (`diagnostic`: ids, counts, states and times), so
1055
+ * never paste a key, a secret or a guest's details into `message`. It opens whatever your
1056
+ * integration's standing. The call carries an idempotency key: a retry never opens a second ticket.
1057
+ *
1058
+ * @example
1059
+ * const ticket = await zs.supportTickets.create({ severity: "many_hotels", subject: "Prices are not going out", message: "Since 08:10 UTC every PUT /rates is accepted and its batch stays pending.", propertyIds: [61, 62, 70] });
1060
+ * console.log(ticket.id, ticket.firstReply.target, ticket.firstReply.dueAt);
1061
+ */
1062
+ create: (body, options) => this.request("POST /support-tickets", { body, ...options }),
1063
+ /** One ticket: its thread, oldest first, and the diagnostic taken when it opened. */
1064
+ get: (ticketId, options) => this.request("GET /support-tickets/{ticketId}", { path: { ticketId }, ...options }),
1065
+ /** Write again on a ticket; it waits for ZimmerStack from then. A closed ticket takes no more messages (SUPPORT_TICKET_CLOSED): open a new one and name the old one. */
1066
+ reply: (ticketId, message, options) => this.request("POST /support-tickets/{ticketId}/messages", { path: { ticketId }, body: { message }, ...options }),
1067
+ /** Close your own ticket. */
1068
+ close: (ticketId, options) => this.request("POST /support-tickets/{ticketId}/close", { path: { ticketId }, ...options }),
1069
+ };
1070
+ /* ── is something wrong on ZimmerStack's side ── */
1071
+ status = {
1072
+ /**
1073
+ * The components (the API, bookings coming in, prices and availability going out, each booking site),
1074
+ * each operational or named in an open incident, and the incidents that touch YOUR hotels: the open
1075
+ * ones and those resolved in the last 7 days. Any key. A company key reads all its hotels', or one
1076
+ * hotel's through `zs.forProperty(id)`. An incident is opened and closed by ZimmerStack's staff:
1077
+ * `operational` means nobody has reported a problem, not that a monitor measured none.
1078
+ *
1079
+ * @example
1080
+ * const { overall, incidents } = await zs.status.get();
1081
+ * for (const incident of incidents.open) console.log(incident.title, incident.status, incident.updates[0]?.message);
1082
+ */
1083
+ get: (options) => this.request("GET /status", options),
1084
+ };
500
1085
  /* ── room types and rate plans ── */
501
1086
  catalog = {
502
1087
  /** Room types and rate plans, with the numeric ids every write uses. */
@@ -622,10 +1207,25 @@ class ZimmerStack {
622
1207
  const accepted = [];
623
1208
  for (const [i, part] of parts.entries()) {
624
1209
  const idempotencyKey = options?.idempotencyKey === undefined ? undefined : parts.length > 1 ? `${options.idempotencyKey}-${i + 1}` : options.idempotencyKey;
625
- accepted.push(await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal }));
1210
+ // The body carries no dryRun, so the answer is the accepted write, never a preview.
1211
+ const answer = await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds, beforeGoLive: options?.beforeGoLive });
1212
+ accepted.push(answer);
626
1213
  }
627
1214
  return accepted;
628
1215
  }
1216
+ /**
1217
+ * The same request with `dryRun: true`: checked and judged exactly as the write, and nothing is written.
1218
+ * One preview per request the write would be split into. No idempotency key of yours is taken: the
1219
+ * server keeps none for a dry run, so the real write may carry any key afterwards.
1220
+ */
1221
+ async #previewAll(operation, updates, options) {
1222
+ const previews = [];
1223
+ for (const part of (0, grid_ts_1.chunk)(updates)) {
1224
+ const answer = await this.request(operation, { body: { dryRun: true, updates: part }, signal: options?.signal, maxWaitSeconds: options?.maxWaitSeconds, beforeGoLive: options?.beforeGoLive });
1225
+ previews.push(previewOnly(operation, answer));
1226
+ }
1227
+ return previews;
1228
+ }
629
1229
  availability = {
630
1230
  /** Rooms left to sell per room type per night, as ZimmerStack's record holds them. Up to 500 days. */
631
1231
  get: (range, options) => this.request("GET /availability", { query: range, ...options }),
@@ -634,14 +1234,63 @@ class ZimmerStack {
634
1234
  * ZimmerStack's record (one answer per request sent; a large write is split for you).
635
1235
  */
636
1236
  set: (updates, options) => this.#writeAll("PUT /availability", updates, options),
1237
+ /**
1238
+ * What `set` WOULD do with these updates, and nothing is written, queued or sent. The answer is a
1239
+ * `WritePreview` (`dryRun: true`), never a `WriteAccepted`: `verdict` (would-write, nothing-to-write,
1240
+ * would-refuse with the refusal a real write would get now), the ranges that would change, the ones
1241
+ * already held, the ones held after a refusal, and the same `notices` the real write carries.
1242
+ *
1243
+ * It is not a free read: it spends the minute budgets like the write it previews (one request, one
1244
+ * write, the same cells), and under a test runner a live key may not send it, like any write. It
1245
+ * counts nothing against the hour and day budgets. To read the calendar use `get`.
1246
+ *
1247
+ * @example
1248
+ * const [preview] = await zs.availability.dryRun([{ roomTypeId: 412, dateFrom: "2026-12-31", dateTo: "2026-12-31", available: 0 }]);
1249
+ * if (preview?.verdict === "would-write") await zs.availability.set(updates);
1250
+ */
1251
+ dryRun: (updates, options) => this.#previewAll("PUT /availability", updates, options),
1252
+ /**
1253
+ * Close one room type on a range of nights EVERYWHERE, in one call: its room count goes to 0 and
1254
+ * stop-sell is switched on for every one of its rate plans. You do not need to know the hotel's
1255
+ * plans. The count closes every rate of the room on every booking site; the stop-sell keeps it closed
1256
+ * when a cancellation puts a room back.
1257
+ *
1258
+ * READ `notReached`: every plan that is not linked or that no booking site sells, and the one thing no
1259
+ * stop-sell reaches, a rate a booking site links on its own side (only the count closes that).
1260
+ * `batches` names the writes to watch land (`zs.batches.wait`). A close is accepted while your
1261
+ * integration is paused or out of budget (`lane: true`): a hotel must never oversell.
1262
+ *
1263
+ * @example
1264
+ * const closed = await zs.availability.close({ roomTypeId: 412, dateFrom: "2026-12-30", dateTo: "2027-01-02" });
1265
+ * for (const gap of closed.notReached) console.log(gap.what, gap.reason, gap.message);
1266
+ */
1267
+ close: async (body, options) => (await this.request("POST /availability/close", { body: realOnly("close", body), ...options })),
1268
+ /** What `close` would do, and nothing is done: the same answer with `dryRun: true` and no batches. Spends the minute budgets like the close. */
1269
+ closeDryRun: async (body, options) => previewOnly("POST /availability/close", (await this.request("POST /availability/close", { body: { ...body, dryRun: true }, ...options }))),
1270
+ /**
1271
+ * Undo exactly what `close` did on these nights, and nothing else: the stop-sell is lifted on the plans
1272
+ * the close switched on (a plan that was stop-sold before stays stopped), and each night gets back the
1273
+ * count it held before. Pass `available` to put your own count on sale instead: only your software
1274
+ * knows how many rooms are free now. A night whose count changed after the close is left as it is, and
1275
+ * a night the close had not closed is skipped (`skippedNights`). A reopen opens inventory, so it waits
1276
+ * like any other write while your integration is paused.
1277
+ *
1278
+ * @example
1279
+ * const reopened = await zs.availability.reopen({ roomTypeId: 412, dateFrom: "2026-12-30", dateTo: "2027-01-02", available: 3 });
1280
+ */
1281
+ reopen: async (body, options) => (await this.request("POST /availability/reopen", { body: realOnly("reopen", body), ...options })),
1282
+ /** What `reopen` would do, and nothing is done. */
1283
+ reopenDryRun: async (body, options) => previewOnly("POST /availability/reopen", (await this.request("POST /availability/reopen", { body: { ...body, dryRun: true }, ...options }))),
637
1284
  };
638
1285
  rates = {
639
- /** Nightly prices per rate plan, in MINOR units (`rateMinor`), before any channel's modifier. */
1286
+ /** Nightly prices per rate plan, before any channel's modifier: `rate` (a decimal string in major units, with `currency` and `decimals`) beside `rateMinor` (hundredths of the major unit, in every currency). */
640
1287
  get: (range, options) => this.request("GET /rates", { query: range, ...options }),
641
1288
  /**
642
- * Set nightly prices in MAJOR units over date ranges (4500 = ₹4,500.00). `currency` may be left
643
- * out: the hotel's own is filled in. To close a night use `restrictions.set` with stopSell,
644
- * never a zero price.
1289
+ * Set nightly prices in MAJOR units over date ranges: a number or a decimal string with the
1290
+ * currency's own decimals (4500.5 or "4500.50"). `currency` may be left out: the hotel's own is
1291
+ * filled in. What could not be kept as sent is named in the answer's `rounded` list. Never a zero
1292
+ * price to stop selling: `restrictions.set` with stopSell closes one rate plan on a night, and
1293
+ * `availability.set` with 0 rooms closes the room type on every booking site.
645
1294
  */
646
1295
  set: async (updates, options) => {
647
1296
  if (updates.length === 0)
@@ -649,6 +1298,17 @@ class ZimmerStack {
649
1298
  const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
650
1299
  return this.#writeAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
651
1300
  },
1301
+ /**
1302
+ * What `set` WOULD do with these prices, and nothing is written: a `WritePreview` per request, with what
1303
+ * would change, what is already held, what would be rounded and the notices (a plan no booking site
1304
+ * sells, an engine that will reprice). See `zs.availability.dryRun` for what it costs.
1305
+ */
1306
+ dryRun: async (updates, options) => {
1307
+ if (updates.length === 0)
1308
+ return [];
1309
+ const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
1310
+ return this.#previewAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
1311
+ },
652
1312
  /**
653
1313
  * Send the hotel's prices to its channels again, unchanged, so nights already there pick the
654
1314
  * current modifiers up. A hotel may ask a few times a day: make it a deliberate button, never
@@ -661,6 +1321,36 @@ class ZimmerStack {
661
1321
  get: (range, options) => this.request("GET /restrictions", { query: range, ...options }),
662
1322
  /** Set stay rules over date ranges: stopSell, closedToArrival, closedToDeparture, minStayArrival, minStayThrough, maxStay. */
663
1323
  set: (updates, options) => this.#writeAll("PUT /restrictions", updates, options),
1324
+ /**
1325
+ * What `set` WOULD do with these stay rules, and nothing is written. The notices are the point: a
1326
+ * stop-sell on one rate plan answers ROOM_STILL_ON_SALE when the room keeps selling through its other
1327
+ * plans. See `zs.availability.dryRun` for what it costs.
1328
+ *
1329
+ * @example
1330
+ * const [preview] = await zs.restrictions.dryRun([{ ratePlanId: 901, dateFrom: "2026-12-31", dateTo: "2026-12-31", stopSell: true }]);
1331
+ * for (const notice of noticesOf(preview)) console.log(notice.code, notice.message, notice.action);
1332
+ */
1333
+ dryRun: (updates, options) => this.#previewAll("PUT /restrictions", updates, options),
1334
+ };
1335
+ /* ── one night's whole story ── */
1336
+ explain = {
1337
+ /**
1338
+ * Explain one night of one room type (optionally one of its rate plans), from ZimmerStack's record:
1339
+ * what your software last sent, what the record holds and who set it, what the channel manager was
1340
+ * last seen holding, every send still on file and how it ended, a held value in the channel manager's
1341
+ * own words, which connections sell each plan, the rules in force, the bookings that moved the count
1342
+ * (ids and times, never a guest), and `summary`: the same in plain sentences, for a person.
1343
+ *
1344
+ * What it cannot know: it reads the channel manager's copy as last seen, never a booking site's own
1345
+ * screen. `seenAt: null` means that night was never read back; `lastSent: null` means the write is older
1346
+ * than the ones whose values are kept (`searched` says how far it looked); `channels.known: false` means
1347
+ * the hotel's connections have not been read yet. Scope ari:read; it calls no channel, so ask freely.
1348
+ *
1349
+ * @example
1350
+ * const night = await zs.explain.night({ roomTypeId: 412, date: "2026-12-31" });
1351
+ * for (const sentence of night.summary) console.log(sentence);
1352
+ */
1353
+ night: (query, options) => this.request("GET /explain", { query, ...options }),
664
1354
  };
665
1355
  /* ── has it reached the channels? ── */
666
1356
  sync = {
@@ -769,12 +1459,16 @@ class ZimmerStack {
769
1459
  cancel: (bookingId, body = {}, options) => this.request("POST /direct-bookings/{bookingId}/cancel", { path: { bookingId }, body, ...options }),
770
1460
  };
771
1461
  /** Follow a booking list's `nextCursor` to its last page. */
772
- async *#allPages(read) {
1462
+ #allPages(read) {
1463
+ return this.#pages(read);
1464
+ }
1465
+ /** Follow any list's `nextCursor` to its last page. A list that says `more: false` is at its end, whatever cursor it hands back. */
1466
+ async *#pages(read) {
773
1467
  let cursor;
774
1468
  do {
775
1469
  const page = await read(cursor);
776
1470
  yield* page.items;
777
- cursor = page.nextCursor ?? undefined;
1471
+ cursor = page.more === false ? undefined : (page.nextCursor ?? undefined);
778
1472
  } while (cursor);
779
1473
  }
780
1474
  /* ── the sandbox (zsk_test_ keys only) ── */
@@ -789,6 +1483,44 @@ class ZimmerStack {
789
1483
  create: (body, options) => this.request("POST /sandbox/bookings", { body, ...options }),
790
1484
  cancel: (bookingId, options) => this.request("POST /sandbox/bookings/{bookingId}/cancel", { path: { bookingId }, ...options }),
791
1485
  modify: (bookingId, body, options) => this.request("POST /sandbox/bookings/{bookingId}/modify", { path: { bookingId }, body, ...options }),
1486
+ /**
1487
+ * Pretend the hotel recorded that a WEBSITE booking's guest did not arrive (one made with
1488
+ * `otaName: "Website"`): the stay and its rooms go NOSHOW, the nights come back on the sandbox's
1489
+ * availability, and your endpoint receives the real `direct.booking.modified`. `{ undo: true }` takes
1490
+ * it back. The booking is not cancelled.
1491
+ */
1492
+ noShow: (bookingId, body = {}, options) => this.request("POST /sandbox/bookings/{bookingId}/no-show", { path: { bookingId }, body, ...options }),
1493
+ },
1494
+ syncEvents: {
1495
+ /**
1496
+ * Pretend a channel problem, or its end: the real `channel.sync.alert` or `channel.sync.recovered`
1497
+ * to your endpoint, and a line in the event log. `event` says which problem (rate_error when left
1498
+ * out); the problem sits on one of the sandbox's pretend channels and `zs.channels.list()` shows it
1499
+ * until a recovered clears it.
1500
+ *
1501
+ * @example
1502
+ * await zs.sandbox.syncEvents.create({ type: "channel.sync.alert", event: "disconnect_channel" });
1503
+ * await zs.sandbox.syncEvents.create({ type: "channel.sync.recovered" });
1504
+ */
1505
+ create: (body, options) => this.request("POST /sandbox/sync-events", { body, ...options }),
1506
+ },
1507
+ faults: {
1508
+ /** The fault in force on this sandbox's pretend channel; `active: false` when there is none. */
1509
+ get: (options) => this.request("GET /sandbox/faults", options),
1510
+ /**
1511
+ * Make the sandbox's pretend channel misbehave, to watch your software meet a bad day: `refuse` (the
1512
+ * next `values` nights of prices or stay rules are refused, with your `message` as the channel
1513
+ * manager's words), `throttle` ("too many requests" for `minutes`) or `outage` (no answer for
1514
+ * `minutes`). One fault at a time: a new one replaces it. Prices and stay rules only: room counts land
1515
+ * as before. The answer's `watch` says what to do next and what you should then see, step by step.
1516
+ *
1517
+ * @example
1518
+ * const fault = await zs.sandbox.faults.set({ kind: "refuse", values: 2, message: "Rate is below the channel's minimum" });
1519
+ * for (const step of fault.watch) console.log(step);
1520
+ */
1521
+ set: (body, options) => this.request("POST /sandbox/faults", { body, ...options }),
1522
+ /** End the fault: the pretend channel answers normally from the next push. Values already held stay held until a different value is sent. */
1523
+ clear: (options) => this.request("DELETE /sandbox/faults", options),
792
1524
  },
793
1525
  };
794
1526
  /* ── the rate grid ── */