@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.js
ADDED
|
@@ -0,0 +1,895 @@
|
|
|
1
|
+
// src/errors.ts
|
|
2
|
+
var JayikError = class extends Error {
|
|
3
|
+
constructor(message, options) {
|
|
4
|
+
super(message, options);
|
|
5
|
+
this.name = new.target.name;
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
var ConnectionError = class extends JayikError {
|
|
9
|
+
};
|
|
10
|
+
var InvalidSignatureError = class extends JayikError {
|
|
11
|
+
};
|
|
12
|
+
var RequestError = class _RequestError extends JayikError {
|
|
13
|
+
/** HTTP status. */
|
|
14
|
+
status;
|
|
15
|
+
response;
|
|
16
|
+
/** Field => messages, filled for validation failures. */
|
|
17
|
+
errors = {};
|
|
18
|
+
constructor(message, response) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.status = response.status;
|
|
21
|
+
this.response = response;
|
|
22
|
+
}
|
|
23
|
+
static fromResponse(response) {
|
|
24
|
+
const body = response.body;
|
|
25
|
+
let message = body !== null && typeof body === "object" ? body.message : void 0;
|
|
26
|
+
const errors = {};
|
|
27
|
+
if (message !== null && typeof message === "object") {
|
|
28
|
+
for (const [field, messages] of Object.entries(message)) {
|
|
29
|
+
errors[field] = (Array.isArray(messages) ? messages : [messages]).map(String);
|
|
30
|
+
}
|
|
31
|
+
message = Object.values(errors)[0]?.[0] ?? "The given data was invalid.";
|
|
32
|
+
}
|
|
33
|
+
if (typeof message !== "string" || message === "") {
|
|
34
|
+
message = `Jayik API request failed with status ${response.status}.`;
|
|
35
|
+
}
|
|
36
|
+
const ErrorClass = STATUS_MAP[response.status] ?? _RequestError;
|
|
37
|
+
const error = new ErrorClass(message, response);
|
|
38
|
+
error.errors = errors;
|
|
39
|
+
return error;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var ValidationError = class extends RequestError {
|
|
43
|
+
};
|
|
44
|
+
var AuthenticationError = class extends RequestError {
|
|
45
|
+
};
|
|
46
|
+
var PermissionDeniedError = class extends RequestError {
|
|
47
|
+
};
|
|
48
|
+
var NotFoundError = class extends RequestError {
|
|
49
|
+
};
|
|
50
|
+
var ConflictError = class extends RequestError {
|
|
51
|
+
};
|
|
52
|
+
var UnprocessableError = class extends RequestError {
|
|
53
|
+
};
|
|
54
|
+
var RateLimitError = class extends RequestError {
|
|
55
|
+
/** Seconds to wait before retrying, from the Retry-After header. */
|
|
56
|
+
get retryAfter() {
|
|
57
|
+
const value = this.response.headers.get("Retry-After");
|
|
58
|
+
return value !== null && /^\s*\d+(\.\d+)?\s*$/.test(value) ? Math.trunc(Number(value)) : null;
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
var STATUS_MAP = {
|
|
62
|
+
400: ValidationError,
|
|
63
|
+
401: AuthenticationError,
|
|
64
|
+
403: PermissionDeniedError,
|
|
65
|
+
404: NotFoundError,
|
|
66
|
+
409: ConflictError,
|
|
67
|
+
422: UnprocessableError,
|
|
68
|
+
429: RateLimitError
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
// src/client.ts
|
|
72
|
+
function envInt(name, fallback) {
|
|
73
|
+
const value = Number.parseInt(process.env[name] ?? "", 10);
|
|
74
|
+
return Number.isNaN(value) ? fallback : value;
|
|
75
|
+
}
|
|
76
|
+
function resolveConfig(config = {}) {
|
|
77
|
+
return {
|
|
78
|
+
apiKey: config.apiKey ?? process.env.JAYIK_API_KEY,
|
|
79
|
+
baseUrl: config.baseUrl ?? process.env.JAYIK_BASE_URL ?? "https://api.jayik.app/api/merchant",
|
|
80
|
+
timeout: config.timeout ?? envInt("JAYIK_TIMEOUT", 30),
|
|
81
|
+
rateLimit: {
|
|
82
|
+
retries: config.rateLimit?.retries ?? envInt("JAYIK_RATE_LIMIT_RETRIES", 2),
|
|
83
|
+
maxWait: config.rateLimit?.maxWait ?? envInt("JAYIK_RATE_LIMIT_MAX_WAIT", 30)
|
|
84
|
+
},
|
|
85
|
+
webhook: {
|
|
86
|
+
secret: config.webhook?.secret ?? process.env.JAYIK_WEBHOOK_SECRET,
|
|
87
|
+
tolerance: config.webhook?.tolerance ?? envInt("JAYIK_WEBHOOK_TOLERANCE", 300)
|
|
88
|
+
},
|
|
89
|
+
fetch: config.fetch,
|
|
90
|
+
sleep: config.sleep
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
function isPlainObject(value) {
|
|
94
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) && !(value instanceof Date);
|
|
95
|
+
}
|
|
96
|
+
function normalizeQuery(query) {
|
|
97
|
+
const out = {};
|
|
98
|
+
for (const [key, raw] of Object.entries(query)) {
|
|
99
|
+
let value = raw;
|
|
100
|
+
if (value === null || value === void 0) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (typeof value === "boolean") {
|
|
104
|
+
value = value ? 1 : 0;
|
|
105
|
+
} else if (Array.isArray(value)) {
|
|
106
|
+
value = value.join(",");
|
|
107
|
+
if (value === "") {
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
} else if (isPlainObject(value)) {
|
|
111
|
+
value = normalizeQuery(value);
|
|
112
|
+
if (Object.keys(value).length === 0) {
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
out[key] = value;
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
function appendQuery(params, value, key) {
|
|
121
|
+
if (isPlainObject(value)) {
|
|
122
|
+
for (const [child, childValue] of Object.entries(value)) {
|
|
123
|
+
appendQuery(params, childValue, `${key}[${child}]`);
|
|
124
|
+
}
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
params.append(key, String(value));
|
|
128
|
+
}
|
|
129
|
+
function buildQueryString(query) {
|
|
130
|
+
const params = new URLSearchParams();
|
|
131
|
+
for (const [key, value] of Object.entries(normalizeQuery(query))) {
|
|
132
|
+
appendQuery(params, value, key);
|
|
133
|
+
}
|
|
134
|
+
return params.toString();
|
|
135
|
+
}
|
|
136
|
+
var pad = (value) => String(value).padStart(2, "0");
|
|
137
|
+
function formatDate(date) {
|
|
138
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
139
|
+
}
|
|
140
|
+
function normalizeBody(value) {
|
|
141
|
+
if (value instanceof Date) {
|
|
142
|
+
return formatDate(value);
|
|
143
|
+
}
|
|
144
|
+
if (Array.isArray(value)) {
|
|
145
|
+
return value.map(normalizeBody);
|
|
146
|
+
}
|
|
147
|
+
if (isPlainObject(value)) {
|
|
148
|
+
return Object.fromEntries(Object.entries(value).map(([key, child]) => [key, normalizeBody(child)]));
|
|
149
|
+
}
|
|
150
|
+
return value;
|
|
151
|
+
}
|
|
152
|
+
function unwrap(json) {
|
|
153
|
+
if (isPlainObject(json) && "data" in json && "message" in json && typeof json.status === "boolean") {
|
|
154
|
+
return json.data;
|
|
155
|
+
}
|
|
156
|
+
return json;
|
|
157
|
+
}
|
|
158
|
+
var Client = class _Client {
|
|
159
|
+
config;
|
|
160
|
+
constructor(config = {}) {
|
|
161
|
+
this.config = resolveConfig(config);
|
|
162
|
+
}
|
|
163
|
+
withKey(apiKey) {
|
|
164
|
+
return new _Client({ ...this.config, apiKey });
|
|
165
|
+
}
|
|
166
|
+
get(uri, query = {}) {
|
|
167
|
+
return this.request("GET", uri, query);
|
|
168
|
+
}
|
|
169
|
+
post(uri, body = {}) {
|
|
170
|
+
return this.request("POST", uri, {}, body);
|
|
171
|
+
}
|
|
172
|
+
put(uri, body = {}) {
|
|
173
|
+
return this.request("PUT", uri, {}, body);
|
|
174
|
+
}
|
|
175
|
+
delete(uri) {
|
|
176
|
+
return this.request("DELETE", uri);
|
|
177
|
+
}
|
|
178
|
+
/** Send a request and return the decoded, unwrapped payload. */
|
|
179
|
+
async request(method, uri, query = {}, body) {
|
|
180
|
+
return unwrap((await this.send(method, uri, query, body)).body);
|
|
181
|
+
}
|
|
182
|
+
/** Send a request and return the raw response (already checked for errors). */
|
|
183
|
+
async send(method, uri, query = {}, body) {
|
|
184
|
+
const { apiKey, timeout, rateLimit } = this.config;
|
|
185
|
+
if (typeof apiKey !== "string" || apiKey === "") {
|
|
186
|
+
throw new JayikError("Jayik API key is not configured. Set JAYIK_API_KEY or use jayik.withKey().");
|
|
187
|
+
}
|
|
188
|
+
const queryString = buildQueryString(query);
|
|
189
|
+
const url = `${this.config.baseUrl.replace(/\/+$/, "")}/${uri.replace(/^\/+/, "")}` + (queryString ? `?${queryString}` : "");
|
|
190
|
+
const headers = { "X-API-KEY": apiKey, Accept: "application/json" };
|
|
191
|
+
let payload;
|
|
192
|
+
if (body !== void 0) {
|
|
193
|
+
headers["Content-Type"] = "application/json";
|
|
194
|
+
payload = JSON.stringify(normalizeBody(body));
|
|
195
|
+
}
|
|
196
|
+
const retries = Math.max(0, rateLimit.retries);
|
|
197
|
+
const maxWait = Math.max(0, rateLimit.maxWait);
|
|
198
|
+
const doFetch = this.config.fetch ?? globalThis.fetch;
|
|
199
|
+
for (let attempt = 0; ; attempt++) {
|
|
200
|
+
const response = await this.fetchOnce(doFetch, url, {
|
|
201
|
+
method,
|
|
202
|
+
headers,
|
|
203
|
+
body: payload,
|
|
204
|
+
signal: timeout > 0 ? AbortSignal.timeout(timeout * 1e3) : void 0
|
|
205
|
+
});
|
|
206
|
+
if (response.status === 429 && attempt < retries) {
|
|
207
|
+
const wait = Math.max(1, Number.parseInt(response.headers.get("Retry-After") ?? "", 10) || 0);
|
|
208
|
+
if (wait <= maxWait) {
|
|
209
|
+
await this.sleep(wait);
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (response.status < 200 || response.status >= 300) {
|
|
214
|
+
throw RequestError.fromResponse(response);
|
|
215
|
+
}
|
|
216
|
+
return response;
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
async fetchOnce(doFetch, url, init) {
|
|
220
|
+
try {
|
|
221
|
+
const response = await doFetch(url, init);
|
|
222
|
+
const text = await response.text();
|
|
223
|
+
let body = null;
|
|
224
|
+
if (text !== "") {
|
|
225
|
+
try {
|
|
226
|
+
body = JSON.parse(text);
|
|
227
|
+
} catch {
|
|
228
|
+
body = null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return { status: response.status, headers: response.headers, body, text };
|
|
232
|
+
} catch (error) {
|
|
233
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
234
|
+
throw new ConnectionError(`Jayik API request failed: ${reason}`, { cause: error });
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
async sleep(seconds) {
|
|
238
|
+
if (this.config.sleep) {
|
|
239
|
+
await this.config.sleep(seconds);
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
await new Promise((resolve) => setTimeout(resolve, seconds * 1e3));
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
|
|
246
|
+
// src/page.ts
|
|
247
|
+
var Page = class {
|
|
248
|
+
/** The raw page object as returned by the API. */
|
|
249
|
+
raw;
|
|
250
|
+
constructor(raw) {
|
|
251
|
+
this.raw = raw !== null && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
252
|
+
}
|
|
253
|
+
get items() {
|
|
254
|
+
const data = this.raw.data;
|
|
255
|
+
if (Array.isArray(data)) {
|
|
256
|
+
return data;
|
|
257
|
+
}
|
|
258
|
+
return data !== null && typeof data === "object" ? Object.values(data) : [];
|
|
259
|
+
}
|
|
260
|
+
get currentPage() {
|
|
261
|
+
return Number(this.raw.current_page ?? 1);
|
|
262
|
+
}
|
|
263
|
+
get perPage() {
|
|
264
|
+
return Number(this.raw.per_page ?? this.items.length);
|
|
265
|
+
}
|
|
266
|
+
/** Null when the list was requested with `simple` (no total count). */
|
|
267
|
+
get total() {
|
|
268
|
+
return this.raw.total != null ? Number(this.raw.total) : null;
|
|
269
|
+
}
|
|
270
|
+
get lastPage() {
|
|
271
|
+
return this.raw.last_page != null ? Number(this.raw.last_page) : null;
|
|
272
|
+
}
|
|
273
|
+
get hasMorePages() {
|
|
274
|
+
const last = this.lastPage;
|
|
275
|
+
if (last !== null) {
|
|
276
|
+
return this.currentPage < last;
|
|
277
|
+
}
|
|
278
|
+
if ("next_page_url" in this.raw) {
|
|
279
|
+
return this.raw.next_page_url !== null;
|
|
280
|
+
}
|
|
281
|
+
return this.perPage > 0 && this.items.length >= this.perPage;
|
|
282
|
+
}
|
|
283
|
+
get isEmpty() {
|
|
284
|
+
return this.items.length === 0;
|
|
285
|
+
}
|
|
286
|
+
/** Number of items on this page. */
|
|
287
|
+
get length() {
|
|
288
|
+
return this.items.length;
|
|
289
|
+
}
|
|
290
|
+
[Symbol.iterator]() {
|
|
291
|
+
return this.items[Symbol.iterator]();
|
|
292
|
+
}
|
|
293
|
+
toJSON() {
|
|
294
|
+
return this.raw;
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
// src/resources/resource.ts
|
|
299
|
+
var Resource = class {
|
|
300
|
+
constructor(client) {
|
|
301
|
+
this.client = client;
|
|
302
|
+
}
|
|
303
|
+
client;
|
|
304
|
+
async paginate(uri, query = {}) {
|
|
305
|
+
return new Page(await this.client.get(uri, query));
|
|
306
|
+
}
|
|
307
|
+
/** Walk every page lazily, one request per page. */
|
|
308
|
+
async *lazyPages(uri, query = {}) {
|
|
309
|
+
const current = { ...query, take: query.take ?? 100 };
|
|
310
|
+
let pageNumber = Math.trunc(Number(query.page ?? 1)) || 1;
|
|
311
|
+
let page;
|
|
312
|
+
do {
|
|
313
|
+
page = await this.paginate(uri, { ...current, page: pageNumber });
|
|
314
|
+
yield* page.items;
|
|
315
|
+
pageNumber++;
|
|
316
|
+
} while (!page.isEmpty && page.hasMorePages);
|
|
317
|
+
}
|
|
318
|
+
async allPages(uri, query = {}) {
|
|
319
|
+
const items = [];
|
|
320
|
+
for await (const item of this.lazyPages(uri, query)) {
|
|
321
|
+
items.push(item);
|
|
322
|
+
}
|
|
323
|
+
return items;
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
// src/resources/misc.ts
|
|
328
|
+
var Account = class extends Resource {
|
|
329
|
+
/** The merchant behind the API key. */
|
|
330
|
+
details() {
|
|
331
|
+
return this.client.get("auth/details");
|
|
332
|
+
}
|
|
333
|
+
async permissions() {
|
|
334
|
+
return (await this.details()).permissions ?? [];
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
var OrderCategories = class extends Resource {
|
|
338
|
+
list(take = 10, page = 1) {
|
|
339
|
+
return this.paginate("v2/order-categories", { take, page });
|
|
340
|
+
}
|
|
341
|
+
lazy() {
|
|
342
|
+
return this.lazyPages("v2/order-categories");
|
|
343
|
+
}
|
|
344
|
+
get(id) {
|
|
345
|
+
return this.client.get(`v2/order-categories/${id}`);
|
|
346
|
+
}
|
|
347
|
+
create(name) {
|
|
348
|
+
return this.client.post("v2/order-categories", { name });
|
|
349
|
+
}
|
|
350
|
+
update(id, name) {
|
|
351
|
+
return this.client.put(`v2/order-categories/${id}`, { name });
|
|
352
|
+
}
|
|
353
|
+
async delete(id) {
|
|
354
|
+
await this.client.delete(`v2/order-categories/${id}`);
|
|
355
|
+
}
|
|
356
|
+
/** Set the category used as the account's default. */
|
|
357
|
+
async setDefault(id) {
|
|
358
|
+
await this.client.put("v2/order-categories/default", { default_order_category_id: id });
|
|
359
|
+
}
|
|
360
|
+
};
|
|
361
|
+
var Governorates = class extends Resource {
|
|
362
|
+
list(take = 10, page = 1) {
|
|
363
|
+
return this.paginate("v2/governorates", { take, page });
|
|
364
|
+
}
|
|
365
|
+
/** Every governorate (id, name, number). Reference data: cache it on your side. */
|
|
366
|
+
all() {
|
|
367
|
+
return this.allPages("v2/governorates", { take: 50 });
|
|
368
|
+
}
|
|
369
|
+
get(id) {
|
|
370
|
+
return this.client.get(`v2/governorates/${id}`);
|
|
371
|
+
}
|
|
372
|
+
};
|
|
373
|
+
var Statuses = class extends Resource {
|
|
374
|
+
list(take = 10, page = 1) {
|
|
375
|
+
return this.paginate("v2/statuses", { take, page });
|
|
376
|
+
}
|
|
377
|
+
/**
|
|
378
|
+
* Every order status. `name` is the stable code (see OrderStatus);
|
|
379
|
+
* ids are UUIDs. Reference data: cache it on your side.
|
|
380
|
+
*/
|
|
381
|
+
all() {
|
|
382
|
+
return this.allPages("v2/statuses", { take: 50 });
|
|
383
|
+
}
|
|
384
|
+
get(id) {
|
|
385
|
+
return this.client.get(`v2/statuses/${id}`);
|
|
386
|
+
}
|
|
387
|
+
};
|
|
388
|
+
var Attributes = class extends Resource {
|
|
389
|
+
list(take = 15, page = 1) {
|
|
390
|
+
return this.paginate("v2/attributes", { take, page });
|
|
391
|
+
}
|
|
392
|
+
all() {
|
|
393
|
+
return this.allPages("v2/attributes");
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
var ApiKeys = class extends Resource {
|
|
397
|
+
/** Keys without their values (values are only shown on create/regenerate). */
|
|
398
|
+
list(take = 10, page = 1) {
|
|
399
|
+
return this.paginate("v2/api-keys", { take, page });
|
|
400
|
+
}
|
|
401
|
+
get(id) {
|
|
402
|
+
return this.client.get(`v2/api-keys/${id}`);
|
|
403
|
+
}
|
|
404
|
+
/**
|
|
405
|
+
* Create a key. The `key` field of the result is shown only this once:
|
|
406
|
+
* store it securely.
|
|
407
|
+
*/
|
|
408
|
+
create(description = null) {
|
|
409
|
+
return this.client.post("v2/api-keys", { description });
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Issue a new value for a key. The old value stops working immediately;
|
|
413
|
+
* the new one is in the result's `key` field, shown only this once.
|
|
414
|
+
*/
|
|
415
|
+
regenerate(id) {
|
|
416
|
+
return this.client.post("v2/api-keys/regenerate", { id });
|
|
417
|
+
}
|
|
418
|
+
/** Switch a key on or off. Pass a description to change it too. */
|
|
419
|
+
update(id, active, description) {
|
|
420
|
+
const body = { active: active ? 1 : 0 };
|
|
421
|
+
if (description !== void 0 && description !== null) {
|
|
422
|
+
body.description = description;
|
|
423
|
+
}
|
|
424
|
+
return this.client.put(`v2/api-keys/${id}`, body);
|
|
425
|
+
}
|
|
426
|
+
delete(id) {
|
|
427
|
+
return this.client.delete(`v2/api-keys/${id}`);
|
|
428
|
+
}
|
|
429
|
+
};
|
|
430
|
+
|
|
431
|
+
// src/resources/orders.ts
|
|
432
|
+
var Orders = class extends Resource {
|
|
433
|
+
/**
|
|
434
|
+
* List orders.
|
|
435
|
+
*
|
|
436
|
+
* await jayik.orders.list({
|
|
437
|
+
* filter: { warehouse_id: id, status_id: [a, b] },
|
|
438
|
+
* include: ['status', 'customer'],
|
|
439
|
+
* sort: '-created_at',
|
|
440
|
+
* });
|
|
441
|
+
*/
|
|
442
|
+
list(query = {}) {
|
|
443
|
+
return this.paginate("v2/orders", query);
|
|
444
|
+
}
|
|
445
|
+
/**
|
|
446
|
+
* Iterate every matching order across all pages (one request per page).
|
|
447
|
+
*
|
|
448
|
+
* for await (const order of jayik.orders.lazy({ take: 200 })) { ... }
|
|
449
|
+
*/
|
|
450
|
+
lazy(query = {}) {
|
|
451
|
+
return this.lazyPages("v2/orders", query);
|
|
452
|
+
}
|
|
453
|
+
/** Fetch one order by its numeric id. */
|
|
454
|
+
get(id, include = []) {
|
|
455
|
+
return this.client.get(`v2/orders/${id}`, { include });
|
|
456
|
+
}
|
|
457
|
+
/** Fetch one order by its tracking number, or null when none matches. */
|
|
458
|
+
async findByTr(tr, include = []) {
|
|
459
|
+
const page = await this.list({ filter: { tr }, include, take: 1, simple: true });
|
|
460
|
+
return page.items[0] ?? null;
|
|
461
|
+
}
|
|
462
|
+
/** Create one order (status Pending). Returns the order record. */
|
|
463
|
+
create(order) {
|
|
464
|
+
return this.client.post("v2/orders", order);
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Create 1–300 orders, all-or-none. The API returns no order data;
|
|
468
|
+
* look the orders up afterwards by their `tr`.
|
|
469
|
+
*/
|
|
470
|
+
async createBatch(orders) {
|
|
471
|
+
await this.client.post("v2/orders/batch", { orders });
|
|
472
|
+
}
|
|
473
|
+
/** Ask the API for an unused tracking number. */
|
|
474
|
+
async generateTr() {
|
|
475
|
+
return String((await this.client.get("v2/orders/generate-tr")).tr_code);
|
|
476
|
+
}
|
|
477
|
+
async trExists(tr) {
|
|
478
|
+
return Boolean((await this.client.get(`v2/orders/tr-exists/${encodeURIComponent(tr)}`))?.exists);
|
|
479
|
+
}
|
|
480
|
+
/** Cancel an order. Only while Pending, AwaitingPickup or PickupDelayed. */
|
|
481
|
+
cancel(tr) {
|
|
482
|
+
return this.client.put("v2/orders/cancel", { tr });
|
|
483
|
+
}
|
|
484
|
+
/** Move a Pending order to AwaitingPickup. */
|
|
485
|
+
readyToPickup(tr) {
|
|
486
|
+
return this.client.put("v2/orders/ready-to-pickup", { tr });
|
|
487
|
+
}
|
|
488
|
+
/** Permanently delete an order by numeric id. Only while Pending. */
|
|
489
|
+
delete(id) {
|
|
490
|
+
return this.client.delete(`v2/orders/${id}`);
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
|
|
494
|
+
// src/resources/warehouses.ts
|
|
495
|
+
var Warehouses = class extends Resource {
|
|
496
|
+
list(take = 15, page = 1) {
|
|
497
|
+
return this.paginate("v2/warehouses", { take, page });
|
|
498
|
+
}
|
|
499
|
+
lazy() {
|
|
500
|
+
return this.lazyPages("v2/warehouses");
|
|
501
|
+
}
|
|
502
|
+
get(id) {
|
|
503
|
+
return this.client.get(`v2/warehouses/${id}`);
|
|
504
|
+
}
|
|
505
|
+
create(warehouse) {
|
|
506
|
+
return this.client.post("v2/warehouses", warehouse);
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Same fields as create, all optional. Always send governorate_id:
|
|
510
|
+
* omitting it clears the warehouse's governorate.
|
|
511
|
+
*/
|
|
512
|
+
update(id, warehouse) {
|
|
513
|
+
return this.client.put(`v2/warehouses/${id}`, warehouse);
|
|
514
|
+
}
|
|
515
|
+
async delete(id) {
|
|
516
|
+
await this.client.delete(`v2/warehouses/${id}`);
|
|
517
|
+
}
|
|
518
|
+
/** Set the warehouse used when an order is created without one. */
|
|
519
|
+
async setDefault(id) {
|
|
520
|
+
await this.client.put("v2/warehouses/default", { default_warehouse_id: id });
|
|
521
|
+
}
|
|
522
|
+
/** One entry per day: id, warehouse_id, day, opens_at, closes_at, is_closed. */
|
|
523
|
+
businessHours(id) {
|
|
524
|
+
return this.client.get(`v2/warehouses/${id}/business-hours`);
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Keyed by lowercase day name; days left out are unchanged.
|
|
528
|
+
*
|
|
529
|
+
* { sunday: { is_closed: false, opens_at: '09:00', closes_at: '17:00' },
|
|
530
|
+
* friday: { is_closed: true } }
|
|
531
|
+
*/
|
|
532
|
+
async updateBusinessHours(id, hours) {
|
|
533
|
+
await this.client.put(`v2/warehouses/${id}/business-hours`, { business_hours: hours });
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
// src/constants.ts
|
|
538
|
+
var OrderStatus = {
|
|
539
|
+
PENDING: "Pending",
|
|
540
|
+
AWAITING_PICKUP: "AwaitingPickup",
|
|
541
|
+
PICKUP_DELAYED: "PickupDelayed",
|
|
542
|
+
CANCELLED_BY_MERCHANT: "CancelledByMerchant",
|
|
543
|
+
IN_TRANSIT: "InTransit",
|
|
544
|
+
IN_DELIVERY_COMPANY_WAREHOUSE: "InDeliveryCompanyWarehouse",
|
|
545
|
+
RECEIVED: "Received",
|
|
546
|
+
HAND_OVER: "HandOver",
|
|
547
|
+
DELAYED: "Delayed",
|
|
548
|
+
RE_DELIVERY: "ReDelivery",
|
|
549
|
+
DELIVERED: "Delivered",
|
|
550
|
+
RETURNED: "Returned",
|
|
551
|
+
RETURNED_TO_COMPANY: "ReturnedToCompany",
|
|
552
|
+
ON_THE_WAY_TO_MERCHANT_WAREHOUSE: "OnTheWayToMerchantWarehouse",
|
|
553
|
+
RETURNED_TO_MAIN_WAREHOUSE: "ReturnedToMainWarehouse",
|
|
554
|
+
CANCELLED: "Cancelled"
|
|
555
|
+
};
|
|
556
|
+
var CANCELLABLE_STATUSES = [
|
|
557
|
+
OrderStatus.PENDING,
|
|
558
|
+
OrderStatus.AWAITING_PICKUP,
|
|
559
|
+
OrderStatus.PICKUP_DELAYED
|
|
560
|
+
];
|
|
561
|
+
var DeliveryType = {
|
|
562
|
+
NORMAL: 0,
|
|
563
|
+
/** Express ("fawri"). May require district_id on the order. */
|
|
564
|
+
FAWRI: 1
|
|
565
|
+
};
|
|
566
|
+
var WebhookOperation = {
|
|
567
|
+
CREATED: "created",
|
|
568
|
+
UPDATED: "updated",
|
|
569
|
+
ASSIGNED: "assigned",
|
|
570
|
+
DELETED: "deleted",
|
|
571
|
+
RESTORED: "restored",
|
|
572
|
+
FORCE_DELETED: "forceDeleted"
|
|
573
|
+
};
|
|
574
|
+
|
|
575
|
+
// src/webhooks/event.ts
|
|
576
|
+
var WebhookEvent = class _WebhookEvent {
|
|
577
|
+
/** One of the WebhookOperation values. */
|
|
578
|
+
operation;
|
|
579
|
+
/** The order record, plus a `driver` object. */
|
|
580
|
+
order;
|
|
581
|
+
/** The full decoded body. */
|
|
582
|
+
payload;
|
|
583
|
+
constructor(payload) {
|
|
584
|
+
this.payload = payload !== null && typeof payload === "object" ? payload : {};
|
|
585
|
+
this.operation = String(this.payload.opration ?? this.payload.operation ?? "");
|
|
586
|
+
const data = this.payload.data;
|
|
587
|
+
this.order = data !== null && typeof data === "object" ? data : {};
|
|
588
|
+
}
|
|
589
|
+
/** Parse a raw request body. Verify its signature first. */
|
|
590
|
+
static fromBody(body) {
|
|
591
|
+
const text = typeof body === "string" ? body : Buffer.from(body).toString("utf8");
|
|
592
|
+
try {
|
|
593
|
+
return new _WebhookEvent(JSON.parse(text));
|
|
594
|
+
} catch {
|
|
595
|
+
return new _WebhookEvent({});
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
is(operation) {
|
|
599
|
+
return this.operation === operation;
|
|
600
|
+
}
|
|
601
|
+
get isCreated() {
|
|
602
|
+
return this.is(WebhookOperation.CREATED);
|
|
603
|
+
}
|
|
604
|
+
get isUpdated() {
|
|
605
|
+
return this.is(WebhookOperation.UPDATED);
|
|
606
|
+
}
|
|
607
|
+
get isAssigned() {
|
|
608
|
+
return this.is(WebhookOperation.ASSIGNED);
|
|
609
|
+
}
|
|
610
|
+
get isDeleted() {
|
|
611
|
+
return this.is(WebhookOperation.DELETED) || this.is(WebhookOperation.FORCE_DELETED);
|
|
612
|
+
}
|
|
613
|
+
/** The order's tracking number. */
|
|
614
|
+
get tr() {
|
|
615
|
+
return this.order.tr != null ? String(this.order.tr) : null;
|
|
616
|
+
}
|
|
617
|
+
/** The order's status code, e.g. "Delivered" (see OrderStatus). */
|
|
618
|
+
get status() {
|
|
619
|
+
const status = this.order.status;
|
|
620
|
+
if (status !== null && typeof status === "object") {
|
|
621
|
+
return status.name ?? null;
|
|
622
|
+
}
|
|
623
|
+
return typeof status === "string" ? status : null;
|
|
624
|
+
}
|
|
625
|
+
/** Driver id/name/phone; values are null unless enabled for the account. */
|
|
626
|
+
get driver() {
|
|
627
|
+
const driver = this.order.driver;
|
|
628
|
+
return driver !== null && typeof driver === "object" ? driver : {};
|
|
629
|
+
}
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
// src/webhooks/handler.ts
|
|
633
|
+
var isRaw = (value) => typeof value === "string" || value instanceof Uint8Array;
|
|
634
|
+
async function readRawBody(req) {
|
|
635
|
+
if (isRaw(req.rawBody)) {
|
|
636
|
+
return req.rawBody;
|
|
637
|
+
}
|
|
638
|
+
if (isRaw(req.body)) {
|
|
639
|
+
return req.body;
|
|
640
|
+
}
|
|
641
|
+
if (req.body !== void 0 || req.readableEnded) {
|
|
642
|
+
return null;
|
|
643
|
+
}
|
|
644
|
+
const chunks = [];
|
|
645
|
+
for await (const chunk of req) {
|
|
646
|
+
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
|
647
|
+
}
|
|
648
|
+
return Buffer.concat(chunks);
|
|
649
|
+
}
|
|
650
|
+
function respond(res, status, body) {
|
|
651
|
+
res.statusCode = status;
|
|
652
|
+
res.setHeader("Content-Type", "application/json");
|
|
653
|
+
res.end(JSON.stringify(body));
|
|
654
|
+
}
|
|
655
|
+
function createWebhookHandler(verifier, options) {
|
|
656
|
+
return async (req, res) => {
|
|
657
|
+
if (req.method !== "POST") {
|
|
658
|
+
res.setHeader("Allow", "POST");
|
|
659
|
+
respond(res, 405, { message: "Method not allowed." });
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
const body = await readRawBody(req);
|
|
663
|
+
if (body === null) {
|
|
664
|
+
respond(res, 500, {
|
|
665
|
+
message: "The raw request body is not available. Mount the Jayik webhook handler before any JSON body parser."
|
|
666
|
+
});
|
|
667
|
+
return;
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
verifier.verifyHeaders(body, req.headers);
|
|
671
|
+
} catch (error) {
|
|
672
|
+
if (error instanceof InvalidSignatureError) {
|
|
673
|
+
respond(res, 401, { message: "Invalid signature." });
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
throw error;
|
|
677
|
+
}
|
|
678
|
+
try {
|
|
679
|
+
await options.onEvent(WebhookEvent.fromBody(body));
|
|
680
|
+
} catch (error) {
|
|
681
|
+
(options.onError ?? console.error)(error);
|
|
682
|
+
respond(res, 500, { message: "Webhook handler failed." });
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
respond(res, 200, { received: true });
|
|
686
|
+
};
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
// src/webhooks/signature.ts
|
|
690
|
+
import { createHmac, timingSafeEqual } from "crypto";
|
|
691
|
+
var SIGNATURE_HEADER = "X-Jayik-Signature";
|
|
692
|
+
var TIMESTAMP_HEADER = "X-Jayik-Timestamp";
|
|
693
|
+
function getHeader(headers, name) {
|
|
694
|
+
if (typeof headers.get === "function") {
|
|
695
|
+
return headers.get(name);
|
|
696
|
+
}
|
|
697
|
+
const wanted = name.toLowerCase();
|
|
698
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
699
|
+
if (key.toLowerCase() === wanted) {
|
|
700
|
+
return (Array.isArray(value) ? value[0] : value) ?? null;
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return null;
|
|
704
|
+
}
|
|
705
|
+
var SignatureVerifier = class {
|
|
706
|
+
secret;
|
|
707
|
+
tolerance;
|
|
708
|
+
/**
|
|
709
|
+
* @param tolerance Maximum age in seconds; 0 disables the age check.
|
|
710
|
+
*/
|
|
711
|
+
constructor(secret, tolerance = 300) {
|
|
712
|
+
this.secret = secret;
|
|
713
|
+
this.tolerance = tolerance;
|
|
714
|
+
}
|
|
715
|
+
sign(payload, timestamp) {
|
|
716
|
+
return "sha256=" + createHmac("sha256", this.secret ?? "").update(`${timestamp}.`).update(payload).digest("hex");
|
|
717
|
+
}
|
|
718
|
+
/** Throws InvalidSignatureError unless the payload was signed by Jayik. */
|
|
719
|
+
verify(payload, signature, timestamp) {
|
|
720
|
+
if (!this.secret) {
|
|
721
|
+
throw new InvalidSignatureError("Jayik webhook secret is not configured (JAYIK_WEBHOOK_SECRET).");
|
|
722
|
+
}
|
|
723
|
+
if (!signature || !timestamp) {
|
|
724
|
+
throw new InvalidSignatureError("Missing Jayik signature headers.");
|
|
725
|
+
}
|
|
726
|
+
if (!/^\d+$/.test(timestamp)) {
|
|
727
|
+
throw new InvalidSignatureError("Invalid Jayik webhook timestamp.");
|
|
728
|
+
}
|
|
729
|
+
if (this.tolerance > 0 && Math.abs(Math.floor(Date.now() / 1e3) - Number(timestamp)) > this.tolerance) {
|
|
730
|
+
throw new InvalidSignatureError("Jayik webhook timestamp is outside the allowed tolerance.");
|
|
731
|
+
}
|
|
732
|
+
const expected = Buffer.from(this.sign(payload, timestamp));
|
|
733
|
+
const given = Buffer.from(signature);
|
|
734
|
+
if (expected.length !== given.length || !timingSafeEqual(expected, given)) {
|
|
735
|
+
throw new InvalidSignatureError("Jayik webhook signature mismatch.");
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
isValid(payload, signature, timestamp) {
|
|
739
|
+
try {
|
|
740
|
+
this.verify(payload, signature, timestamp);
|
|
741
|
+
} catch (error) {
|
|
742
|
+
if (error instanceof InvalidSignatureError) {
|
|
743
|
+
return false;
|
|
744
|
+
}
|
|
745
|
+
throw error;
|
|
746
|
+
}
|
|
747
|
+
return true;
|
|
748
|
+
}
|
|
749
|
+
/** Verify using a request's headers. */
|
|
750
|
+
verifyHeaders(payload, headers) {
|
|
751
|
+
this.verify(payload, getHeader(headers, SIGNATURE_HEADER), getHeader(headers, TIMESTAMP_HEADER));
|
|
752
|
+
}
|
|
753
|
+
};
|
|
754
|
+
|
|
755
|
+
// src/resources/webhook.ts
|
|
756
|
+
var Webhook = class extends Resource {
|
|
757
|
+
/**
|
|
758
|
+
* Current settings: `webhook` (URL), `secret` (its `value` is the signing
|
|
759
|
+
* secret, put it in JAYIK_WEBHOOK_SECRET) and `signature` (scheme details).
|
|
760
|
+
*/
|
|
761
|
+
get() {
|
|
762
|
+
return this.client.get("v2/webhook");
|
|
763
|
+
}
|
|
764
|
+
/** The signing secret (whsec_...). */
|
|
765
|
+
async secret() {
|
|
766
|
+
return (await this.get())?.secret?.value ?? null;
|
|
767
|
+
}
|
|
768
|
+
/**
|
|
769
|
+
* Set the URL that receives events. Must be https://.
|
|
770
|
+
* Call get() afterwards if you need to confirm the saved value.
|
|
771
|
+
*/
|
|
772
|
+
set(url) {
|
|
773
|
+
return this.client.put("v2/webhook", { webhook: url });
|
|
774
|
+
}
|
|
775
|
+
/** Stop receiving events. */
|
|
776
|
+
remove() {
|
|
777
|
+
return this.client.put("v2/webhook", { webhook: null });
|
|
778
|
+
}
|
|
779
|
+
/**
|
|
780
|
+
* Ask Jayik to send a test event to your URL: real data when `tr` is
|
|
781
|
+
* given, sample data otherwise. `operation` defaults to "created"
|
|
782
|
+
* (see WebhookOperation). Returns what was dispatched.
|
|
783
|
+
*/
|
|
784
|
+
test(tr, operation) {
|
|
785
|
+
const body = {};
|
|
786
|
+
if (tr != null) body.tr = tr;
|
|
787
|
+
if (operation != null) body.operation = operation;
|
|
788
|
+
return this.client.post("v2/webhook/test", body);
|
|
789
|
+
}
|
|
790
|
+
/** Re-send a `created` event for the order to your URL. */
|
|
791
|
+
redeliver(tr) {
|
|
792
|
+
return this.client.post(`v2/webhook/deliveries/${encodeURIComponent(tr)}`);
|
|
793
|
+
}
|
|
794
|
+
/** A verifier using the configured webhook secret and tolerance. */
|
|
795
|
+
get verifier() {
|
|
796
|
+
const { secret, tolerance } = this.client.config.webhook;
|
|
797
|
+
return new SignatureVerifier(secret, tolerance);
|
|
798
|
+
}
|
|
799
|
+
/**
|
|
800
|
+
* Verify an incoming webhook and parse it. Throws InvalidSignatureError
|
|
801
|
+
* when it was not signed by Jayik.
|
|
802
|
+
*
|
|
803
|
+
* @param rawBody The request body exactly as received, before JSON decoding.
|
|
804
|
+
*/
|
|
805
|
+
constructEvent(rawBody, headers) {
|
|
806
|
+
this.verifier.verifyHeaders(rawBody, headers);
|
|
807
|
+
return WebhookEvent.fromBody(rawBody);
|
|
808
|
+
}
|
|
809
|
+
/**
|
|
810
|
+
* A (req, res) handler for node:http, Express and Connect that verifies
|
|
811
|
+
* the signature and calls you with the event.
|
|
812
|
+
*
|
|
813
|
+
* app.post('/jayik/webhook', jayik.webhook.handler(async (event) => { ... }));
|
|
814
|
+
*/
|
|
815
|
+
handler(onEvent) {
|
|
816
|
+
return createWebhookHandler(this.verifier, typeof onEvent === "function" ? { onEvent } : onEvent);
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
|
|
820
|
+
// src/jayik.ts
|
|
821
|
+
var Jayik = class _Jayik {
|
|
822
|
+
/** The underlying HTTP client, for endpoints this package does not wrap yet. */
|
|
823
|
+
client;
|
|
824
|
+
account;
|
|
825
|
+
orders;
|
|
826
|
+
warehouses;
|
|
827
|
+
orderCategories;
|
|
828
|
+
governorates;
|
|
829
|
+
statuses;
|
|
830
|
+
/** Product types used in order_items[].attribute_id. */
|
|
831
|
+
attributes;
|
|
832
|
+
webhook;
|
|
833
|
+
apiKeys;
|
|
834
|
+
/**
|
|
835
|
+
* @param config Options, or just the API key. Anything left out falls back
|
|
836
|
+
* to the JAYIK_* environment variables.
|
|
837
|
+
*/
|
|
838
|
+
constructor(config = {}) {
|
|
839
|
+
this.client = config instanceof Client ? config : new Client(typeof config === "string" ? { apiKey: config } : config);
|
|
840
|
+
this.account = new Account(this.client);
|
|
841
|
+
this.orders = new Orders(this.client);
|
|
842
|
+
this.warehouses = new Warehouses(this.client);
|
|
843
|
+
this.orderCategories = new OrderCategories(this.client);
|
|
844
|
+
this.governorates = new Governorates(this.client);
|
|
845
|
+
this.statuses = new Statuses(this.client);
|
|
846
|
+
this.attributes = new Attributes(this.client);
|
|
847
|
+
this.webhook = new Webhook(this.client);
|
|
848
|
+
this.apiKeys = new ApiKeys(this.client);
|
|
849
|
+
}
|
|
850
|
+
/**
|
|
851
|
+
* A new instance that authenticates with another merchant's API key.
|
|
852
|
+
* Useful for marketplaces where each vendor has their own Jayik account.
|
|
853
|
+
*/
|
|
854
|
+
withKey(apiKey) {
|
|
855
|
+
return new _Jayik(this.client.withKey(apiKey));
|
|
856
|
+
}
|
|
857
|
+
};
|
|
858
|
+
export {
|
|
859
|
+
Account,
|
|
860
|
+
ApiKeys,
|
|
861
|
+
Attributes,
|
|
862
|
+
AuthenticationError,
|
|
863
|
+
CANCELLABLE_STATUSES,
|
|
864
|
+
Client,
|
|
865
|
+
ConflictError,
|
|
866
|
+
ConnectionError,
|
|
867
|
+
DeliveryType,
|
|
868
|
+
Governorates,
|
|
869
|
+
InvalidSignatureError,
|
|
870
|
+
Jayik,
|
|
871
|
+
JayikError,
|
|
872
|
+
NotFoundError,
|
|
873
|
+
OrderCategories,
|
|
874
|
+
OrderStatus,
|
|
875
|
+
Orders,
|
|
876
|
+
Page,
|
|
877
|
+
PermissionDeniedError,
|
|
878
|
+
RateLimitError,
|
|
879
|
+
RequestError,
|
|
880
|
+
SIGNATURE_HEADER,
|
|
881
|
+
SignatureVerifier,
|
|
882
|
+
Statuses,
|
|
883
|
+
TIMESTAMP_HEADER,
|
|
884
|
+
UnprocessableError,
|
|
885
|
+
ValidationError,
|
|
886
|
+
Warehouses,
|
|
887
|
+
Webhook,
|
|
888
|
+
WebhookEvent,
|
|
889
|
+
WebhookOperation,
|
|
890
|
+
buildQueryString,
|
|
891
|
+
createWebhookHandler,
|
|
892
|
+
formatDate,
|
|
893
|
+
normalizeQuery,
|
|
894
|
+
unwrap
|
|
895
|
+
};
|