@zimmerstack/connect 0.0.0-stage → 0.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.
@@ -0,0 +1,612 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ZimmerStack = void 0;
4
+ const errors_ts_1 = require("./errors.js");
5
+ const generated_ts_1 = require("./generated.js");
6
+ const grid_ts_1 = require("./grid.js");
7
+ /* ───────────────────────────── the shared core ───────────────────────────── */
8
+ /** Requests in flight at once. Writes go one at a time on top of that. */
9
+ const PARALLEL = 4;
10
+ const KEY_SHAPE = /^zsk_(live|test)_[A-Za-z0-9_-]{16,}$/;
11
+ const IDEMPOTENCY_SHAPE = /^[A-Za-z0-9_-]{10,64}$/;
12
+ /** After one of these the key will never work again: every later call is refused here, not sent. */
13
+ const KEY_IS_DEAD = new Set(["API_KEY_INVALID", "API_KEY_REVOKED", "API_KEY_EXPIRED"]);
14
+ const CATALOG_TTL_MS = 10 * 60_000;
15
+ function sleep(ms, signal) {
16
+ return new Promise((resolve, reject) => {
17
+ if (signal?.aborted)
18
+ return reject(signal.reason);
19
+ const timer = setTimeout(() => {
20
+ signal?.removeEventListener("abort", onAbort);
21
+ resolve();
22
+ }, ms);
23
+ const onAbort = () => {
24
+ clearTimeout(timer);
25
+ reject(signal?.reason);
26
+ };
27
+ signal?.addEventListener("abort", onAbort, { once: true });
28
+ });
29
+ }
30
+ function env(name) {
31
+ return typeof process !== "undefined" && process.env ? process.env[name] : undefined;
32
+ }
33
+ function underTestRunner() {
34
+ return env("NODE_ENV") === "test" || Boolean(env("VITEST") || env("JEST_WORKER_ID") || env("NODE_TEST_CONTEXT"));
35
+ }
36
+ function resolveBase(baseUrl) {
37
+ if (!baseUrl)
38
+ return generated_ts_1.API_ORIGIN;
39
+ let url;
40
+ try {
41
+ url = new URL(baseUrl);
42
+ }
43
+ catch {
44
+ throw new errors_ts_1.ZimmerStackUsageError("baseUrl is not a URL");
45
+ }
46
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1" || url.hostname === "[::1]";
47
+ if (url.origin !== generated_ts_1.API_ORIGIN && !local) {
48
+ throw new errors_ts_1.ZimmerStackUsageError(`baseUrl may only be ${generated_ts_1.API_ORIGIN} or a local stand-in (http://localhost:…): the key is sent to no other host`);
49
+ }
50
+ return url.origin;
51
+ }
52
+ class Core {
53
+ #key;
54
+ mode;
55
+ base;
56
+ #fetch;
57
+ #timeoutMs;
58
+ #maxRetries;
59
+ #maxWaitSeconds;
60
+ #allowLiveWritesInTests;
61
+ #onEvent;
62
+ #resumeAll = 0;
63
+ #resumeWrites = 0;
64
+ #active = 0;
65
+ #queue = [];
66
+ #writeTail = Promise.resolve();
67
+ #dead;
68
+ catalogs = new Map();
69
+ /** A sandbox company key's one hotel, found once when a call asked for a hotel and none was named. */
70
+ soleSandboxProperty;
71
+ /** The same, once known: sent with every later call that names no hotel, so the refusal is met once. */
72
+ soleSandboxId;
73
+ constructor(options) {
74
+ const g = globalThis;
75
+ if ((typeof g.window !== "undefined" && typeof g.window.document !== "undefined") || g.navigator?.product === "ReactNative") {
76
+ 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.");
77
+ }
78
+ const key = options.apiKey ?? env("ZIMMERSTACK_CONNECT_KEY");
79
+ if (!key)
80
+ throw new errors_ts_1.ZimmerStackUsageError("No API key: set the environment variable ZIMMERSTACK_CONNECT_KEY (zsk_test_… while you build) on your server");
81
+ const shape = KEY_SHAPE.exec(key.trim());
82
+ if (!shape)
83
+ 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.");
84
+ this.#key = key.trim();
85
+ this.mode = shape[1];
86
+ this.base = resolveBase(options.baseUrl);
87
+ const f = options.fetch ?? globalThis.fetch;
88
+ if (typeof f !== "function")
89
+ throw new errors_ts_1.ZimmerStackUsageError("No fetch in this runtime: @zimmerstack/connect needs Node 20 or newer");
90
+ this.#fetch = f;
91
+ this.#timeoutMs = options.timeoutMs ?? 30_000;
92
+ this.#maxRetries = Math.min(5, Math.max(0, Math.trunc(options.maxRetries ?? 3)));
93
+ this.#maxWaitSeconds = options.maxWaitSeconds ?? 120;
94
+ this.#allowLiveWritesInTests = options.allowLiveWritesInTests === true;
95
+ this.#onEvent = options.onEvent;
96
+ }
97
+ authorization() {
98
+ return "Bearer " + this.#key;
99
+ }
100
+ #emit(event) {
101
+ try {
102
+ this.#onEvent?.(event);
103
+ }
104
+ catch {
105
+ /* a logger must never break a request */
106
+ }
107
+ }
108
+ send(wire) {
109
+ if (this.#dead) {
110
+ const d = this.#dead;
111
+ return Promise.reject(new errors_ts_1.ZimmerStackError({
112
+ status: d.status,
113
+ code: d.code,
114
+ message: `${d.message} (this key was refused earlier, so ${wire.operation} was not sent; start again with a working key)`,
115
+ operation: wire.operation,
116
+ retryable: false,
117
+ }));
118
+ }
119
+ if (wire.write && this.mode === "live" && !this.#allowLiveWritesInTests && underTestRunner()) {
120
+ return Promise.reject(new errors_ts_1.ZimmerStackError({
121
+ status: 0,
122
+ code: "LIVE_KEY_IN_TEST",
123
+ message: `${wire.operation} was not sent: this is a live key (zsk_live_) under a test runner, and a test must not change a real hotel. Use a zsk_test_ sandbox key or a fake fetch.`,
124
+ operation: wire.operation,
125
+ retryable: false,
126
+ }));
127
+ }
128
+ if (!wire.write)
129
+ return this.#attempts(wire);
130
+ // Writes go one after another: a burst spends the write budget at once, and two writes to one
131
+ // night must reach the record in the order they were made.
132
+ const run = () => this.#attempts(wire);
133
+ const result = this.#writeTail.then(run, run);
134
+ this.#writeTail = result.catch(() => undefined);
135
+ return result;
136
+ }
137
+ #slot() {
138
+ const take = () => {
139
+ this.#active++;
140
+ let released = false;
141
+ return () => {
142
+ if (released)
143
+ return;
144
+ released = true;
145
+ this.#active--;
146
+ this.#queue.shift()?.();
147
+ };
148
+ };
149
+ if (this.#active < PARALLEL)
150
+ return Promise.resolve(take());
151
+ return new Promise((resolve) => this.#queue.push(() => resolve(take())));
152
+ }
153
+ /** Wait until the budgets the last answers reported have room again, instead of earning a 429. */
154
+ async #pace(wire) {
155
+ for (;;) {
156
+ const wait = Math.max(this.#resumeAll, wire.write ? this.#resumeWrites : 0) - Date.now();
157
+ if (wait <= 0)
158
+ return;
159
+ this.#emit({ type: "pace", operation: wire.operation, waitMs: wait });
160
+ await sleep(wait, wire.signal);
161
+ }
162
+ }
163
+ /** RateLimit: "key";r=117;t=42, "key-writes";r=29;t=42 (r = requests left, t = seconds until the window has room). */
164
+ #notePace(res) {
165
+ for (const part of (res.headers.get("ratelimit") ?? "").split(",")) {
166
+ const left = /;\s*r=(\d+)/.exec(part);
167
+ const refill = /;\s*t=(\d+)/.exec(part);
168
+ if (!left || !refill || Number(left[1]) > PARALLEL)
169
+ continue;
170
+ const at = Date.now() + Math.min(Number(refill[1]), 65) * 1000;
171
+ if (/"[^"]*(writes|bookings|cells)[^"]*"/.test(part))
172
+ this.#resumeWrites = Math.max(this.#resumeWrites, at);
173
+ else
174
+ this.#resumeAll = Math.max(this.#resumeAll, at);
175
+ }
176
+ }
177
+ async #attempts(wire) {
178
+ for (let attempt = 1;; attempt++) {
179
+ await this.#pace(wire);
180
+ const release = await this.#slot();
181
+ const started = Date.now();
182
+ let res;
183
+ let json;
184
+ try {
185
+ const timeout = AbortSignal.timeout(this.#timeoutMs);
186
+ res = await this.#fetch(wire.url, {
187
+ method: wire.method,
188
+ headers: wire.headers,
189
+ body: wire.body,
190
+ // The API never redirects, and the key must not follow one to another address.
191
+ redirect: "manual",
192
+ signal: wire.signal ? AbortSignal.any([timeout, wire.signal]) : timeout,
193
+ });
194
+ json = (await res.json().catch(() => null));
195
+ }
196
+ catch (cause) {
197
+ release();
198
+ if (wire.signal?.aborted)
199
+ throw cause;
200
+ const timedOut = cause?.name === "TimeoutError";
201
+ if (!wire.resendable || attempt > this.#maxRetries) {
202
+ throw new errors_ts_1.ZimmerStackError({
203
+ status: 0,
204
+ code: timedOut ? "TIMEOUT" : "NETWORK_ERROR",
205
+ message: wire.resendable
206
+ ? `${wire.operation} could not reach ZimmerStack after ${attempt} attempts`
207
+ : `${wire.operation} could not reach ZimmerStack, and it is not safe to send again without knowing whether it was applied: read the current state before you retry`,
208
+ operation: wire.operation,
209
+ retryable: wire.resendable,
210
+ cause,
211
+ });
212
+ }
213
+ const waitMs = (2 ** (attempt - 1) + Math.random()) * 1000;
214
+ this.#emit({ type: "retry", operation: wire.operation, attempt, waitMs, reason: timedOut ? "TIMEOUT" : "NETWORK_ERROR" });
215
+ await sleep(waitMs, wire.signal);
216
+ continue;
217
+ }
218
+ release();
219
+ this.#notePace(res);
220
+ this.#emit({ type: "response", operation: wire.operation, status: res.status, attempt, ms: Date.now() - started });
221
+ if (res.ok)
222
+ return json && typeof json === "object" ? json.data : undefined;
223
+ const data = (json && typeof json.data === "object" && json.data !== null ? json.data : {});
224
+ const code = typeof data.code === "string" ? data.code : `HTTP_${res.status}`;
225
+ const headerSeconds = Number(res.headers.get("retry-after"));
226
+ const retryAfter = Number.isFinite(headerSeconds) && headerSeconds > 0 ? headerSeconds : typeof data.retryAfterSeconds === "number" ? data.retryAfterSeconds : undefined;
227
+ // What passes with time: a used-up budget, a fault on ZimmerStack's side, a duplicate of a request
228
+ // still running. Every other answer is a verdict on the request itself.
229
+ const passesWithTime = res.status === 429 || res.status >= 500 || code === "IDEMPOTENCY_IN_FLIGHT";
230
+ const error = new errors_ts_1.ZimmerStackError({
231
+ status: res.status,
232
+ code,
233
+ message: typeof json?.message === "string" && json.message ? json.message : `${wire.operation} answered ${res.status}`,
234
+ operation: wire.operation,
235
+ details: data.details,
236
+ scope: typeof data.scope === "string" ? data.scope : undefined,
237
+ retryAfterSeconds: retryAfter,
238
+ retryable: passesWithTime,
239
+ });
240
+ if (KEY_IS_DEAD.has(code)) {
241
+ this.#dead = error;
242
+ throw error;
243
+ }
244
+ // A 429 was refused before anything ran, so sending it again is always safe. A 5xx may have run.
245
+ const safeToResend = res.status === 429 || code === "IDEMPOTENCY_IN_FLIGHT" || wire.resendable;
246
+ // A long Retry-After (an hourly or daily budget, a pause) is not worth holding a request open for.
247
+ if (!passesWithTime || !safeToResend || attempt > this.#maxRetries || (retryAfter ?? 0) > this.#maxWaitSeconds)
248
+ throw error;
249
+ const waitMs = ((retryAfter ?? 2 ** (attempt - 1)) + Math.random()) * 1000;
250
+ this.#emit({ type: "retry", operation: wire.operation, attempt, waitMs, reason: code });
251
+ await sleep(waitMs, wire.signal);
252
+ }
253
+ }
254
+ }
255
+ /** How `forProperty` hands its core to the view it creates, without a public constructor argument. */
256
+ let handoff;
257
+ /* ───────────────────────────── the client ───────────────────────────── */
258
+ /**
259
+ * The ZimmerStack Connect API, from your server.
260
+ *
261
+ * @example
262
+ * import { ZimmerStack } from "@zimmerstack/connect";
263
+ *
264
+ * const zs = new ZimmerStack(); // reads ZIMMERSTACK_CONNECT_KEY
265
+ * const grid = await zs.grid.load("2026-12-01", "2026-12-14");
266
+ * await zs.grid.save({ rates: [{ ratePlanId: 901, date: "2026-12-24", rate: 5200 }] });
267
+ *
268
+ * Make one per process and reuse it: the pace it keeps is per instance.
269
+ */
270
+ class ZimmerStack {
271
+ #core;
272
+ /** "test" on a sandbox key: nothing you send reaches a channel. */
273
+ mode;
274
+ /** The hotel a company key acts on through this instance. */
275
+ propertyId;
276
+ constructor(options = {}) {
277
+ const shared = handoff;
278
+ handoff = undefined;
279
+ this.#core = shared ?? new Core(options);
280
+ this.mode = this.#core.mode;
281
+ // A company key's hotel: the option, else (for a client made from the environment) ZIMMERSTACK_PROPERTY_ID.
282
+ const fromEnv = shared ? undefined : env("ZIMMERSTACK_PROPERTY_ID")?.trim();
283
+ if (fromEnv && !/^[1-9]\d*$/.test(fromEnv)) {
284
+ throw new errors_ts_1.ZimmerStackUsageError("ZIMMERSTACK_PROPERTY_ID must be a property's numeric id (zs.properties.list() names them)");
285
+ }
286
+ const propertyId = options.propertyId ?? (fromEnv ? Number(fromEnv) : undefined);
287
+ if (propertyId !== undefined && (!Number.isInteger(propertyId) || propertyId <= 0)) {
288
+ throw new errors_ts_1.ZimmerStackUsageError("propertyId must be a property's numeric id (zs.properties.list() names them)");
289
+ }
290
+ this.propertyId = propertyId;
291
+ }
292
+ /**
293
+ * A software vendor's company key: the same client, acting on one hotel. Shares this client's pace,
294
+ * so make as many as you have hotels.
295
+ *
296
+ * @example
297
+ * const { properties } = await zs.properties.list();
298
+ * for (const p of properties) await zs.forProperty(p.id).sync.get();
299
+ */
300
+ forProperty(propertyId) {
301
+ handoff = this.#core;
302
+ try {
303
+ return new ZimmerStack({ propertyId });
304
+ }
305
+ finally {
306
+ handoff = undefined;
307
+ }
308
+ }
309
+ /** Never prints the key. */
310
+ toJSON() {
311
+ return { mode: this.mode, propertyId: this.propertyId };
312
+ }
313
+ [Symbol.for("nodejs.util.inspect.custom")]() {
314
+ return `ZimmerStack { mode: '${this.mode}'${this.propertyId ? `, propertyId: ${this.propertyId}` : ""} }`;
315
+ }
316
+ /**
317
+ * Any operation of the contract by its name, typed. The methods below are this with friendlier names;
318
+ * use it for an operation they do not cover.
319
+ *
320
+ * @example
321
+ * const sync = await zs.request("GET /sync");
322
+ */
323
+ async request(operation, ...rest) {
324
+ const args = (rest[0] ?? {});
325
+ const meta = generated_ts_1.OPERATIONS[operation];
326
+ if (!meta)
327
+ throw new errors_ts_1.ZimmerStackUsageError(`"${operation}" is not an operation of the Connect API`);
328
+ const [method = "", template = ""] = operation.split(" ");
329
+ const path = template.replace(/\{(\w+)\}/g, (_m, name) => {
330
+ const value = args.path?.[name];
331
+ if (value === undefined || value === null || String(value) === "")
332
+ throw new errors_ts_1.ZimmerStackUsageError(`${operation} needs ${name}`);
333
+ return encodeURIComponent(String(value));
334
+ });
335
+ const url = new URL(this.#core.base + generated_ts_1.API_PREFIX + path);
336
+ for (const [name, value] of Object.entries(args.query ?? {}))
337
+ if (value !== undefined && value !== null)
338
+ url.searchParams.set(name, String(value));
339
+ const headers = { authorization: this.#core.authorization(), accept: "application/json", "user-agent": `zimmerstack-connect-node/${generated_ts_1.SDK_VERSION}` };
340
+ const hotel = this.propertyId ?? (operation === "GET /properties" ? undefined : this.#core.soleSandboxId);
341
+ if (hotel)
342
+ headers[generated_ts_1.PROPERTY_HEADER] = String(hotel);
343
+ const body = args.body === undefined ? undefined : JSON.stringify(args.body);
344
+ if (body !== undefined)
345
+ headers["content-type"] = "application/json";
346
+ if (meta.idempotent) {
347
+ // One key per write, reused on every retry of it, so a write that timed out can never land twice.
348
+ if (args.idempotencyKey !== undefined && !IDEMPOTENCY_SHAPE.test(args.idempotencyKey)) {
349
+ throw new errors_ts_1.ZimmerStackUsageError("idempotencyKey must be 10 to 64 characters of A-Z a-z 0-9 _ -");
350
+ }
351
+ headers[generated_ts_1.IDEMPOTENCY_HEADER] = args.idempotencyKey ?? crypto.randomUUID();
352
+ }
353
+ const wire = { operation, method, url, headers, body, write: method !== "GET", resendable: method === "GET" || meta.idempotent, signal: args.signal };
354
+ try {
355
+ return (await this.#core.send(wire));
356
+ }
357
+ catch (err) {
358
+ // A company key that named no hotel. The API refused before anything ran, so sending again is safe.
359
+ if (!(err instanceof errors_ts_1.ZimmerStackError) || err.code !== "PROPERTY_REQUIRED" || this.propertyId !== undefined)
360
+ throw err;
361
+ const sole = await this.#soleSandboxProperty(args.signal);
362
+ if (sole === undefined) {
363
+ throw new errors_ts_1.ZimmerStackError({
364
+ status: err.status,
365
+ code: err.code,
366
+ message: "This is a company key: say which hotel each call acts on. Use zs.forProperty(id), new ZimmerStack({ propertyId }) or the environment variable ZIMMERSTACK_PROPERTY_ID; zs.properties.list() names the hotels this key reaches.",
367
+ operation,
368
+ details: err.details,
369
+ retryable: false,
370
+ });
371
+ }
372
+ // The same request (same idempotency key) naming the hotel, on its own copy of the headers.
373
+ return (await this.#core.send({ ...wire, headers: { ...headers, [generated_ts_1.PROPERTY_HEADER]: String(sole) } }));
374
+ }
375
+ }
376
+ /**
377
+ * The one hotel a SANDBOX company key reaches (its sandbox), so the first call of a new integration works
378
+ * without naming it. A live key never guesses: a hotel it acts on is always named.
379
+ */
380
+ #soleSandboxProperty(signal) {
381
+ if (this.mode !== "test")
382
+ return Promise.resolve(undefined);
383
+ this.#core.soleSandboxProperty ??= this.request("GET /properties", { signal })
384
+ .then((list) => {
385
+ const only = list.keyKind === "company" && list.properties.length === 1 && list.properties[0].sandbox ? list.properties[0].id : undefined;
386
+ this.#core.soleSandboxId = only;
387
+ return only;
388
+ })
389
+ .catch(() => {
390
+ this.#core.soleSandboxProperty = undefined; // a failed lookup is asked again next time
391
+ return undefined;
392
+ });
393
+ return this.#core.soleSandboxProperty;
394
+ }
395
+ /* ── which hotel ── */
396
+ properties = {
397
+ /** The hotels this key may act on. A company key names one of them on every other call (`forProperty`). */
398
+ list: (options) => this.request("GET /properties", options),
399
+ };
400
+ property = {
401
+ /** The hotel: its timezone and currency, what this key may do, its own limits, what it has used, where it stands. */
402
+ get: (options) => this.request("GET /property", options),
403
+ };
404
+ /* ── room types and rate plans ── */
405
+ catalog = {
406
+ /** Room types and rate plans, with the numeric ids every write uses. */
407
+ get: async (options) => {
408
+ const value = await this.request("GET /catalog", options);
409
+ this.#core.catalogs.set(this.propertyId ?? 0, { at: Date.now(), value });
410
+ return value;
411
+ },
412
+ /** Create or change room types by your own `ref`. Needs the scope catalog:write. */
413
+ upsertRoomTypes: (body, options) => this.#structure("PUT /catalog/room-types", { body, ...options }),
414
+ /** Delete a room type; its rate plans go with it. */
415
+ deleteRoomType: (roomTypeId, options) => this.#structure("DELETE /catalog/room-types/{roomTypeId}", { path: { roomTypeId }, ...options }),
416
+ /** Create or change rate plans by your own `ref`. */
417
+ upsertRatePlans: (body, options) => this.#structure("PUT /catalog/rate-plans", { body, ...options }),
418
+ deleteRatePlan: (ratePlanId, options) => this.#structure("DELETE /catalog/rate-plans/{ratePlanId}", { path: { ratePlanId }, ...options }),
419
+ };
420
+ async #structure(operation, args) {
421
+ try {
422
+ return await this.request(operation, ...[args]);
423
+ }
424
+ finally {
425
+ this.#core.catalogs.delete(this.propertyId ?? 0); // whatever happened, the catalog may have changed
426
+ }
427
+ }
428
+ /** The catalog, kept ten minutes: it changes when someone adds a room type or a plan, not while a grid is open. */
429
+ async #cachedCatalog(signal) {
430
+ const hit = this.#core.catalogs.get(this.propertyId ?? 0);
431
+ if (hit && Date.now() - hit.at < CATALOG_TTL_MS)
432
+ return hit.value;
433
+ return this.catalog.get({ signal });
434
+ }
435
+ /* ── availability, rates, stay rules ── */
436
+ /** One request per 1,000 updates / 5,000 cells, one after another. */
437
+ async #writeAll(operation, updates, options) {
438
+ if (updates.length === 0)
439
+ return [];
440
+ const parts = (0, grid_ts_1.chunk)(updates);
441
+ if (options?.idempotencyKey !== undefined && parts.length > 1 && options.idempotencyKey.length > 60) {
442
+ throw new errors_ts_1.ZimmerStackUsageError("This write is split into several requests; give an idempotencyKey of at most 60 characters so each part can carry its own");
443
+ }
444
+ const accepted = [];
445
+ for (const [i, part] of parts.entries()) {
446
+ const idempotencyKey = options?.idempotencyKey === undefined ? undefined : parts.length > 1 ? `${options.idempotencyKey}-${i + 1}` : options.idempotencyKey;
447
+ accepted.push(await this.request(operation, { body: { updates: part }, idempotencyKey, signal: options?.signal }));
448
+ }
449
+ return accepted;
450
+ }
451
+ availability = {
452
+ /** Rooms left to sell per room type per night, as ZimmerStack's record holds them. Up to 500 days. */
453
+ get: (range, options) => this.request("GET /availability", { query: range, ...options }),
454
+ /**
455
+ * Set rooms left to sell: absolute numbers over date ranges. Answers when the values are in
456
+ * ZimmerStack's record (one answer per request sent; a large write is split for you).
457
+ */
458
+ set: (updates, options) => this.#writeAll("PUT /availability", updates, options),
459
+ };
460
+ rates = {
461
+ /** Nightly prices per rate plan, in MINOR units (`rateMinor`), before any channel's modifier. */
462
+ get: (range, options) => this.request("GET /rates", { query: range, ...options }),
463
+ /**
464
+ * Set nightly prices in MAJOR units over date ranges (4500 = ₹4,500.00). `currency` may be left
465
+ * out: the hotel's own is filled in. To close a night use `restrictions.set` with stopSell,
466
+ * never a zero price.
467
+ */
468
+ set: async (updates, options) => {
469
+ if (updates.length === 0)
470
+ return [];
471
+ const currency = updates.every((u) => u.currency) ? "" : (await this.#cachedCatalog(options?.signal)).currency;
472
+ return this.#writeAll("PUT /rates", updates.map((u) => ({ ...u, currency: u.currency ?? currency })), options);
473
+ },
474
+ /**
475
+ * Send the hotel's prices to its channels again, unchanged, so nights already there pick the
476
+ * current modifiers up. A hotel may ask a few times a day: make it a deliberate button, never
477
+ * automatic. Watch `rates.dirtyCells` on `sync.get()` fall to 0.
478
+ */
479
+ resend: (options) => this.request("POST /rates/resend", options),
480
+ };
481
+ restrictions = {
482
+ /** The stay rules per rate plan per night; null = no rule set for that field. */
483
+ get: (range, options) => this.request("GET /restrictions", { query: range, ...options }),
484
+ /** Set stay rules over date ranges: stopSell, closedToArrival, closedToDeparture, minStayArrival, minStayThrough, maxStay. */
485
+ set: (updates, options) => this.#writeAll("PUT /restrictions", updates, options),
486
+ };
487
+ /* ── has it reached the channels? ── */
488
+ sync = {
489
+ /** How far what you sent has travelled: cells still on their way, the last error, where the integration stands. */
490
+ get: (options) => this.request("GET /sync", options),
491
+ };
492
+ batches = {
493
+ /** One write, by the `batchId` its answer carried. */
494
+ get: (batchId, options) => this.request("GET /batches/{batchId}", { path: { batchId }, ...options }),
495
+ /**
496
+ * Wait for a write to reach the channels, asking no more often than every 15 seconds, for at most
497
+ * five minutes. Returns the last status: if it is still "pending", say "still syncing" and let the
498
+ * person look again later. Availability lands in seconds; a full calendar of prices takes minutes.
499
+ */
500
+ wait: async (batchId, options = {}) => {
501
+ const interval = Math.max(15_000, options.intervalMs ?? 15_000);
502
+ const deadline = Date.now() + (options.timeoutMs ?? 5 * 60_000);
503
+ for (;;) {
504
+ const batch = await this.batches.get(batchId, { signal: options.signal });
505
+ if (batch.status !== "pending" || Date.now() + interval > deadline)
506
+ return batch;
507
+ await sleep(interval, options.signal);
508
+ }
509
+ },
510
+ };
511
+ /* ── channels and what each is sent ── */
512
+ channels = {
513
+ /**
514
+ * The connected channels (Booking.com, MakeMyTrip, …), each with the price modifier it holds:
515
+ * `[]` = prices go as they are; `null` = a rule set by hand that this API cannot express.
516
+ */
517
+ list: (options) => this.request("GET /channels", options),
518
+ /**
519
+ * Replace a channel's modifier with these steps (`[]` removes it). Needs the scope
520
+ * channel-modifiers:write.
521
+ *
522
+ * ONE CALL MOVES EVERY PRICE SENT TO THAT CHANNEL FROM THEN ON. Call it when a person saved the
523
+ * setting; never from a loop, a timer or a test against a live key. Prices already on the channel
524
+ * stay as they are until those nights are sent again (`rates.resend`).
525
+ */
526
+ setModifier: (channelId, steps, options) => this.request("PUT /channels/{channelId}/modifier", { path: { channelId }, body: { steps }, ...options }),
527
+ };
528
+ /* ── bookings from your own booking engine ── */
529
+ bookings = {
530
+ /** Bookings this integration created, newest first. */
531
+ list: (query, options) => this.request("GET /bookings", { query, ...options }),
532
+ /**
533
+ * Create a booking in the hotel's PMS. Always send `externalReference` (your own reservation id):
534
+ * the same value returns the same booking, which makes every retry safe.
535
+ */
536
+ create: (body, options) => this.request("POST /bookings", { body, ...options }),
537
+ get: (bookingId, options) => this.request("GET /bookings/{bookingId}", { path: { bookingId }, ...options }),
538
+ /** Cancel a booking this integration created; its nights open again on the channels. */
539
+ cancel: (bookingId, body = {}, options) => this.request("POST /bookings/{bookingId}/cancel", { path: { bookingId }, body, ...options }),
540
+ };
541
+ /* ── bookings the OTAs sent ── */
542
+ channelBookings = {
543
+ /** OTA bookings the channel manager delivered, in the webhook's shape. Follow `nextCursor`, or use `all`. */
544
+ list: (query, options) => this.request("GET /channel-bookings", { query, ...options }),
545
+ get: (bookingId, options) => this.request("GET /channel-bookings/{bookingId}", { path: { bookingId }, ...options }),
546
+ /**
547
+ * Every OTA booking changed since `since`, page by page, for reconciling what your webhook missed.
548
+ *
549
+ * @example
550
+ * for await (const booking of zs.channelBookings.all({ since: lastSeen })) save(booking);
551
+ */
552
+ all: (query, options) => this.#allChannelBookings(query, options),
553
+ };
554
+ async *#allChannelBookings(query, options) {
555
+ let cursor;
556
+ do {
557
+ const page = await this.channelBookings.list({ limit: 100, ...query, cursor }, options);
558
+ yield* page.items;
559
+ cursor = page.nextCursor ?? undefined;
560
+ } while (cursor);
561
+ }
562
+ /* ── the sandbox (zsk_test_ keys only) ── */
563
+ sandbox = {
564
+ bookings: {
565
+ list: (options) => this.request("GET /sandbox/bookings", options),
566
+ /** Pretend an OTA booked: the booking, the availability moved down, and the real webhook to your endpoint. */
567
+ create: (body, options) => this.request("POST /sandbox/bookings", { body, ...options }),
568
+ cancel: (bookingId, options) => this.request("POST /sandbox/bookings/{bookingId}/cancel", { path: { bookingId }, ...options }),
569
+ modify: (bookingId, body, options) => this.request("POST /sandbox/bookings/{bookingId}/modify", { path: { bookingId }, body, ...options }),
570
+ },
571
+ };
572
+ /* ── the rate grid ── */
573
+ grid = {
574
+ /**
575
+ * The whole grid for a window, ready for a screen: rows are room types with their rate plans,
576
+ * columns are nights. Three reads (four the first time). A window may span 500 days; a screen
577
+ * needs 14 to 60.
578
+ */
579
+ load: async (from, to, options) => {
580
+ const query = { from, to };
581
+ const [catalog, availability, rates, restrictions] = await Promise.all([
582
+ this.#cachedCatalog(options?.signal),
583
+ this.availability.get(query, options),
584
+ this.rates.get(query, options),
585
+ this.restrictions.get(query, options),
586
+ ]);
587
+ return (0, grid_ts_1.buildGrid)({ from, to, catalog, availability, rates, restrictions });
588
+ },
589
+ /**
590
+ * Save what a person changed: single nights in, the fewest ranges out, one request per resource,
591
+ * one after another. Each answer carries a `batchId`: the values are in ZimmerStack's record and
592
+ * on their way to the channels.
593
+ */
594
+ save: async (edits, options) => {
595
+ const accepted = [];
596
+ if (edits.availability?.length) {
597
+ const ranges = (0, grid_ts_1.toRanges)(edits.availability.map((e) => ({ id: e.roomTypeId, date: e.date, value: e.available })));
598
+ accepted.push(...(await this.availability.set(ranges.map((r) => ({ roomTypeId: r.id, dateFrom: r.dateFrom, dateTo: r.dateTo, available: r.value })), options)));
599
+ }
600
+ if (edits.rates?.length) {
601
+ const ranges = (0, grid_ts_1.toRanges)(edits.rates.map((e) => ({ id: e.ratePlanId, date: e.date, value: e.rate })));
602
+ accepted.push(...(await this.rates.set(ranges.map((r) => ({ ratePlanId: r.id, dateFrom: r.dateFrom, dateTo: r.dateTo, rate: r.value })), options)));
603
+ }
604
+ if (edits.restrictions?.length) {
605
+ const ranges = (0, grid_ts_1.toRanges)(edits.restrictions.map(({ ratePlanId, date, ...rules }) => ({ id: ratePlanId, date, value: rules })));
606
+ accepted.push(...(await this.restrictions.set(ranges.map((r) => ({ ratePlanId: r.id, dateFrom: r.dateFrom, dateTo: r.dateTo, ...r.value })), options)));
607
+ }
608
+ return accepted;
609
+ },
610
+ };
611
+ }
612
+ exports.ZimmerStack = ZimmerStack;
@@ -0,0 +1,46 @@
1
+ import type { ErrorCode } from "./generated.js";
2
+ /**
3
+ * What the API answered when it refused a request, or what stopped a request before it was sent.
4
+ *
5
+ * Branch on `code`: it is stable. `message` is written for a person (show it to them) and may change.
6
+ */
7
+ export declare class ZimmerStackError extends Error {
8
+ /** The HTTP status; 0 when the request never reached the API (see `code`). */
9
+ readonly status: number;
10
+ /**
11
+ * The API's stable code (RATE_LIMITED, RATE_OUT_OF_BAND, SCOPE_MISSING, …), or one of this client's own:
12
+ * LIVE_KEY_IN_TEST, NETWORK_ERROR, TIMEOUT.
13
+ */
14
+ readonly code: ErrorCode | LocalErrorCode | (string & {});
15
+ /** What the API said about it: the offending fields of a VALIDATION, the budget of a RATE_LIMITED, … */
16
+ readonly details: unknown;
17
+ /** Seconds until the same request can pass, when the API said so (429 and 503). */
18
+ readonly retryAfterSeconds: number | undefined;
19
+ /** Which budget refused, on a RATE_LIMITED (writes, cells-hour, modifier-changes-day, …). */
20
+ readonly scope: string | undefined;
21
+ /**
22
+ * true when the same request may pass later (a used-up budget, a fault on ZimmerStack's side, a
23
+ * network failure). The client has already retried what was worth holding a request open for;
24
+ * anything false is a verdict on the request itself: fix it, never resend it.
25
+ */
26
+ readonly retryable: boolean;
27
+ /** The operation that failed, as the contract names it: "PUT /rates". Never contains the key. */
28
+ readonly operation: string;
29
+ constructor(init: {
30
+ status: number;
31
+ code: string;
32
+ message: string;
33
+ operation: string;
34
+ details?: unknown;
35
+ retryAfterSeconds?: number;
36
+ scope?: string;
37
+ retryable: boolean;
38
+ cause?: unknown;
39
+ });
40
+ }
41
+ /** Codes this client raises itself, before or instead of an answer from the API. */
42
+ export type LocalErrorCode = "LIVE_KEY_IN_TEST" | "NETWORK_ERROR" | "TIMEOUT";
43
+ /** A mistake in how the client was set up or called. Nothing was sent. */
44
+ export declare class ZimmerStackUsageError extends Error {
45
+ constructor(message: string);
46
+ }