@ripwords/myinvois-client 0.0.5 → 0.0.6

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/dist/index.js CHANGED
@@ -1,482 +1,4 @@
1
- import http from "node:http";
2
- import https from "node:https";
3
1
 
4
- //#region node_modules/node-fetch-native/dist/native.mjs
5
- const e = globalThis.Blob, o = globalThis.File, a = globalThis.FormData, s = globalThis.Headers, t = globalThis.Request, h = globalThis.Response, i = globalThis.AbortController, l = globalThis.fetch || (() => {
6
- throw new Error("[node-fetch-native] Failed to fetch: `globalThis.fetch` is not available!");
7
- });
8
-
9
- //#endregion
10
- //#region node_modules/destr/dist/index.mjs
11
- const suspectProtoRx = /"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/;
12
- const suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
13
- const JsonSigRx = /^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/;
14
- function jsonParseTransform(key, value) {
15
- if (key === "__proto__" || key === "constructor" && value && typeof value === "object" && "prototype" in value) {
16
- warnKeyDropped(key);
17
- return;
18
- }
19
- return value;
20
- }
21
- function warnKeyDropped(key) {
22
- console.warn(`[destr] Dropping "${key}" key to prevent prototype pollution.`);
23
- }
24
- function destr(value, options = {}) {
25
- if (typeof value !== "string") return value;
26
- if (value[0] === "\"" && value[value.length - 1] === "\"" && value.indexOf("\\") === -1) return value.slice(1, -1);
27
- const _value = value.trim();
28
- if (_value.length <= 9) switch (_value.toLowerCase()) {
29
- case "true": return true;
30
- case "false": return false;
31
- case "undefined": return void 0;
32
- case "null": return null;
33
- case "nan": return Number.NaN;
34
- case "infinity": return Number.POSITIVE_INFINITY;
35
- case "-infinity": return Number.NEGATIVE_INFINITY;
36
- }
37
- if (!JsonSigRx.test(value)) {
38
- if (options.strict) throw new SyntaxError("[destr] Invalid JSON");
39
- return value;
40
- }
41
- try {
42
- if (suspectProtoRx.test(value) || suspectConstructorRx.test(value)) {
43
- if (options.strict) throw new Error("[destr] Possible prototype pollution");
44
- return JSON.parse(value, jsonParseTransform);
45
- }
46
- return JSON.parse(value);
47
- } catch (error) {
48
- if (options.strict) throw error;
49
- return value;
50
- }
51
- }
52
-
53
- //#endregion
54
- //#region node_modules/ufo/dist/index.mjs
55
- const r = String.fromCharCode;
56
- const HASH_RE = /#/g;
57
- const AMPERSAND_RE = /&/g;
58
- const SLASH_RE = /\//g;
59
- const EQUAL_RE = /=/g;
60
- const PLUS_RE = /\+/g;
61
- const ENC_CARET_RE = /%5e/gi;
62
- const ENC_BACKTICK_RE = /%60/gi;
63
- const ENC_PIPE_RE = /%7c/gi;
64
- const ENC_SPACE_RE = /%20/gi;
65
- function encode(text) {
66
- return encodeURI("" + text).replace(ENC_PIPE_RE, "|");
67
- }
68
- function encodeQueryValue(input) {
69
- return encode(typeof input === "string" ? input : JSON.stringify(input)).replace(PLUS_RE, "%2B").replace(ENC_SPACE_RE, "+").replace(HASH_RE, "%23").replace(AMPERSAND_RE, "%26").replace(ENC_BACKTICK_RE, "`").replace(ENC_CARET_RE, "^").replace(SLASH_RE, "%2F");
70
- }
71
- function encodeQueryKey(text) {
72
- return encodeQueryValue(text).replace(EQUAL_RE, "%3D");
73
- }
74
- function decode(text = "") {
75
- try {
76
- return decodeURIComponent("" + text);
77
- } catch {
78
- return "" + text;
79
- }
80
- }
81
- function decodeQueryKey(text) {
82
- return decode(text.replace(PLUS_RE, " "));
83
- }
84
- function decodeQueryValue(text) {
85
- return decode(text.replace(PLUS_RE, " "));
86
- }
87
- function parseQuery(parametersString = "") {
88
- const object = /* @__PURE__ */ Object.create(null);
89
- if (parametersString[0] === "?") parametersString = parametersString.slice(1);
90
- for (const parameter of parametersString.split("&")) {
91
- const s$1 = parameter.match(/([^=]+)=?(.*)/) || [];
92
- if (s$1.length < 2) continue;
93
- const key = decodeQueryKey(s$1[1]);
94
- if (key === "__proto__" || key === "constructor") continue;
95
- const value = decodeQueryValue(s$1[2] || "");
96
- if (object[key] === void 0) object[key] = value;
97
- else if (Array.isArray(object[key])) object[key].push(value);
98
- else object[key] = [object[key], value];
99
- }
100
- return object;
101
- }
102
- function encodeQueryItem(key, value) {
103
- if (typeof value === "number" || typeof value === "boolean") value = String(value);
104
- if (!value) return encodeQueryKey(key);
105
- if (Array.isArray(value)) return value.map((_value) => `${encodeQueryKey(key)}=${encodeQueryValue(_value)}`).join("&");
106
- return `${encodeQueryKey(key)}=${encodeQueryValue(value)}`;
107
- }
108
- function stringifyQuery(query) {
109
- return Object.keys(query).filter((k) => query[k] !== void 0).map((k) => encodeQueryItem(k, query[k])).filter(Boolean).join("&");
110
- }
111
- const PROTOCOL_STRICT_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{1,2})/;
112
- const PROTOCOL_REGEX = /^[\s\w\0+.-]{2,}:([/\\]{2})?/;
113
- const PROTOCOL_RELATIVE_REGEX = /^([/\\]\s*){2,}[^/\\]/;
114
- const TRAILING_SLASH_RE = /\/$|\/\?|\/#/;
115
- const JOIN_LEADING_SLASH_RE = /^\.?\//;
116
- function hasProtocol(inputString, opts = {}) {
117
- if (typeof opts === "boolean") opts = { acceptRelative: opts };
118
- if (opts.strict) return PROTOCOL_STRICT_REGEX.test(inputString);
119
- return PROTOCOL_REGEX.test(inputString) || (opts.acceptRelative ? PROTOCOL_RELATIVE_REGEX.test(inputString) : false);
120
- }
121
- function hasTrailingSlash(input = "", respectQueryAndFragment) {
122
- if (!respectQueryAndFragment) return input.endsWith("/");
123
- return TRAILING_SLASH_RE.test(input);
124
- }
125
- function withoutTrailingSlash(input = "", respectQueryAndFragment) {
126
- if (!respectQueryAndFragment) return (hasTrailingSlash(input) ? input.slice(0, -1) : input) || "/";
127
- if (!hasTrailingSlash(input, true)) return input || "/";
128
- let path = input;
129
- let fragment = "";
130
- const fragmentIndex = input.indexOf("#");
131
- if (fragmentIndex !== -1) {
132
- path = input.slice(0, fragmentIndex);
133
- fragment = input.slice(fragmentIndex);
134
- }
135
- const [s0, ...s$1] = path.split("?");
136
- const cleanPath = s0.endsWith("/") ? s0.slice(0, -1) : s0;
137
- return (cleanPath || "/") + (s$1.length > 0 ? `?${s$1.join("?")}` : "") + fragment;
138
- }
139
- function withTrailingSlash(input = "", respectQueryAndFragment) {
140
- if (!respectQueryAndFragment) return input.endsWith("/") ? input : input + "/";
141
- if (hasTrailingSlash(input, true)) return input || "/";
142
- let path = input;
143
- let fragment = "";
144
- const fragmentIndex = input.indexOf("#");
145
- if (fragmentIndex !== -1) {
146
- path = input.slice(0, fragmentIndex);
147
- fragment = input.slice(fragmentIndex);
148
- if (!path) return fragment;
149
- }
150
- const [s0, ...s$1] = path.split("?");
151
- return s0 + "/" + (s$1.length > 0 ? `?${s$1.join("?")}` : "") + fragment;
152
- }
153
- function withBase(input, base) {
154
- if (isEmptyURL(base) || hasProtocol(input)) return input;
155
- const _base = withoutTrailingSlash(base);
156
- if (input.startsWith(_base)) return input;
157
- return joinURL(_base, input);
158
- }
159
- function withQuery(input, query) {
160
- const parsed = parseURL(input);
161
- const mergedQuery = {
162
- ...parseQuery(parsed.search),
163
- ...query
164
- };
165
- parsed.search = stringifyQuery(mergedQuery);
166
- return stringifyParsedURL(parsed);
167
- }
168
- function isEmptyURL(url) {
169
- return !url || url === "/";
170
- }
171
- function isNonEmptyURL(url) {
172
- return url && url !== "/";
173
- }
174
- function joinURL(base, ...input) {
175
- let url = base || "";
176
- for (const segment of input.filter((url2) => isNonEmptyURL(url2))) if (url) {
177
- const _segment = segment.replace(JOIN_LEADING_SLASH_RE, "");
178
- url = withTrailingSlash(url) + _segment;
179
- } else url = segment;
180
- return url;
181
- }
182
- const protocolRelative = Symbol.for("ufo:protocolRelative");
183
- function parseURL(input = "", defaultProto) {
184
- const _specialProtoMatch = input.match(/^[\s\0]*(blob:|data:|javascript:|vbscript:)(.*)/i);
185
- if (_specialProtoMatch) {
186
- const [, _proto, _pathname = ""] = _specialProtoMatch;
187
- return {
188
- protocol: _proto.toLowerCase(),
189
- pathname: _pathname,
190
- href: _proto + _pathname,
191
- auth: "",
192
- host: "",
193
- search: "",
194
- hash: ""
195
- };
196
- }
197
- if (!hasProtocol(input, { acceptRelative: true })) return defaultProto ? parseURL(defaultProto + input) : parsePath(input);
198
- const [, protocol = "", auth, hostAndPath = ""] = input.replace(/\\/g, "/").match(/^[\s\0]*([\w+.-]{2,}:)?\/\/([^/@]+@)?(.*)/) || [];
199
- let [, host = "", path = ""] = hostAndPath.match(/([^#/?]*)(.*)?/) || [];
200
- if (protocol === "file:") path = path.replace(/\/(?=[A-Za-z]:)/, "");
201
- const { pathname, search, hash } = parsePath(path);
202
- return {
203
- protocol: protocol.toLowerCase(),
204
- auth: auth ? auth.slice(0, Math.max(0, auth.length - 1)) : "",
205
- host,
206
- pathname,
207
- search,
208
- hash,
209
- [protocolRelative]: !protocol
210
- };
211
- }
212
- function parsePath(input = "") {
213
- const [pathname = "", search = "", hash = ""] = (input.match(/([^#?]*)(\?[^#]*)?(#.*)?/) || []).splice(1);
214
- return {
215
- pathname,
216
- search,
217
- hash
218
- };
219
- }
220
- function stringifyParsedURL(parsed) {
221
- const pathname = parsed.pathname || "";
222
- const search = parsed.search ? (parsed.search.startsWith("?") ? "" : "?") + parsed.search : "";
223
- const hash = parsed.hash || "";
224
- const auth = parsed.auth ? parsed.auth + "@" : "";
225
- const host = parsed.host || "";
226
- const proto = parsed.protocol || parsed[protocolRelative] ? (parsed.protocol || "") + "//" : "";
227
- return proto + auth + host + pathname + search + hash;
228
- }
229
-
230
- //#endregion
231
- //#region node_modules/ofetch/dist/shared/ofetch.03887fc3.mjs
232
- var FetchError = class extends Error {
233
- constructor(message, opts) {
234
- super(message, opts);
235
- this.name = "FetchError";
236
- if (opts?.cause && !this.cause) this.cause = opts.cause;
237
- }
238
- };
239
- function createFetchError(ctx) {
240
- const errorMessage = ctx.error?.message || ctx.error?.toString() || "";
241
- const method = ctx.request?.method || ctx.options?.method || "GET";
242
- const url = ctx.request?.url || String(ctx.request) || "/";
243
- const requestStr = `[${method}] ${JSON.stringify(url)}`;
244
- const statusStr = ctx.response ? `${ctx.response.status} ${ctx.response.statusText}` : "<no response>";
245
- const message = `${requestStr}: ${statusStr}${errorMessage ? ` ${errorMessage}` : ""}`;
246
- const fetchError = new FetchError(message, ctx.error ? { cause: ctx.error } : void 0);
247
- for (const key of [
248
- "request",
249
- "options",
250
- "response"
251
- ]) Object.defineProperty(fetchError, key, { get() {
252
- return ctx[key];
253
- } });
254
- for (const [key, refKey] of [
255
- ["data", "_data"],
256
- ["status", "status"],
257
- ["statusCode", "status"],
258
- ["statusText", "statusText"],
259
- ["statusMessage", "statusText"]
260
- ]) Object.defineProperty(fetchError, key, { get() {
261
- return ctx.response && ctx.response[refKey];
262
- } });
263
- return fetchError;
264
- }
265
- const payloadMethods = new Set(Object.freeze([
266
- "PATCH",
267
- "POST",
268
- "PUT",
269
- "DELETE"
270
- ]));
271
- function isPayloadMethod(method = "GET") {
272
- return payloadMethods.has(method.toUpperCase());
273
- }
274
- function isJSONSerializable(value) {
275
- if (value === void 0) return false;
276
- const t$1 = typeof value;
277
- if (t$1 === "string" || t$1 === "number" || t$1 === "boolean" || t$1 === null) return true;
278
- if (t$1 !== "object") return false;
279
- if (Array.isArray(value)) return true;
280
- if (value.buffer) return false;
281
- return value.constructor && value.constructor.name === "Object" || typeof value.toJSON === "function";
282
- }
283
- const textTypes = /* @__PURE__ */ new Set([
284
- "image/svg",
285
- "application/xml",
286
- "application/xhtml",
287
- "application/html"
288
- ]);
289
- const JSON_RE = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
290
- function detectResponseType(_contentType = "") {
291
- if (!_contentType) return "json";
292
- const contentType = _contentType.split(";").shift() || "";
293
- if (JSON_RE.test(contentType)) return "json";
294
- if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
295
- return "blob";
296
- }
297
- function resolveFetchOptions(request, input, defaults, Headers$1) {
298
- const headers = mergeHeaders(input?.headers ?? request?.headers, defaults?.headers, Headers$1);
299
- let query;
300
- if (defaults?.query || defaults?.params || input?.params || input?.query) query = {
301
- ...defaults?.params,
302
- ...defaults?.query,
303
- ...input?.params,
304
- ...input?.query
305
- };
306
- return {
307
- ...defaults,
308
- ...input,
309
- query,
310
- params: query,
311
- headers
312
- };
313
- }
314
- function mergeHeaders(input, defaults, Headers$1) {
315
- if (!defaults) return new Headers$1(input);
316
- const headers = new Headers$1(defaults);
317
- if (input) for (const [key, value] of Symbol.iterator in input || Array.isArray(input) ? input : new Headers$1(input)) headers.set(key, value);
318
- return headers;
319
- }
320
- async function callHooks(context, hooks) {
321
- if (hooks) if (Array.isArray(hooks)) for (const hook of hooks) await hook(context);
322
- else await hooks(context);
323
- }
324
- const retryStatusCodes = /* @__PURE__ */ new Set([
325
- 408,
326
- 409,
327
- 425,
328
- 429,
329
- 500,
330
- 502,
331
- 503,
332
- 504
333
- ]);
334
- const nullBodyResponses = /* @__PURE__ */ new Set([
335
- 101,
336
- 204,
337
- 205,
338
- 304
339
- ]);
340
- function createFetch(globalOptions = {}) {
341
- const { fetch: fetch$1 = globalThis.fetch, Headers: Headers$1 = globalThis.Headers, AbortController: AbortController$1 = globalThis.AbortController } = globalOptions;
342
- async function onError(context) {
343
- const isAbort = context.error && context.error.name === "AbortError" && !context.options.timeout || false;
344
- if (context.options.retry !== false && !isAbort) {
345
- let retries;
346
- if (typeof context.options.retry === "number") retries = context.options.retry;
347
- else retries = isPayloadMethod(context.options.method) ? 0 : 1;
348
- const responseCode = context.response && context.response.status || 500;
349
- if (retries > 0 && (Array.isArray(context.options.retryStatusCodes) ? context.options.retryStatusCodes.includes(responseCode) : retryStatusCodes.has(responseCode))) {
350
- const retryDelay = typeof context.options.retryDelay === "function" ? context.options.retryDelay(context) : context.options.retryDelay || 0;
351
- if (retryDelay > 0) await new Promise((resolve) => setTimeout(resolve, retryDelay));
352
- return $fetchRaw(context.request, {
353
- ...context.options,
354
- retry: retries - 1
355
- });
356
- }
357
- }
358
- const error = createFetchError(context);
359
- if (Error.captureStackTrace) Error.captureStackTrace(error, $fetchRaw);
360
- throw error;
361
- }
362
- const $fetchRaw = async function $fetchRaw2(_request, _options = {}) {
363
- const context = {
364
- request: _request,
365
- options: resolveFetchOptions(_request, _options, globalOptions.defaults, Headers$1),
366
- response: void 0,
367
- error: void 0
368
- };
369
- if (context.options.method) context.options.method = context.options.method.toUpperCase();
370
- if (context.options.onRequest) await callHooks(context, context.options.onRequest);
371
- if (typeof context.request === "string") {
372
- if (context.options.baseURL) context.request = withBase(context.request, context.options.baseURL);
373
- if (context.options.query) {
374
- context.request = withQuery(context.request, context.options.query);
375
- delete context.options.query;
376
- }
377
- if ("query" in context.options) delete context.options.query;
378
- if ("params" in context.options) delete context.options.params;
379
- }
380
- if (context.options.body && isPayloadMethod(context.options.method)) {
381
- if (isJSONSerializable(context.options.body)) {
382
- context.options.body = typeof context.options.body === "string" ? context.options.body : JSON.stringify(context.options.body);
383
- context.options.headers = new Headers$1(context.options.headers || {});
384
- if (!context.options.headers.has("content-type")) context.options.headers.set("content-type", "application/json");
385
- if (!context.options.headers.has("accept")) context.options.headers.set("accept", "application/json");
386
- } else if ("pipeTo" in context.options.body && typeof context.options.body.pipeTo === "function" || typeof context.options.body.pipe === "function") {
387
- if (!("duplex" in context.options)) context.options.duplex = "half";
388
- }
389
- }
390
- let abortTimeout;
391
- if (!context.options.signal && context.options.timeout) {
392
- const controller = new AbortController$1();
393
- abortTimeout = setTimeout(() => {
394
- const error = new Error("[TimeoutError]: The operation was aborted due to timeout");
395
- error.name = "TimeoutError";
396
- error.code = 23;
397
- controller.abort(error);
398
- }, context.options.timeout);
399
- context.options.signal = controller.signal;
400
- }
401
- try {
402
- context.response = await fetch$1(context.request, context.options);
403
- } catch (error) {
404
- context.error = error;
405
- if (context.options.onRequestError) await callHooks(context, context.options.onRequestError);
406
- return await onError(context);
407
- } finally {
408
- if (abortTimeout) clearTimeout(abortTimeout);
409
- }
410
- const hasBody = (context.response.body || context.response._bodyInit) && !nullBodyResponses.has(context.response.status) && context.options.method !== "HEAD";
411
- if (hasBody) {
412
- const responseType = (context.options.parseResponse ? "json" : context.options.responseType) || detectResponseType(context.response.headers.get("content-type") || "");
413
- switch (responseType) {
414
- case "json": {
415
- const data = await context.response.text();
416
- const parseFunction = context.options.parseResponse || destr;
417
- context.response._data = parseFunction(data);
418
- break;
419
- }
420
- case "stream": {
421
- context.response._data = context.response.body || context.response._bodyInit;
422
- break;
423
- }
424
- default: context.response._data = await context.response[responseType]();
425
- }
426
- }
427
- if (context.options.onResponse) await callHooks(context, context.options.onResponse);
428
- if (!context.options.ignoreResponseError && context.response.status >= 400 && context.response.status < 600) {
429
- if (context.options.onResponseError) await callHooks(context, context.options.onResponseError);
430
- return await onError(context);
431
- }
432
- return context.response;
433
- };
434
- const $fetch = async function $fetch2(request, options) {
435
- const r$1 = await $fetchRaw(request, options);
436
- return r$1._data;
437
- };
438
- $fetch.raw = $fetchRaw;
439
- $fetch.native = (...args) => fetch$1(...args);
440
- $fetch.create = (defaultOptions = {}, customGlobalOptions = {}) => createFetch({
441
- ...globalOptions,
442
- ...customGlobalOptions,
443
- defaults: {
444
- ...globalOptions.defaults,
445
- ...customGlobalOptions.defaults,
446
- ...defaultOptions
447
- }
448
- });
449
- return $fetch;
450
- }
451
-
452
- //#endregion
453
- //#region node_modules/ofetch/dist/node.mjs
454
- function createNodeFetch() {
455
- const useKeepAlive = JSON.parse(process.env.FETCH_KEEP_ALIVE || "false");
456
- if (!useKeepAlive) return l;
457
- const agentOptions = { keepAlive: true };
458
- const httpAgent = new http.Agent(agentOptions);
459
- const httpsAgent = new https.Agent(agentOptions);
460
- const nodeFetchOptions = { agent(parsedURL) {
461
- return parsedURL.protocol === "http:" ? httpAgent : httpsAgent;
462
- } };
463
- return function nodeFetchWithKeepAlive(input, init) {
464
- return l(input, {
465
- ...nodeFetchOptions,
466
- ...init
467
- });
468
- };
469
- }
470
- const fetch = globalThis.fetch ? (...args) => globalThis.fetch(...args) : createNodeFetch();
471
- const Headers = globalThis.Headers || s;
472
- const AbortController = globalThis.AbortController || i;
473
- const ofetch = createFetch({
474
- fetch,
475
- Headers,
476
- AbortController
477
- });
478
-
479
- //#endregion
480
2
  //#region src/utils/MyInvoisClient.ts
481
3
  var MyInvoisClient = class {
482
4
  baseUrl;
@@ -487,22 +9,27 @@ var MyInvoisClient = class {
487
9
  constructor(clientId, clientSecret, environment) {
488
10
  this.clientId = clientId;
489
11
  this.clientSecret = clientSecret;
490
- if (environment === "sandbox") this.baseUrl = "https://preprod-mytax.hasil.gov.my";
491
- else this.baseUrl = "https://mytax.hasil.gov.my";
12
+ if (environment === "sandbox") this.baseUrl = "https://preprod-api.myinvois.hasil.gov.my";
13
+ else this.baseUrl = "https://api.myinvois.hasil.gov.my";
492
14
  }
493
15
  async refreshToken() {
494
- const tokenResponse = await ofetch(`${this.baseUrl}/connect/token`, {
495
- method: "POST",
496
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
497
- body: {
498
- grant_type: "client_credentials",
499
- client_id: this.clientId,
500
- client_secret: this.clientSecret,
501
- scope: "InvoicingAPI"
502
- }
503
- });
504
- this.token = tokenResponse.access_token;
505
- this.tokenExpiration = new Date(Date.now() + tokenResponse.expires_in * 1e3);
16
+ try {
17
+ const response = await fetch(`${this.baseUrl}/connect/token`, {
18
+ method: "POST",
19
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
20
+ body: new URLSearchParams({
21
+ grant_type: "client_credentials",
22
+ client_id: this.clientId,
23
+ client_secret: this.clientSecret,
24
+ scope: "InvoicingAPI"
25
+ })
26
+ });
27
+ const tokenResponse = await response.json();
28
+ this.token = tokenResponse.access_token;
29
+ this.tokenExpiration = new Date(Date.now() + tokenResponse.expires_in * 1e3);
30
+ } catch (error) {
31
+ console.error(error);
32
+ }
506
33
  }
507
34
  async getToken() {
508
35
  if (!this.tokenExpiration || this.tokenExpiration < new Date()) await this.refreshToken();
@@ -510,13 +37,12 @@ var MyInvoisClient = class {
510
37
  }
511
38
  async fetch(path, options = {}) {
512
39
  const token = await this.getToken();
513
- return ofetch(`${this.baseUrl}${path}`, {
40
+ return fetch(`${this.baseUrl}${path}`, {
514
41
  ...options,
515
42
  headers: {
516
43
  ...options.headers,
517
44
  Authorization: `Bearer ${token}`
518
- },
519
- responseType: "json"
45
+ }
520
46
  });
521
47
  }
522
48
  /**
@@ -528,9 +54,11 @@ var MyInvoisClient = class {
528
54
  */
529
55
  async verifyTin(tin, nric) {
530
56
  try {
531
- await this.fetch(`/api/v1.0/taxpayer/validate/${tin}?idType=NRIC&idValue=${nric}`, { method: "GET" });
532
- return true;
533
- } catch {
57
+ const response = await this.fetch(`/api/v1.0/taxpayer/validate/${tin}?idType=NRIC&idValue=${nric}`, { method: "GET" });
58
+ if (response.status === 200) return true;
59
+ return false;
60
+ } catch (error) {
61
+ console.error(error);
534
62
  return false;
535
63
  }
536
64
  }
package/package.json CHANGED
@@ -1,17 +1,8 @@
1
1
  {
2
2
  "name": "@ripwords/myinvois-client",
3
- "version": "0.0.5",
4
- "description": "MyInvois client",
3
+ "version": "0.0.6",
5
4
  "main": "dist/index.js",
6
- "types": "dist/index.d.ts",
7
5
  "module": "src/index.ts",
8
- "type": "module",
9
- "scripts": {
10
- "build": "rolldown -c rolldown.config.ts",
11
- "release": "bun run build && npm publish --access public && git push --follow-tags",
12
- "lint": "oxlint",
13
- "test": "vitest"
14
- },
15
6
  "devDependencies": {
16
7
  "@types/bun": "latest",
17
8
  "dotenv": "^16.5.0",
@@ -24,7 +15,13 @@
24
15
  "peerDependencies": {
25
16
  "typescript": "^5"
26
17
  },
27
- "dependencies": {
28
- "ofetch": "^1.4.1"
29
- }
18
+ "description": "MyInvois client",
19
+ "scripts": {
20
+ "build": "rolldown -c rolldown.config.ts",
21
+ "release": "bun run build && npm publish --access public && git push --follow-tags",
22
+ "lint": "oxlint",
23
+ "test": "vitest"
24
+ },
25
+ "type": "module",
26
+ "types": "dist/index.d.ts"
30
27
  }
@@ -1,5 +1,3 @@
1
- import { ofetch } from 'ofetch/node'
2
-
3
1
  interface TokenResponse {
4
2
  access_token: string
5
3
  expires_in: number
@@ -21,33 +19,36 @@ export class MyInvoisClient {
21
19
  this.clientSecret = clientSecret
22
20
 
23
21
  if (environment === 'sandbox') {
24
- this.baseUrl = 'https://preprod-mytax.hasil.gov.my'
22
+ this.baseUrl = 'https://preprod-api.myinvois.hasil.gov.my'
25
23
  } else {
26
- this.baseUrl = 'https://mytax.hasil.gov.my'
24
+ this.baseUrl = 'https://api.myinvois.hasil.gov.my'
27
25
  }
28
26
  }
29
27
 
30
28
  private async refreshToken() {
31
- const tokenResponse = await ofetch<TokenResponse>(
32
- `${this.baseUrl}/connect/token`,
33
- {
29
+ try {
30
+ const response = await fetch(`${this.baseUrl}/connect/token`, {
34
31
  method: 'POST',
35
32
  headers: {
36
33
  'Content-Type': 'application/x-www-form-urlencoded',
37
34
  },
38
- body: {
35
+ body: new URLSearchParams({
39
36
  grant_type: 'client_credentials',
40
37
  client_id: this.clientId,
41
38
  client_secret: this.clientSecret,
42
39
  scope: 'InvoicingAPI',
43
- },
44
- },
45
- )
40
+ }),
41
+ })
46
42
 
47
- this.token = tokenResponse.access_token
48
- this.tokenExpiration = new Date(
49
- Date.now() + tokenResponse.expires_in * 1000,
50
- )
43
+ const tokenResponse: TokenResponse = await response.json()
44
+
45
+ this.token = tokenResponse.access_token
46
+ this.tokenExpiration = new Date(
47
+ Date.now() + tokenResponse.expires_in * 1000,
48
+ )
49
+ } catch (error) {
50
+ console.error(error)
51
+ }
51
52
  }
52
53
 
53
54
  private async getToken() {
@@ -58,16 +59,12 @@ export class MyInvoisClient {
58
59
  return this.token
59
60
  }
60
61
 
61
- private async fetch<T>(
62
- path: string,
63
- options: Parameters<typeof ofetch>[1] = {},
64
- ) {
62
+ private async fetch(path: string, options: Parameters<typeof fetch>[1] = {}) {
65
63
  const token = await this.getToken()
66
64
 
67
- return ofetch<T>(`${this.baseUrl}${path}`, {
65
+ return fetch(`${this.baseUrl}${path}`, {
68
66
  ...options,
69
67
  headers: { ...options.headers, Authorization: `Bearer ${token}` },
70
- responseType: 'json',
71
68
  })
72
69
  }
73
70
 
@@ -80,15 +77,20 @@ export class MyInvoisClient {
80
77
  */
81
78
  async verifyTin(tin: string, nric: string) {
82
79
  try {
83
- await this.fetch<void>(
80
+ const response = await this.fetch(
84
81
  `/api/v1.0/taxpayer/validate/${tin}?idType=NRIC&idValue=${nric}`,
85
82
  {
86
83
  method: 'GET',
87
84
  },
88
85
  )
89
86
 
90
- return true
91
- } catch {
87
+ if (response.status === 200) {
88
+ return true
89
+ }
90
+
91
+ return false
92
+ } catch (error) {
93
+ console.error(error)
92
94
  return false
93
95
  }
94
96
  }