@jayik/node 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +672 -2
- package/dist/index.cjs +957 -0
- package/dist/index.d.cts +587 -0
- package/dist/index.d.ts +587 -0
- package/dist/index.js +895 -0
- package/package.json +55 -4
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,587 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
|
|
3
|
+
/** The parts of an API answer kept on errors and returned by `client.send()`. */
|
|
4
|
+
interface ApiResponse {
|
|
5
|
+
status: number;
|
|
6
|
+
headers: Headers;
|
|
7
|
+
/** The decoded JSON body, or null when the body was empty or not JSON. */
|
|
8
|
+
body: unknown;
|
|
9
|
+
/** The raw body text. */
|
|
10
|
+
text: string;
|
|
11
|
+
}
|
|
12
|
+
declare class JayikError extends Error {
|
|
13
|
+
constructor(message: string, options?: ErrorOptions);
|
|
14
|
+
}
|
|
15
|
+
/** The request never got an answer: network failure or timeout. See `cause`. */
|
|
16
|
+
declare class ConnectionError extends JayikError {
|
|
17
|
+
}
|
|
18
|
+
/** A webhook that is not signed by Jayik, or cannot be checked. */
|
|
19
|
+
declare class InvalidSignatureError extends JayikError {
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Any non-2xx answer from the API. Error bodies look like
|
|
23
|
+
* {"status": false, "message": "..." | {"field": ["..."]}, "data": []}.
|
|
24
|
+
*/
|
|
25
|
+
declare class RequestError extends JayikError {
|
|
26
|
+
/** HTTP status. */
|
|
27
|
+
readonly status: number;
|
|
28
|
+
readonly response: ApiResponse;
|
|
29
|
+
/** Field => messages, filled for validation failures. */
|
|
30
|
+
errors: Record<string, string[]>;
|
|
31
|
+
constructor(message: string, response: ApiResponse);
|
|
32
|
+
static fromResponse(response: ApiResponse): RequestError;
|
|
33
|
+
}
|
|
34
|
+
/** 400 — invalid or refused input. */
|
|
35
|
+
declare class ValidationError extends RequestError {
|
|
36
|
+
}
|
|
37
|
+
/** 401 — missing or invalid key. */
|
|
38
|
+
declare class AuthenticationError extends RequestError {
|
|
39
|
+
}
|
|
40
|
+
/** 403 — inactive account, missing permission, or action not allowed. */
|
|
41
|
+
declare class PermissionDeniedError extends RequestError {
|
|
42
|
+
}
|
|
43
|
+
/** 404 — nothing with that id on your account. */
|
|
44
|
+
declare class NotFoundError extends RequestError {
|
|
45
|
+
}
|
|
46
|
+
/** 409 — not possible in the order's current state. */
|
|
47
|
+
declare class ConflictError extends RequestError {
|
|
48
|
+
}
|
|
49
|
+
/** 422 — valid request that cannot be carried out. */
|
|
50
|
+
declare class UnprocessableError extends RequestError {
|
|
51
|
+
}
|
|
52
|
+
/** 429 — rate limit (120 requests/minute per account) reached. */
|
|
53
|
+
declare class RateLimitError extends RequestError {
|
|
54
|
+
/** Seconds to wait before retrying, from the Retry-After header. */
|
|
55
|
+
get retryAfter(): number | null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface JayikConfig {
|
|
59
|
+
/**
|
|
60
|
+
* Created in the Tajr dashboard (https://tajr.jayik.app/api-keys). The key
|
|
61
|
+
* acts as the merchant account that owns it; keep it server-side only.
|
|
62
|
+
* Defaults to the JAYIK_API_KEY environment variable.
|
|
63
|
+
*/
|
|
64
|
+
apiKey?: string;
|
|
65
|
+
/** Defaults to JAYIK_BASE_URL, then https://api.jayik.app/api/merchant. */
|
|
66
|
+
baseUrl?: string;
|
|
67
|
+
/** Request timeout in seconds (JAYIK_TIMEOUT, default 30). 0 disables it. */
|
|
68
|
+
timeout?: number;
|
|
69
|
+
/**
|
|
70
|
+
* The API allows 120 requests/minute per account and answers 429 with a
|
|
71
|
+
* Retry-After header. The client waits and retries up to `retries` times
|
|
72
|
+
* (JAYIK_RATE_LIMIT_RETRIES, default 2), never sleeping longer than
|
|
73
|
+
* `maxWait` seconds per attempt (JAYIK_RATE_LIMIT_MAX_WAIT, default 30).
|
|
74
|
+
* Set retries to 0 to get a RateLimitError immediately.
|
|
75
|
+
*/
|
|
76
|
+
rateLimit?: {
|
|
77
|
+
retries?: number;
|
|
78
|
+
maxWait?: number;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* `secret` is the `secret.value` returned by `jayik.webhook.get()` (starts
|
|
82
|
+
* with whsec_; JAYIK_WEBHOOK_SECRET). Webhooks older than `tolerance`
|
|
83
|
+
* seconds are rejected (JAYIK_WEBHOOK_TOLERANCE, default 300; 0 disables).
|
|
84
|
+
*/
|
|
85
|
+
webhook?: {
|
|
86
|
+
secret?: string;
|
|
87
|
+
tolerance?: number;
|
|
88
|
+
};
|
|
89
|
+
/** Replace the fetch implementation. Mainly for tests. */
|
|
90
|
+
fetch?: typeof fetch;
|
|
91
|
+
/** Replace the wait between rate-limit retries (receives seconds). Mainly for tests. */
|
|
92
|
+
sleep?: (seconds: number) => void | Promise<void>;
|
|
93
|
+
}
|
|
94
|
+
interface ResolvedConfig {
|
|
95
|
+
apiKey: string | undefined;
|
|
96
|
+
baseUrl: string;
|
|
97
|
+
timeout: number;
|
|
98
|
+
rateLimit: {
|
|
99
|
+
retries: number;
|
|
100
|
+
maxWait: number;
|
|
101
|
+
};
|
|
102
|
+
webhook: {
|
|
103
|
+
secret: string | undefined;
|
|
104
|
+
tolerance: number;
|
|
105
|
+
};
|
|
106
|
+
fetch?: typeof fetch;
|
|
107
|
+
sleep?: (seconds: number) => void | Promise<void>;
|
|
108
|
+
}
|
|
109
|
+
type QueryValue = string | number | boolean | null | undefined | ReadonlyArray<string | number> | {
|
|
110
|
+
[key: string]: QueryValue;
|
|
111
|
+
};
|
|
112
|
+
type Query = {
|
|
113
|
+
[key: string]: QueryValue;
|
|
114
|
+
};
|
|
115
|
+
type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';
|
|
116
|
+
/**
|
|
117
|
+
* Drops null/undefined, turns arrays into CSV (include: ['status', 'customer'])
|
|
118
|
+
* and booleans into 1/0 so `filter[...]` style objects can be passed naturally.
|
|
119
|
+
*/
|
|
120
|
+
declare function normalizeQuery(query: Query): Record<string, unknown>;
|
|
121
|
+
declare function buildQueryString(query: Query): string;
|
|
122
|
+
/** "YYYY-MM-DD HH:MM:SS" in the process's local time zone. */
|
|
123
|
+
declare function formatDate(date: Date): string;
|
|
124
|
+
/**
|
|
125
|
+
* Responses in the {status, message, data} wrapper are unwrapped to `data`;
|
|
126
|
+
* bare objects, arrays and page objects are returned as they are.
|
|
127
|
+
*/
|
|
128
|
+
declare function unwrap(json: unknown): unknown;
|
|
129
|
+
declare class Client {
|
|
130
|
+
readonly config: ResolvedConfig;
|
|
131
|
+
constructor(config?: JayikConfig);
|
|
132
|
+
withKey(apiKey: string): Client;
|
|
133
|
+
get<T = any>(uri: string, query?: Query): Promise<T>;
|
|
134
|
+
post<T = any>(uri: string, body?: object): Promise<T>;
|
|
135
|
+
put<T = any>(uri: string, body?: object): Promise<T>;
|
|
136
|
+
delete<T = any>(uri: string): Promise<T>;
|
|
137
|
+
/** Send a request and return the decoded, unwrapped payload. */
|
|
138
|
+
request<T = any>(method: Method, uri: string, query?: Query, body?: object): Promise<T>;
|
|
139
|
+
/** Send a request and return the raw response (already checked for errors). */
|
|
140
|
+
send(method: Method, uri: string, query?: Query, body?: object): Promise<ApiResponse>;
|
|
141
|
+
private fetchOnce;
|
|
142
|
+
private sleep;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A record exactly as the API sends it (snake_case keys). */
|
|
146
|
+
type JayikRecord = Record<string, any>;
|
|
147
|
+
interface OrderItemInput {
|
|
148
|
+
attribute_id?: string;
|
|
149
|
+
name?: string;
|
|
150
|
+
weight?: number;
|
|
151
|
+
unit?: string;
|
|
152
|
+
count?: number;
|
|
153
|
+
[key: string]: unknown;
|
|
154
|
+
}
|
|
155
|
+
interface CreateOrderInput {
|
|
156
|
+
customer_phone: string;
|
|
157
|
+
customer_address: string;
|
|
158
|
+
/** IQD to collect; 0 for prepaid. */
|
|
159
|
+
amount: number;
|
|
160
|
+
/** One of your categories. */
|
|
161
|
+
order_category_id: string;
|
|
162
|
+
/** Governorate UUID or its `number`. */
|
|
163
|
+
governorate_id: string | number;
|
|
164
|
+
customer_name?: string;
|
|
165
|
+
/** Your own tracking number; generated when omitted. */
|
|
166
|
+
tr?: string;
|
|
167
|
+
/** Pickup point; must be yours. */
|
|
168
|
+
warehouse_id?: string;
|
|
169
|
+
/** Needed for fawri when the account has a fawri price list. */
|
|
170
|
+
district_id?: string;
|
|
171
|
+
/** 0 normal (default), 1 fawri / express. See DeliveryType. */
|
|
172
|
+
delivery_type?: 0 | 1;
|
|
173
|
+
notes?: string;
|
|
174
|
+
business_name?: string;
|
|
175
|
+
/** "lat,lng", e.g. "33.312805,44.361488". */
|
|
176
|
+
destination_coordinate?: string;
|
|
177
|
+
total_products?: number;
|
|
178
|
+
/** Date objects are formatted as "YYYY-MM-DD HH:MM:SS" in local time. */
|
|
179
|
+
scheduled_delivery_date_from?: Date | string;
|
|
180
|
+
/** Must be after `_from`. */
|
|
181
|
+
scheduled_delivery_date_to?: Date | string;
|
|
182
|
+
invoice_url?: string;
|
|
183
|
+
order_items?: OrderItemInput[];
|
|
184
|
+
[key: string]: unknown;
|
|
185
|
+
}
|
|
186
|
+
/** Batch orders also require `tr` and `customer_name`, and a governorate UUID. */
|
|
187
|
+
interface CreateBatchOrderInput extends CreateOrderInput {
|
|
188
|
+
tr: string;
|
|
189
|
+
customer_name: string;
|
|
190
|
+
governorate_id: string;
|
|
191
|
+
}
|
|
192
|
+
type OrderInclude = 'status' | 'customer' | 'governorate' | 'district' | 'warehouse' | 'orderCategory' | 'orderItems' | 'orderItems.attribute' | 'merchant' | 'history.merchant' | 'driverRate' | 'amountChanges' | 'financial' | (string & {});
|
|
193
|
+
type Include = OrderInclude[] | string;
|
|
194
|
+
type FilterValue = string | number | ReadonlyArray<string | number> | null | undefined;
|
|
195
|
+
interface OrderFilter {
|
|
196
|
+
tr?: FilterValue;
|
|
197
|
+
uuid?: FilterValue;
|
|
198
|
+
status_id?: FilterValue;
|
|
199
|
+
not_status_id?: FilterValue;
|
|
200
|
+
governorate_id?: FilterValue;
|
|
201
|
+
warehouse_id?: FilterValue;
|
|
202
|
+
order_category_id?: FilterValue;
|
|
203
|
+
delivery_type?: FilterValue;
|
|
204
|
+
'customer.phone'?: FilterValue;
|
|
205
|
+
'customer.name'?: FilterValue;
|
|
206
|
+
'customer.address'?: FilterValue;
|
|
207
|
+
amount?: FilterValue;
|
|
208
|
+
[key: string]: QueryValue;
|
|
209
|
+
}
|
|
210
|
+
interface ListOrdersQuery {
|
|
211
|
+
/** Default 15, max 500. */
|
|
212
|
+
take?: number;
|
|
213
|
+
page?: number;
|
|
214
|
+
/** Dates filtering on last update; send `from` and `to` together. */
|
|
215
|
+
from?: string;
|
|
216
|
+
to?: string;
|
|
217
|
+
/** Skips the total count (faster). */
|
|
218
|
+
simple?: boolean;
|
|
219
|
+
/** e.g. "-created_at" ("-" = descending). */
|
|
220
|
+
sort?: string;
|
|
221
|
+
include?: Include;
|
|
222
|
+
filter?: OrderFilter;
|
|
223
|
+
[key: string]: QueryValue;
|
|
224
|
+
}
|
|
225
|
+
interface WarehouseInput {
|
|
226
|
+
name?: string;
|
|
227
|
+
address?: string;
|
|
228
|
+
lat?: number | string;
|
|
229
|
+
long?: number | string;
|
|
230
|
+
/** UUID or number. */
|
|
231
|
+
governorate_id?: string | number | null;
|
|
232
|
+
phone?: string | null;
|
|
233
|
+
secondary_phone?: string | null;
|
|
234
|
+
/** HH:MM */
|
|
235
|
+
availability_times_from?: string | null;
|
|
236
|
+
/** HH:MM */
|
|
237
|
+
availability_times_to?: string | null;
|
|
238
|
+
/** Your own reference. */
|
|
239
|
+
site_id?: string | null;
|
|
240
|
+
[key: string]: unknown;
|
|
241
|
+
}
|
|
242
|
+
type CreateWarehouseInput = WarehouseInput & {
|
|
243
|
+
name: string;
|
|
244
|
+
address: string;
|
|
245
|
+
};
|
|
246
|
+
type DayName = 'sunday' | 'monday' | 'tuesday' | 'wednesday' | 'thursday' | 'friday' | 'saturday';
|
|
247
|
+
type BusinessHoursInput = Partial<Record<DayName, {
|
|
248
|
+
is_closed?: boolean;
|
|
249
|
+
opens_at?: string;
|
|
250
|
+
closes_at?: string;
|
|
251
|
+
}>>;
|
|
252
|
+
|
|
253
|
+
/** One page of a list endpoint (Laravel-style page object). */
|
|
254
|
+
declare class Page<T = JayikRecord> implements Iterable<T> {
|
|
255
|
+
/** The raw page object as returned by the API. */
|
|
256
|
+
readonly raw: Record<string, any>;
|
|
257
|
+
constructor(raw: unknown);
|
|
258
|
+
get items(): T[];
|
|
259
|
+
get currentPage(): number;
|
|
260
|
+
get perPage(): number;
|
|
261
|
+
/** Null when the list was requested with `simple` (no total count). */
|
|
262
|
+
get total(): number | null;
|
|
263
|
+
get lastPage(): number | null;
|
|
264
|
+
get hasMorePages(): boolean;
|
|
265
|
+
get isEmpty(): boolean;
|
|
266
|
+
/** Number of items on this page. */
|
|
267
|
+
get length(): number;
|
|
268
|
+
[Symbol.iterator](): Iterator<T>;
|
|
269
|
+
toJSON(): Record<string, any>;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
declare abstract class Resource {
|
|
273
|
+
protected readonly client: Client;
|
|
274
|
+
constructor(client: Client);
|
|
275
|
+
protected paginate(uri: string, query?: Query): Promise<Page>;
|
|
276
|
+
/** Walk every page lazily, one request per page. */
|
|
277
|
+
protected lazyPages(uri: string, query?: Query): AsyncGenerator<JayikRecord, void, undefined>;
|
|
278
|
+
protected allPages(uri: string, query?: Query): Promise<JayikRecord[]>;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
declare class Account extends Resource {
|
|
282
|
+
/** The merchant behind the API key. */
|
|
283
|
+
details(): Promise<{
|
|
284
|
+
user: JayikRecord;
|
|
285
|
+
roles: string[];
|
|
286
|
+
permissions: string[];
|
|
287
|
+
[key: string]: any;
|
|
288
|
+
}>;
|
|
289
|
+
permissions(): Promise<string[]>;
|
|
290
|
+
}
|
|
291
|
+
declare class OrderCategories extends Resource {
|
|
292
|
+
list(take?: number, page?: number): Promise<Page>;
|
|
293
|
+
lazy(): AsyncGenerator<JayikRecord, void, undefined>;
|
|
294
|
+
get(id: string): Promise<JayikRecord>;
|
|
295
|
+
create(name: string): Promise<JayikRecord>;
|
|
296
|
+
update(id: string, name: string): Promise<JayikRecord>;
|
|
297
|
+
delete(id: string): Promise<void>;
|
|
298
|
+
/** Set the category used as the account's default. */
|
|
299
|
+
setDefault(id: string): Promise<void>;
|
|
300
|
+
}
|
|
301
|
+
declare class Governorates extends Resource {
|
|
302
|
+
list(take?: number, page?: number): Promise<Page>;
|
|
303
|
+
/** Every governorate (id, name, number). Reference data: cache it on your side. */
|
|
304
|
+
all(): Promise<JayikRecord[]>;
|
|
305
|
+
get(id: string): Promise<JayikRecord>;
|
|
306
|
+
}
|
|
307
|
+
declare class Statuses extends Resource {
|
|
308
|
+
list(take?: number, page?: number): Promise<Page>;
|
|
309
|
+
/**
|
|
310
|
+
* Every order status. `name` is the stable code (see OrderStatus);
|
|
311
|
+
* ids are UUIDs. Reference data: cache it on your side.
|
|
312
|
+
*/
|
|
313
|
+
all(): Promise<JayikRecord[]>;
|
|
314
|
+
get(id: string): Promise<JayikRecord>;
|
|
315
|
+
}
|
|
316
|
+
/** Product types; their ids feed order_items[].attribute_id. */
|
|
317
|
+
declare class Attributes extends Resource {
|
|
318
|
+
list(take?: number, page?: number): Promise<Page>;
|
|
319
|
+
all(): Promise<JayikRecord[]>;
|
|
320
|
+
}
|
|
321
|
+
declare class ApiKeys extends Resource {
|
|
322
|
+
/** Keys without their values (values are only shown on create/regenerate). */
|
|
323
|
+
list(take?: number, page?: number): Promise<Page>;
|
|
324
|
+
get(id: string): Promise<JayikRecord>;
|
|
325
|
+
/**
|
|
326
|
+
* Create a key. The `key` field of the result is shown only this once:
|
|
327
|
+
* store it securely.
|
|
328
|
+
*/
|
|
329
|
+
create(description?: string | null): Promise<JayikRecord>;
|
|
330
|
+
/**
|
|
331
|
+
* Issue a new value for a key. The old value stops working immediately;
|
|
332
|
+
* the new one is in the result's `key` field, shown only this once.
|
|
333
|
+
*/
|
|
334
|
+
regenerate(id: string): Promise<JayikRecord>;
|
|
335
|
+
/** Switch a key on or off. Pass a description to change it too. */
|
|
336
|
+
update(id: string, active: boolean, description?: string | null): Promise<JayikRecord>;
|
|
337
|
+
delete(id: string): Promise<JayikRecord>;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
declare class Orders extends Resource {
|
|
341
|
+
/**
|
|
342
|
+
* List orders.
|
|
343
|
+
*
|
|
344
|
+
* await jayik.orders.list({
|
|
345
|
+
* filter: { warehouse_id: id, status_id: [a, b] },
|
|
346
|
+
* include: ['status', 'customer'],
|
|
347
|
+
* sort: '-created_at',
|
|
348
|
+
* });
|
|
349
|
+
*/
|
|
350
|
+
list(query?: ListOrdersQuery): Promise<Page>;
|
|
351
|
+
/**
|
|
352
|
+
* Iterate every matching order across all pages (one request per page).
|
|
353
|
+
*
|
|
354
|
+
* for await (const order of jayik.orders.lazy({ take: 200 })) { ... }
|
|
355
|
+
*/
|
|
356
|
+
lazy(query?: ListOrdersQuery): AsyncGenerator<JayikRecord, void, undefined>;
|
|
357
|
+
/** Fetch one order by its numeric id. */
|
|
358
|
+
get(id: number, include?: Include): Promise<JayikRecord>;
|
|
359
|
+
/** Fetch one order by its tracking number, or null when none matches. */
|
|
360
|
+
findByTr(tr: string, include?: Include): Promise<JayikRecord | null>;
|
|
361
|
+
/** Create one order (status Pending). Returns the order record. */
|
|
362
|
+
create(order: CreateOrderInput): Promise<JayikRecord>;
|
|
363
|
+
/**
|
|
364
|
+
* Create 1–300 orders, all-or-none. The API returns no order data;
|
|
365
|
+
* look the orders up afterwards by their `tr`.
|
|
366
|
+
*/
|
|
367
|
+
createBatch(orders: CreateBatchOrderInput[]): Promise<void>;
|
|
368
|
+
/** Ask the API for an unused tracking number. */
|
|
369
|
+
generateTr(): Promise<string>;
|
|
370
|
+
trExists(tr: string): Promise<boolean>;
|
|
371
|
+
/** Cancel an order. Only while Pending, AwaitingPickup or PickupDelayed. */
|
|
372
|
+
cancel(tr: string): Promise<JayikRecord>;
|
|
373
|
+
/** Move a Pending order to AwaitingPickup. */
|
|
374
|
+
readyToPickup(tr: string): Promise<JayikRecord>;
|
|
375
|
+
/** Permanently delete an order by numeric id. Only while Pending. */
|
|
376
|
+
delete(id: number): Promise<JayikRecord>;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Pickup points. In a marketplace, create one warehouse per vendor and pass
|
|
381
|
+
* its id as `warehouse_id` when creating that vendor's orders.
|
|
382
|
+
*/
|
|
383
|
+
declare class Warehouses extends Resource {
|
|
384
|
+
list(take?: number, page?: number): Promise<Page>;
|
|
385
|
+
lazy(): AsyncGenerator<JayikRecord, void, undefined>;
|
|
386
|
+
get(id: string): Promise<JayikRecord>;
|
|
387
|
+
create(warehouse: CreateWarehouseInput): Promise<JayikRecord>;
|
|
388
|
+
/**
|
|
389
|
+
* Same fields as create, all optional. Always send governorate_id:
|
|
390
|
+
* omitting it clears the warehouse's governorate.
|
|
391
|
+
*/
|
|
392
|
+
update(id: string, warehouse: WarehouseInput): Promise<JayikRecord>;
|
|
393
|
+
delete(id: string): Promise<void>;
|
|
394
|
+
/** Set the warehouse used when an order is created without one. */
|
|
395
|
+
setDefault(id: string): Promise<void>;
|
|
396
|
+
/** One entry per day: id, warehouse_id, day, opens_at, closes_at, is_closed. */
|
|
397
|
+
businessHours(id: string): Promise<JayikRecord[]>;
|
|
398
|
+
/**
|
|
399
|
+
* Keyed by lowercase day name; days left out are unchanged.
|
|
400
|
+
*
|
|
401
|
+
* { sunday: { is_closed: false, opens_at: '09:00', closes_at: '17:00' },
|
|
402
|
+
* friday: { is_closed: true } }
|
|
403
|
+
*/
|
|
404
|
+
updateBusinessHours(id: string, hours: BusinessHoursInput): Promise<void>;
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
declare const SIGNATURE_HEADER = "X-Jayik-Signature";
|
|
408
|
+
declare const TIMESTAMP_HEADER = "X-Jayik-Timestamp";
|
|
409
|
+
/** The raw request body, before any JSON decoding. */
|
|
410
|
+
type RawBody = string | Uint8Array;
|
|
411
|
+
/** Node's `req.headers`, a fetch `Headers` object, or any plain header map. */
|
|
412
|
+
type HeadersLike = {
|
|
413
|
+
get(name: string): string | null;
|
|
414
|
+
} | Record<string, string | string[] | undefined>;
|
|
415
|
+
/**
|
|
416
|
+
* Jayik signs each webhook with HMAC-SHA256 over "{timestamp}.{raw body}"
|
|
417
|
+
* and sends it as "X-Jayik-Signature: sha256={hex}" next to
|
|
418
|
+
* "X-Jayik-Timestamp: {unix seconds}".
|
|
419
|
+
*/
|
|
420
|
+
declare class SignatureVerifier {
|
|
421
|
+
private readonly secret;
|
|
422
|
+
private readonly tolerance;
|
|
423
|
+
/**
|
|
424
|
+
* @param tolerance Maximum age in seconds; 0 disables the age check.
|
|
425
|
+
*/
|
|
426
|
+
constructor(secret: string | null | undefined, tolerance?: number);
|
|
427
|
+
sign(payload: RawBody, timestamp: number | string): string;
|
|
428
|
+
/** Throws InvalidSignatureError unless the payload was signed by Jayik. */
|
|
429
|
+
verify(payload: RawBody, signature: string | null | undefined, timestamp: string | null | undefined): void;
|
|
430
|
+
isValid(payload: RawBody, signature: string | null | undefined, timestamp: string | null | undefined): boolean;
|
|
431
|
+
/** Verify using a request's headers. */
|
|
432
|
+
verifyHeaders(payload: RawBody, headers: HeadersLike): void;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* A parsed webhook body: {"opration": "...", "data": {order record + driver}}.
|
|
437
|
+
* (The API spells the key "opration".)
|
|
438
|
+
*/
|
|
439
|
+
declare class WebhookEvent {
|
|
440
|
+
/** One of the WebhookOperation values. */
|
|
441
|
+
readonly operation: string;
|
|
442
|
+
/** The order record, plus a `driver` object. */
|
|
443
|
+
readonly order: JayikRecord;
|
|
444
|
+
/** The full decoded body. */
|
|
445
|
+
readonly payload: JayikRecord;
|
|
446
|
+
constructor(payload: unknown);
|
|
447
|
+
/** Parse a raw request body. Verify its signature first. */
|
|
448
|
+
static fromBody(body: RawBody): WebhookEvent;
|
|
449
|
+
is(operation: string): boolean;
|
|
450
|
+
get isCreated(): boolean;
|
|
451
|
+
get isUpdated(): boolean;
|
|
452
|
+
get isAssigned(): boolean;
|
|
453
|
+
get isDeleted(): boolean;
|
|
454
|
+
/** The order's tracking number. */
|
|
455
|
+
get tr(): string | null;
|
|
456
|
+
/** The order's status code, e.g. "Delivered" (see OrderStatus). */
|
|
457
|
+
get status(): string | null;
|
|
458
|
+
/** Driver id/name/phone; values are null unless enabled for the account. */
|
|
459
|
+
get driver(): JayikRecord;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
interface WebhookHandlerOptions {
|
|
463
|
+
/** Called for every verified webhook. Jayik expects a 2xx within 5 seconds, so hand slow work to a queue. */
|
|
464
|
+
onEvent: (event: WebhookEvent) => void | Promise<void>;
|
|
465
|
+
/** Called when `onEvent` throws (the request is answered with a 500). Defaults to console.error. */
|
|
466
|
+
onError?: (error: unknown) => void;
|
|
467
|
+
}
|
|
468
|
+
type IncomingRequest = IncomingMessage & {
|
|
469
|
+
body?: unknown;
|
|
470
|
+
rawBody?: unknown;
|
|
471
|
+
};
|
|
472
|
+
type WebhookHandler = (req: IncomingRequest, res: ServerResponse) => Promise<void>;
|
|
473
|
+
/**
|
|
474
|
+
* A request handler for `node:http`, Express, Connect and anything else that
|
|
475
|
+
* passes Node's (req, res). Rejects unsigned requests with a 401 and answers
|
|
476
|
+
* {"received": true} once `onEvent` has run.
|
|
477
|
+
*/
|
|
478
|
+
declare function createWebhookHandler(verifier: SignatureVerifier, options: WebhookHandlerOptions): WebhookHandler;
|
|
479
|
+
|
|
480
|
+
/** Manage where Jayik sends order events, and receive them. */
|
|
481
|
+
declare class Webhook extends Resource {
|
|
482
|
+
/**
|
|
483
|
+
* Current settings: `webhook` (URL), `secret` (its `value` is the signing
|
|
484
|
+
* secret, put it in JAYIK_WEBHOOK_SECRET) and `signature` (scheme details).
|
|
485
|
+
*/
|
|
486
|
+
get(): Promise<JayikRecord>;
|
|
487
|
+
/** The signing secret (whsec_...). */
|
|
488
|
+
secret(): Promise<string | null>;
|
|
489
|
+
/**
|
|
490
|
+
* Set the URL that receives events. Must be https://.
|
|
491
|
+
* Call get() afterwards if you need to confirm the saved value.
|
|
492
|
+
*/
|
|
493
|
+
set(url: string): Promise<JayikRecord>;
|
|
494
|
+
/** Stop receiving events. */
|
|
495
|
+
remove(): Promise<JayikRecord>;
|
|
496
|
+
/**
|
|
497
|
+
* Ask Jayik to send a test event to your URL: real data when `tr` is
|
|
498
|
+
* given, sample data otherwise. `operation` defaults to "created"
|
|
499
|
+
* (see WebhookOperation). Returns what was dispatched.
|
|
500
|
+
*/
|
|
501
|
+
test(tr?: string | null, operation?: string | null): Promise<JayikRecord>;
|
|
502
|
+
/** Re-send a `created` event for the order to your URL. */
|
|
503
|
+
redeliver(tr: string): Promise<JayikRecord>;
|
|
504
|
+
/** A verifier using the configured webhook secret and tolerance. */
|
|
505
|
+
get verifier(): SignatureVerifier;
|
|
506
|
+
/**
|
|
507
|
+
* Verify an incoming webhook and parse it. Throws InvalidSignatureError
|
|
508
|
+
* when it was not signed by Jayik.
|
|
509
|
+
*
|
|
510
|
+
* @param rawBody The request body exactly as received, before JSON decoding.
|
|
511
|
+
*/
|
|
512
|
+
constructEvent(rawBody: RawBody, headers: HeadersLike): WebhookEvent;
|
|
513
|
+
/**
|
|
514
|
+
* A (req, res) handler for node:http, Express and Connect that verifies
|
|
515
|
+
* the signature and calls you with the event.
|
|
516
|
+
*
|
|
517
|
+
* app.post('/jayik/webhook', jayik.webhook.handler(async (event) => { ... }));
|
|
518
|
+
*/
|
|
519
|
+
handler(onEvent: WebhookHandlerOptions['onEvent'] | WebhookHandlerOptions): WebhookHandler;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
declare class Jayik {
|
|
523
|
+
/** The underlying HTTP client, for endpoints this package does not wrap yet. */
|
|
524
|
+
readonly client: Client;
|
|
525
|
+
readonly account: Account;
|
|
526
|
+
readonly orders: Orders;
|
|
527
|
+
readonly warehouses: Warehouses;
|
|
528
|
+
readonly orderCategories: OrderCategories;
|
|
529
|
+
readonly governorates: Governorates;
|
|
530
|
+
readonly statuses: Statuses;
|
|
531
|
+
/** Product types used in order_items[].attribute_id. */
|
|
532
|
+
readonly attributes: Attributes;
|
|
533
|
+
readonly webhook: Webhook;
|
|
534
|
+
readonly apiKeys: ApiKeys;
|
|
535
|
+
/**
|
|
536
|
+
* @param config Options, or just the API key. Anything left out falls back
|
|
537
|
+
* to the JAYIK_* environment variables.
|
|
538
|
+
*/
|
|
539
|
+
constructor(config?: JayikConfig | string | Client);
|
|
540
|
+
/**
|
|
541
|
+
* A new instance that authenticates with another merchant's API key.
|
|
542
|
+
* Useful for marketplaces where each vendor has their own Jayik account.
|
|
543
|
+
*/
|
|
544
|
+
withKey(apiKey: string): Jayik;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
/** Stable status codes, found in an order's `status.name`. */
|
|
548
|
+
declare const OrderStatus: {
|
|
549
|
+
readonly PENDING: "Pending";
|
|
550
|
+
readonly AWAITING_PICKUP: "AwaitingPickup";
|
|
551
|
+
readonly PICKUP_DELAYED: "PickupDelayed";
|
|
552
|
+
readonly CANCELLED_BY_MERCHANT: "CancelledByMerchant";
|
|
553
|
+
readonly IN_TRANSIT: "InTransit";
|
|
554
|
+
readonly IN_DELIVERY_COMPANY_WAREHOUSE: "InDeliveryCompanyWarehouse";
|
|
555
|
+
readonly RECEIVED: "Received";
|
|
556
|
+
readonly HAND_OVER: "HandOver";
|
|
557
|
+
readonly DELAYED: "Delayed";
|
|
558
|
+
readonly RE_DELIVERY: "ReDelivery";
|
|
559
|
+
readonly DELIVERED: "Delivered";
|
|
560
|
+
readonly RETURNED: "Returned";
|
|
561
|
+
readonly RETURNED_TO_COMPANY: "ReturnedToCompany";
|
|
562
|
+
readonly ON_THE_WAY_TO_MERCHANT_WAREHOUSE: "OnTheWayToMerchantWarehouse";
|
|
563
|
+
readonly RETURNED_TO_MAIN_WAREHOUSE: "ReturnedToMainWarehouse";
|
|
564
|
+
readonly CANCELLED: "Cancelled";
|
|
565
|
+
};
|
|
566
|
+
type OrderStatus = (typeof OrderStatus)[keyof typeof OrderStatus];
|
|
567
|
+
/** Statuses in which the merchant may still cancel the order. */
|
|
568
|
+
declare const CANCELLABLE_STATUSES: readonly OrderStatus[];
|
|
569
|
+
declare const DeliveryType: {
|
|
570
|
+
readonly NORMAL: 0;
|
|
571
|
+
/** Express ("fawri"). May require district_id on the order. */
|
|
572
|
+
readonly FAWRI: 1;
|
|
573
|
+
};
|
|
574
|
+
type DeliveryType = (typeof DeliveryType)[keyof typeof DeliveryType];
|
|
575
|
+
/** Values of the `opration` key in webhook bodies. */
|
|
576
|
+
declare const WebhookOperation: {
|
|
577
|
+
readonly CREATED: "created";
|
|
578
|
+
readonly UPDATED: "updated";
|
|
579
|
+
readonly ASSIGNED: "assigned";
|
|
580
|
+
readonly DELETED: "deleted";
|
|
581
|
+
readonly RESTORED: "restored";
|
|
582
|
+
readonly FORCE_DELETED: "forceDeleted";
|
|
583
|
+
};
|
|
584
|
+
type WebhookOperation = (typeof WebhookOperation)[keyof typeof WebhookOperation];
|
|
585
|
+
|
|
586
|
+
export { Account, ApiKeys, Attributes, AuthenticationError, CANCELLABLE_STATUSES, Client, ConflictError, ConnectionError, DeliveryType, Governorates, InvalidSignatureError, Jayik, JayikError, NotFoundError, OrderCategories, OrderStatus, Orders, Page, PermissionDeniedError, RateLimitError, RequestError, SIGNATURE_HEADER, SignatureVerifier, Statuses, TIMESTAMP_HEADER, UnprocessableError, ValidationError, Warehouses, Webhook, WebhookEvent, WebhookOperation, buildQueryString, createWebhookHandler, formatDate, normalizeQuery, unwrap };
|
|
587
|
+
export type { ApiResponse, BusinessHoursInput, CreateBatchOrderInput, CreateOrderInput, CreateWarehouseInput, DayName, HeadersLike, Include, JayikConfig, JayikRecord, ListOrdersQuery, OrderFilter, OrderInclude, OrderItemInput, Query, QueryValue, RawBody, ResolvedConfig, WarehouseInput, WebhookHandler, WebhookHandlerOptions };
|