@kite-sa/sdk 0.0.0-stage → 0.6.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,341 @@
1
+ /** Every endpoint in the spec, namespaced by its operationId. */
2
+ export function createEndpoints(request) {
3
+ return {
4
+ analytics: {
5
+ /**
6
+ * Find below-market listings. Residential listings asking noticeably less than
7
+ * similar listings nearby, biggest gap first.
8
+ */
9
+ belowMarket: (params) => request("GET", "/market/below-market", {
10
+ query: params,
11
+ }),
12
+ /**
13
+ * Find below-market listings (old path). **Deprecated:** use GET
14
+ * /market/below-market, which takes the same parameters and returns the same
15
+ * response.
16
+ */
17
+ deals: (params) => request("GET", "/market/deals", { query: params }),
18
+ /**
19
+ * Get comparable listings. Active listings similar to this one, nearest first,
20
+ * with how each one differs. A comparable has the same city, listing type and
21
+ * property type, is within about 5 km, and has an area between 2/3 and 1.5 times
22
+ * this listing's (the comparison-approach caliper).
23
+ */
24
+ listingComparables: (id, params) => request("GET", `/listings/${encodeURIComponent(String(id))}/comparables`, { query: (params ?? {}) }),
25
+ /**
26
+ * Get a listing's market position. Where a listing's price sits in its market:
27
+ * percentile, quartiles and difference from the median, against like-for-like
28
+ * listings in its neighborhood and in its city. The cohort is listings with the
29
+ * same listing type, category and property type, and for residential listings
30
+ * the same bedroom count.
31
+ */
32
+ listingMarketPosition: (id) => request("GET", `/listings/${encodeURIComponent(String(id))}/market-position`),
33
+ /**
34
+ * Get a listing's nearby asking-price band. The 25th percentile, median and 75th
35
+ * percentile of asking prices for comparable units near this listing, in SAR and
36
+ * per m², where this listing's price sits against them, and the cohort and
37
+ * stability behind the numbers.
38
+ */
39
+ listingPriceBand: (id) => request("GET", `/listings/${encodeURIComponent(String(id))}/price-band`),
40
+ /**
41
+ * Compare neighborhoods. Side-by-side profile of 2 to 5 neighborhoods: price
42
+ * quartiles, area, price per m², amenity shares, bedroom and property-type mix,
43
+ * and for rentals the gross yield against the same cohort's sale prices.
44
+ */
45
+ neighborhoodsCompare: (params) => request("GET", "/market/neighborhoods/compare", { query: params }),
46
+ /**
47
+ * Get gross rental yield. Gross rental yield (median yearly asking rent ÷ median
48
+ * asking sale price) for one property type, over the whole city (or the
49
+ * requested neighborhoods) and per neighborhood, highest yield first. Rent and
50
+ * sale medians come from the same cohort (property type, and bedrooms if given)
51
+ * in the same area.
52
+ */
53
+ rentalYield: (params) => request("GET", "/market/rental-yield", {
54
+ query: params,
55
+ }),
56
+ /**
57
+ * Get price trends. Monthly asking prices over recent months (up to 36), for a
58
+ * city or for up to five neighborhoods (one series each): the median and
59
+ * quartiles for the price level, and a constant-quality price index
60
+ * (`price_index`) for change over time.
61
+ */
62
+ trends: (params) => request("GET", "/market/trends", { query: params }),
63
+ },
64
+ exports: {
65
+ /**
66
+ * Create an export. Starts an export of a whole dataset as files, for loading
67
+ * into a warehouse.
68
+ */
69
+ create: (body, headers) => request("POST", "/exports", {
70
+ body,
71
+ headers: headers,
72
+ }),
73
+ /**
74
+ * Get an export. An export's status and, once `completed`, a signed download
75
+ * link for every file, valid for 60 minutes; call again for fresh links.
76
+ */
77
+ get: (exportId) => request("GET", `/exports/${encodeURIComponent(String(exportId))}`),
78
+ /**
79
+ * List exports. Your organization's exports, newest first, without download
80
+ * links (GET one export for those).
81
+ */
82
+ list: (params) => request("GET", "/exports", { query: (params ?? {}) }),
83
+ },
84
+ listings: {
85
+ /** Get listings by id. Up to 100 listings in one call, in the order requested. */
86
+ batch: (params) => request("GET", "/listings/batch", { query: params }),
87
+ /** Count listings. How many listings match the same filters as search. */
88
+ count: (params) => request("GET", "/listings/count", { query: params }),
89
+ /** Get a listing. One active listing. */
90
+ get: (id) => request("GET", `/listings/${encodeURIComponent(String(id))}`),
91
+ /**
92
+ * Get a listing's price history. Every price change Kite recorded for an active
93
+ * listing, oldest first.
94
+ */
95
+ priceHistory: (id) => request("GET", `/listings/${encodeURIComponent(String(id))}/price-history`),
96
+ /**
97
+ * Search listings. Active, deduplicated listings in one city, quality-filtered
98
+ * like kite.sa.
99
+ */
100
+ search: (params) => request("GET", "/listings", { query: params }),
101
+ },
102
+ market: {
103
+ /**
104
+ * Area distribution. Histogram and percentiles of floor/plot area (m²) over
105
+ * listings in the sample that state an area (`without_area_count` did not).
106
+ */
107
+ areaDistribution: (params) => request("GET", "/market/area-distribution", {
108
+ query: params,
109
+ }),
110
+ /**
111
+ * Commercial rent per m² by neighborhood. Asking rent per m² of commercial space
112
+ * (shops, offices, warehouses, commercial land and whole buildings) by
113
+ * neighborhood, with the city-wide figure for each type as a benchmark.
114
+ */
115
+ commercialRents: (params) => request("GET", "/market/commercial-rents", {
116
+ query: params,
117
+ }),
118
+ /**
119
+ * Land prices per m². Median registered price per m² of land plots, per quarter,
120
+ * for a city, for each of up to 20 neighborhoods (`neighborhood_id`), or for
121
+ * every neighborhood in the city in one call (`group_by=neighborhood` without
122
+ * `neighborhood_id`, over at most 12 quarters), with quarter-on-quarter and
123
+ * year-on-year change.
124
+ */
125
+ landPrices: (params) => request("GET", "/market/land-prices", {
126
+ query: params,
127
+ }),
128
+ /**
129
+ * Prices by neighborhood. Median and quartile price per neighborhood in a city,
130
+ * most expensive first.
131
+ */
132
+ neighborhoods: (params) => request("GET", "/market/neighborhoods", {
133
+ query: params,
134
+ }),
135
+ /** Price distribution. Histogram and percentiles of price. */
136
+ priceDistribution: (params) => request("GET", "/market/price-distribution", {
137
+ query: params,
138
+ }),
139
+ /**
140
+ * Market summary. Headline numbers for a city (or neighborhoods): listing count,
141
+ * median and quartile price, median area and price per m², how recently listings
142
+ * were updated, and breakdowns by property type, top neighborhoods by volume,
143
+ * and source. Computed over the market sample: active, deduplicated listings
144
+ * updated in the last 30 days (`updated_at`), after the same outlier filter
145
+ * kite.sa uses (per-tier price fences from the median and MAD of log price,
146
+ * bedroom and area sanity checks, and a floor at 30% of the neighborhood
147
+ * median).
148
+ */
149
+ summary: (params) => request("GET", "/market/summary", { query: params }),
150
+ /**
151
+ * New supply. How many listings came onto the market recently: listings first
152
+ * seen in the last 7 days vs the 7 days before, and the last 30 days vs the 30
153
+ * days before (rolling windows ending now).
154
+ */
155
+ supply: (params) => request("GET", "/market/supply", { query: params }),
156
+ /**
157
+ * Registered deal statistics. Deal counts and median, 25th and 75th percentile
158
+ * price per m² and total price, per quarter and land-use class, for a city, a
159
+ * set of neighborhoods combined (`group_by=city` with `neighborhood_id`), or
160
+ * each neighborhood (`group_by=neighborhood`).
161
+ */
162
+ transactions: (params) => request("GET", "/market/transactions", {
163
+ query: params,
164
+ }),
165
+ /**
166
+ * Vacancy indicator. How long listings in the sample have been on the market, as
167
+ * a proxy for vacancy (actual occupancy isn't observed).
168
+ */
169
+ vacancy: (params) => request("GET", "/market/vacancy", { query: params }),
170
+ },
171
+ official: {
172
+ /**
173
+ * Kite Property Index. **Free on every plan (0 units).** Series built on Saudi
174
+ * open data are served under the Saudi Open Data License v2.0 with attribution:
175
+ * show `attribution.notice` wherever you display or pass on those figures. The
176
+ * Kite Property Index, as published: the series of a **published monthly
177
+ * release**, frozen when it was released.
178
+ */
179
+ marketIndex: (params) => request("GET", "/market/property-index", {
180
+ query: (params ?? {}),
181
+ }),
182
+ /**
183
+ * Registered rents (REGA). **Free on every plan (0 units).** This is Saudi open
184
+ * data, served at no charge under the Saudi Open Data License v2.0 with
185
+ * attribution: show `attribution.notice` wherever you display or pass on the
186
+ * figures. Registered rents from REGA's quarterly rent index ("مؤشر الايجار",
187
+ * published on open.data.gov.sa): for each neighborhood and property type, the
188
+ * **mean** yearly rent of the residential leases registered on Ejar that
189
+ * quarter, the mean yearly rent per m², and the number of contracts behind them.
190
+ * - **These are means, not medians.** REGA publishes the mean; a few large
191
+ * leases pull it up, so it usually sits above a median.
192
+ */
193
+ registeredRents: (params) => request("GET", "/market/registered-rents", {
194
+ query: params,
195
+ }),
196
+ },
197
+ organization: {
198
+ auditEvents: {
199
+ /** List audit events. Newest first, 50 per page. */
200
+ list: (params) => request("GET", "/organization/audit-events", {
201
+ query: (params ?? {}),
202
+ }),
203
+ },
204
+ /** Get your organization. Name, plan and limits, and this month's usage. */
205
+ get: () => request("GET", "/organization"),
206
+ keys: {
207
+ /** Create a data key. Creates a `dk_live_…` key. */
208
+ create: (body, headers) => request("POST", "/organization/keys", {
209
+ body,
210
+ headers: headers,
211
+ }),
212
+ /** List data keys. Active data keys (`dk_live_…`). */
213
+ list: () => request("GET", "/organization/keys"),
214
+ /** Revoke a key. Requests with the key are rejected right away. */
215
+ revoke: (keyId, headers) => request("POST", `/organization/keys/${encodeURIComponent(String(keyId))}/revoke`, { headers: headers }),
216
+ },
217
+ members: {
218
+ /**
219
+ * List members and invitations. Everyone with access to this organization and
220
+ * every invitation not yet accepted, with each person's role.
221
+ */
222
+ list: () => request("GET", "/organization/members"),
223
+ },
224
+ projects: {
225
+ /** List projects. The projects this organization's keys belong to. */
226
+ list: () => request("GET", "/organization/projects"),
227
+ },
228
+ requestLogs: {
229
+ /**
230
+ * List request logs. Calls this organization made, newest first, within its
231
+ * retention window (7, 30 or 90 days, set on the Settings page).
232
+ */
233
+ list: (params) => request("GET", "/organization/request-logs", {
234
+ query: (params ?? {}),
235
+ }),
236
+ },
237
+ /**
238
+ * Daily usage. Requests and units per UTC day, key, endpoint and result class,
239
+ * for the last 7, 30 or 90 days.
240
+ */
241
+ usage: (params) => request("GET", "/organization/usage", {
242
+ query: (params ?? {}),
243
+ }),
244
+ webhooks: {
245
+ /** Create a webhook endpoint. Subscribes an HTTPS URL to listing events. */
246
+ create: (body, headers) => request("POST", "/organization/webhooks", {
247
+ body,
248
+ headers: headers,
249
+ }),
250
+ /**
251
+ * Delete a webhook endpoint. Stops delivery and removes the endpoint and its
252
+ * delivery history.
253
+ */
254
+ delete: (webhookId, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/delete`, { headers: headers }),
255
+ /**
256
+ * List deliveries. What was sent to this endpoint, newest first, with what it
257
+ * answered.
258
+ */
259
+ deliveries: (webhookId, params) => request("GET", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/deliveries`, { query: (params ?? {}) }),
260
+ /** List webhook endpoints. Every endpoint this organization has subscribed. */
261
+ list: () => request("GET", "/organization/webhooks"),
262
+ /**
263
+ * Replay a delivery. Queues the same payload again, with its original
264
+ * `event_id` so a receiver that already handled it can recognise the repeat.
265
+ */
266
+ replay: (webhookId, deliveryId, headers) => request("POST", `/organization/webhooks/${encodeURIComponent(String(webhookId))}/deliveries/${encodeURIComponent(String(deliveryId))}/replay`, { headers: headers }),
267
+ },
268
+ },
269
+ projects: {
270
+ /** List developers. Developers with active projects on Kite, most projects first. */
271
+ developers: (params) => request("GET", "/developers", {
272
+ query: (params ?? {}),
273
+ }),
274
+ /**
275
+ * Get a project. One project with its description, boundary, amenities,
276
+ * financing banks and a summary of the units listed on Kite.
277
+ */
278
+ get: (id) => request("GET", `/projects/${encodeURIComponent(String(id))}`),
279
+ /**
280
+ * Search projects. Off-plan and newly built residential and commercial projects
281
+ * from Saudi developers and portals, one entry per project (copies from several
282
+ * sources are merged).
283
+ */
284
+ search: (params) => request("GET", "/projects", {
285
+ query: (params ?? {}),
286
+ }),
287
+ /**
288
+ * List a project's units. Active listings on Kite linked to one project: units
289
+ * for sale (total price) and, for some projects, rentals (yearly rent).
290
+ */
291
+ units: (id, params) => request("GET", `/projects/${encodeURIComponent(String(id))}/units`, { query: (params ?? {}) }),
292
+ /**
293
+ * Search project units. Units across all projects: active listings linked to a
294
+ * project, filtered by the unit (bedrooms, price, area) and by its project
295
+ * (city, developer, status).
296
+ */
297
+ unitsSearch: (params) => request("GET", "/project-units", {
298
+ query: (params ?? {}),
299
+ }),
300
+ },
301
+ reference: {
302
+ /** List cities. Cities Kite covers. */
303
+ cities: () => request("GET", "/cities"),
304
+ /**
305
+ * What the API covers. What the API can answer, per city: active listings by
306
+ * listing type and kind of property, how many neighborhoods have at least 10 of
307
+ * them, the share with a published nearby price band, the latest registered-deal
308
+ * quarter and how much of it is placed in neighborhoods, and whether registered
309
+ * rents exist.
310
+ */
311
+ coverage: (params) => request("GET", "/coverage", {
312
+ query: (params ?? {}),
313
+ }),
314
+ /**
315
+ * List city directions. Groupings of neighborhoods by part of the city (north,
316
+ * east, …).
317
+ */
318
+ directions: (city) => request("GET", `/cities/${encodeURIComponent(String(city))}/directions`),
319
+ /** List enumerated values. Allowed values for enumerated fields and filters. */
320
+ enums: () => request("GET", "/enums"),
321
+ /**
322
+ * Get this key's limits. The plan, rate limit, monthly quota, page size and
323
+ * paging depth that apply to the key making the request, and the APIs it can
324
+ * reach.
325
+ */
326
+ limits: () => request("GET", "/limits"),
327
+ /** List neighborhoods. Active neighborhoods in a city. */
328
+ neighborhoods: (city) => request("GET", `/cities/${encodeURIComponent(String(city))}/neighborhoods`),
329
+ },
330
+ transactions: {
331
+ /**
332
+ * Search registered deals. Individual sale deals registered with the Ministry of
333
+ * Justice, from its quarterly open data, in one city: month, neighborhood,
334
+ * land-use class, area, price and price per m².
335
+ */
336
+ search: (params) => request("GET", "/transactions", {
337
+ query: params,
338
+ }),
339
+ },
340
+ };
341
+ }
@@ -0,0 +1,111 @@
1
+ import { type Endpoints } from "./generated.js";
2
+ import type { operations } from "./openapi.js";
3
+ export type { operations } from "./openapi.js";
4
+ export type { Endpoints } from "./generated.js";
5
+ type Op = keyof operations;
6
+ type QueryOf<K extends Op> = operations[K]["parameters"] extends {
7
+ query?: infer Q;
8
+ } ? NonNullable<Q> : never;
9
+ type ResultOf<K extends Op> = operations[K]["responses"] extends {
10
+ 200: {
11
+ content: {
12
+ "application/json": infer R;
13
+ };
14
+ };
15
+ } ? R : never;
16
+ export type ListingSearchParams = QueryOf<"listings.search">;
17
+ export type ListingCountParams = QueryOf<"listings.count">;
18
+ export type ListingPage = ResultOf<"listings.search">;
19
+ export type Listing = ListingPage["data"][number];
20
+ /** Any non-2xx response. Branch on `code`; `message` is for humans. */
21
+ export declare class KiteError extends Error {
22
+ readonly status: number;
23
+ readonly type: string;
24
+ readonly code: string;
25
+ readonly requestId: string | null;
26
+ readonly param: string | null;
27
+ /** Seconds to wait before retrying, from Retry-After, when the API sent one. */
28
+ readonly retryAfter: number | null;
29
+ constructor(status: number, type: string, code: string, message: string, requestId: string | null, param?: string | null,
30
+ /** Seconds to wait before retrying, from Retry-After, when the API sent one. */
31
+ retryAfter?: number | null);
32
+ }
33
+ export interface KiteOptions {
34
+ /** Defaults to the KITE_API_KEY environment variable. */
35
+ apiKey?: string;
36
+ baseUrl?: string;
37
+ /** Retries for 429, 5xx and network errors (default 2). */
38
+ maxRetries?: number;
39
+ /** Per-attempt timeout in milliseconds (default 30000). */
40
+ timeoutMs?: number;
41
+ /** Custom fetch, e.g. for tests or proxies. */
42
+ fetch?: typeof fetch;
43
+ }
44
+ type Query = Record<string, string | number | boolean | readonly (string | number)[] | undefined>;
45
+ /** Kept in step with package.json by src/index.test.ts. */
46
+ export declare const VERSION = "0.6.0";
47
+ /** Arrays go comma-separated, as the API expects; unset values are dropped. */
48
+ export declare function toSearchParams(query?: Query): string;
49
+ /**
50
+ * Every namespace in the spec, merged into the class type. Declaration merging
51
+ * rather than a hand-written list of fields: that list is exactly what drifted
52
+ * out of date before, leaving `market`, `analytics` and `projects` unreachable
53
+ * while the docs sold them.
54
+ *
55
+ * The lint rule below guards a real hazard — an interface can promise members
56
+ * the constructor never sets, and the types would not notice. Here the
57
+ * constructor assigns them from `createEndpoints`, and `generated.test.ts`
58
+ * resolves every `operationId` in the spec against a real instance, so the
59
+ * promise is checked rather than assumed.
60
+ */
61
+ export interface Kite extends Omit<Endpoints, "listings"> {
62
+ }
63
+ export declare class Kite {
64
+ readonly baseUrl: string;
65
+ private readonly apiKey;
66
+ private readonly maxRetries;
67
+ private readonly timeoutMs;
68
+ private readonly fetchImpl;
69
+ constructor(options?: KiteOptions);
70
+ /** Low-level call for any endpoint; prefer the typed helpers below. */
71
+ request<T>(method: "GET" | "POST", path: string, options?: {
72
+ query?: Query;
73
+ body?: unknown;
74
+ headers?: Record<string, string | undefined>;
75
+ }): Promise<T>;
76
+ /**
77
+ * The generated `listings` namespace plus paging that follows the cursor for
78
+ * you. Declared here rather than merged in, because it is the one namespace
79
+ * this client adds to.
80
+ */
81
+ readonly listings: Endpoints["listings"] & {
82
+ searchAll: (params: Omit<ListingSearchParams, "cursor">) => AsyncGenerator<Listing>;
83
+ };
84
+ /** Kept from 0.1.x; the generated names live on `reference`. */
85
+ readonly cities: {
86
+ list: Endpoints["reference"]["cities"];
87
+ neighborhoods: Endpoints["reference"]["neighborhoods"];
88
+ directions: Endpoints["reference"]["directions"];
89
+ };
90
+ /** Allowed values for enum parameters (sources, property types, …). */
91
+ enums(): Promise<{
92
+ data: {
93
+ listing_types: string[];
94
+ listing_categories: string[];
95
+ property_types: {
96
+ residential: string[];
97
+ commercial: string[];
98
+ };
99
+ rent_frequencies: string[];
100
+ advertiser_types: string[];
101
+ amenities: string[];
102
+ project_features: string[];
103
+ project_banks: string[];
104
+ sources: {
105
+ id: string;
106
+ name: string;
107
+ }[];
108
+ };
109
+ }>;
110
+ }
111
+ export default Kite;
package/dist/index.js ADDED
@@ -0,0 +1,146 @@
1
+ import { createEndpoints } from "./generated.js";
2
+ // ── Errors ────────────────────────────────────────────────────────────────
3
+ /** Any non-2xx response. Branch on `code`; `message` is for humans. */
4
+ export class KiteError extends Error {
5
+ status;
6
+ type;
7
+ code;
8
+ requestId;
9
+ param;
10
+ retryAfter;
11
+ constructor(status, type, code, message, requestId, param = null,
12
+ /** Seconds to wait before retrying, from Retry-After, when the API sent one. */
13
+ retryAfter = null) {
14
+ super(message);
15
+ this.status = status;
16
+ this.type = type;
17
+ this.code = code;
18
+ this.requestId = requestId;
19
+ this.param = param;
20
+ this.retryAfter = retryAfter;
21
+ this.name = "KiteError";
22
+ }
23
+ }
24
+ /** Kept in step with package.json by src/index.test.ts. */
25
+ export const VERSION = "0.6.0";
26
+ const USER_AGENT = `kite-sa-js/${VERSION}`;
27
+ /** Longest Retry-After worth waiting for; anything longer (a monthly quota) throws. */
28
+ const MAX_RETRY_WAIT_S = 60;
29
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
30
+ /** Arrays go comma-separated, as the API expects; unset values are dropped. */
31
+ export function toSearchParams(query = {}) {
32
+ const out = new URLSearchParams();
33
+ for (const [k, v] of Object.entries(query)) {
34
+ if (v === undefined || v === null)
35
+ continue;
36
+ out.set(k, Array.isArray(v) ? v.join(",") : String(v));
37
+ }
38
+ const s = out.toString();
39
+ return s ? `?${s}` : "";
40
+ }
41
+ /* eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging */
42
+ export class Kite {
43
+ baseUrl;
44
+ apiKey;
45
+ maxRetries;
46
+ timeoutMs;
47
+ fetchImpl;
48
+ constructor(options = {}) {
49
+ const key = options.apiKey ?? (typeof process !== "undefined" ? process.env?.KITE_API_KEY : undefined);
50
+ if (!key) {
51
+ throw new Error("Pass apiKey or set KITE_API_KEY. Get a key at https://platform.kite.sa.");
52
+ }
53
+ this.apiKey = key;
54
+ this.baseUrl = (options.baseUrl ?? "https://api.kite.sa/v1").replace(/\/$/, "");
55
+ this.maxRetries = options.maxRetries ?? 2;
56
+ this.timeoutMs = options.timeoutMs ?? 30_000;
57
+ this.fetchImpl = options.fetch ?? globalThis.fetch;
58
+ const endpoints = createEndpoints((method, path, opts) => this.request(method, path, opts));
59
+ Object.assign(this, endpoints);
60
+ this.listings = {
61
+ ...endpoints.listings,
62
+ searchAll: async function* (params) {
63
+ let cursor;
64
+ do {
65
+ const page = await this.listings.search({ ...params, cursor });
66
+ yield* page.data;
67
+ cursor = page.pagination.has_more
68
+ ? (page.pagination.next_cursor ?? undefined)
69
+ : undefined;
70
+ } while (cursor);
71
+ }.bind(this),
72
+ };
73
+ this.cities = {
74
+ list: endpoints.reference.cities,
75
+ neighborhoods: endpoints.reference.neighborhoods,
76
+ directions: endpoints.reference.directions,
77
+ };
78
+ }
79
+ /** Low-level call for any endpoint; prefer the typed helpers below. */
80
+ async request(method, path, options = {}) {
81
+ const url = `${this.baseUrl}${path}${toSearchParams(options.query)}`;
82
+ for (let attempt = 0;; attempt++) {
83
+ let res;
84
+ try {
85
+ res = await this.fetchImpl(url, {
86
+ method,
87
+ headers: {
88
+ // Caller-supplied optional headers cannot replace the SDK key.
89
+ ...Object.fromEntries(Object.entries(options.headers ?? {}).filter((entry) => entry[1] !== undefined)),
90
+ Authorization: `Bearer ${this.apiKey}`,
91
+ Accept: "application/json",
92
+ // Browsers forbid setting User-Agent, and the request fails outright
93
+ // if you try. Keys must never reach a browser anyway, so this is
94
+ // best-effort: it identifies SDK traffic in the request log wherever
95
+ // the runtime allows it.
96
+ ...(typeof window === "undefined" && { "User-Agent": USER_AGENT }),
97
+ ...(options.body !== undefined && { "Content-Type": "application/json" }),
98
+ },
99
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
100
+ signal: AbortSignal.timeout(this.timeoutMs),
101
+ });
102
+ }
103
+ catch (err) {
104
+ if (attempt < this.maxRetries) {
105
+ await sleep(backoff(attempt));
106
+ continue;
107
+ }
108
+ throw err;
109
+ }
110
+ if (res.ok)
111
+ return (await res.json());
112
+ const error = await toError(res);
113
+ const retryable = res.status === 429 || res.status >= 500;
114
+ const wait = error.retryAfter ?? backoff(attempt) / 1000;
115
+ if (retryable && attempt < this.maxRetries && wait <= MAX_RETRY_WAIT_S) {
116
+ await sleep(wait * 1000);
117
+ continue;
118
+ }
119
+ throw error;
120
+ }
121
+ }
122
+ /**
123
+ * The generated `listings` namespace plus paging that follows the cursor for
124
+ * you. Declared here rather than merged in, because it is the one namespace
125
+ * this client adds to.
126
+ */
127
+ listings;
128
+ /** Kept from 0.1.x; the generated names live on `reference`. */
129
+ cities;
130
+ /** Allowed values for enum parameters (sources, property types, …). */
131
+ enums() {
132
+ return this.reference.enums();
133
+ }
134
+ }
135
+ /** Exponential backoff with jitter, in milliseconds: ~0.5s, 1s, 2s, … */
136
+ function backoff(attempt) {
137
+ return Math.min(8000, 500 * 2 ** attempt) * (0.75 + Math.random() * 0.5);
138
+ }
139
+ async function toError(res) {
140
+ const retryAfter = Number(res.headers.get("retry-after"));
141
+ const requestId = res.headers.get("x-request-id");
142
+ const body = (await res.json().catch(() => null));
143
+ const e = body?.error;
144
+ return new KiteError(res.status, e?.type ?? "api_error", e?.code ?? `http_${res.status}`, e?.message ?? `The API returned HTTP ${res.status}.`, e?.request_id ?? requestId, e?.param ?? null, Number.isFinite(retryAfter) && res.headers.has("retry-after") ? retryAfter : null);
145
+ }
146
+ export default Kite;
@@ -0,0 +1,64 @@
1
+ export interface ClientConfig {
2
+ /** Base URL for all API requests (e.g. 'https://api.example.com') */
3
+ baseUrl: string;
4
+ /**
5
+ * Bearer token or a function that returns one (supports async refresh).
6
+ * When provided, adds `Authorization: Bearer <token>` to every request.
7
+ */
8
+ token?: string | (() => string | Promise<string>);
9
+ /**
10
+ * Fetch credentials mode. Use 'include' for cookie-based auth.
11
+ * Defaults to 'same-origin'.
12
+ */
13
+ credentials?: RequestCredentials;
14
+ /** Additional headers sent with every request */
15
+ headers?: Record<string, string>;
16
+ /**
17
+ * Global error hook called with every non-2xx response error before it is
18
+ * thrown. Use for logging, monitoring, or triggering auth refresh flows.
19
+ *
20
+ * @example
21
+ * configureClient({
22
+ * onError: (err) => Sentry.captureException(err),
23
+ * })
24
+ */
25
+ onError?: (err: Error) => void;
26
+ /**
27
+ * Default AbortSignal for every request. Useful for cancelling in-flight
28
+ * requests (e.g. on route change). Overridable per call via the config param.
29
+ */
30
+ signal?: AbortSignal;
31
+ /**
32
+ * Default timeout in milliseconds. When set, every request is aborted with a
33
+ * TimeoutError after the specified duration. Overridable per call.
34
+ */
35
+ timeout?: number;
36
+ /**
37
+ * Request interceptor called before every fetch. Receives the resolved URL and
38
+ * RequestInit; may return an object with optional url/init overrides.
39
+ *
40
+ * @example
41
+ * configureClient({
42
+ * onRequest: ({ url, init }) => ({ init: { ...init, headers: { ...init.headers, 'X-Request-Id': crypto.randomUUID() } } }),
43
+ * })
44
+ */
45
+ onRequest?: (req: {
46
+ url: string;
47
+ init: RequestInit;
48
+ }) => void | {
49
+ url?: string;
50
+ init?: RequestInit;
51
+ } | Promise<void | {
52
+ url?: string;
53
+ init?: RequestInit;
54
+ }>;
55
+ /**
56
+ * Custom fetch implementation. Defaults to globalThis.fetch, resolved at
57
+ * call time so test mocks of globalThis.fetch are always honoured.
58
+ */
59
+ fetch?: typeof globalThis.fetch;
60
+ }
61
+ /** Configure the API client. Call once at app startup before making any requests. */
62
+ export declare function configureClient(config: ClientConfig): void;
63
+ /** @internal — used by generated fetch functions */
64
+ export declare function getConfig(): Readonly<ClientConfig>;
@@ -0,0 +1,13 @@
1
+ // This file is auto-generated by openapi-zod-ts — do not edit
2
+ let _config = {
3
+ baseUrl: "",
4
+ credentials: "same-origin",
5
+ };
6
+ /** Configure the API client. Call once at app startup before making any requests. */
7
+ export function configureClient(config) {
8
+ _config = { ..._config, ...config };
9
+ }
10
+ /** @internal — used by generated fetch functions */
11
+ export function getConfig() {
12
+ return _config;
13
+ }