@clikgate/node 0.0.0-stage → 2.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/LICENSE +21 -0
  3. package/README.md +300 -2
  4. package/SECURITY.md +34 -0
  5. package/dist/cjs/ads-hashing.d.ts +37 -0
  6. package/dist/cjs/ads-hashing.js +67 -0
  7. package/dist/cjs/click-ids.d.ts +184 -0
  8. package/dist/cjs/click-ids.js +535 -0
  9. package/dist/cjs/client.d.ts +175 -0
  10. package/dist/cjs/client.js +266 -0
  11. package/dist/cjs/config.d.ts +12 -0
  12. package/dist/cjs/config.js +87 -0
  13. package/dist/cjs/core.d.ts +15 -0
  14. package/dist/cjs/core.js +100 -0
  15. package/dist/cjs/enums.d.ts +48 -0
  16. package/dist/cjs/enums.js +47 -0
  17. package/dist/cjs/errors.d.ts +117 -0
  18. package/dist/cjs/errors.js +257 -0
  19. package/dist/cjs/express.d.ts +49 -0
  20. package/dist/cjs/express.js +44 -0
  21. package/dist/cjs/fastify.d.ts +47 -0
  22. package/dist/cjs/fastify.js +35 -0
  23. package/dist/cjs/generated/index.d.ts +17534 -0
  24. package/dist/cjs/generated/index.js +8816 -0
  25. package/dist/cjs/goals.d.ts +116 -0
  26. package/dist/cjs/goals.js +381 -0
  27. package/dist/cjs/guard.d.ts +17 -0
  28. package/dist/cjs/guard.js +40 -0
  29. package/dist/cjs/http.d.ts +16 -0
  30. package/dist/cjs/http.js +148 -0
  31. package/dist/cjs/identity.d.ts +32 -0
  32. package/dist/cjs/identity.js +99 -0
  33. package/dist/cjs/index.d.ts +32 -0
  34. package/dist/cjs/index.js +64 -0
  35. package/dist/cjs/logger.d.ts +9 -0
  36. package/dist/cjs/logger.js +8 -0
  37. package/dist/cjs/money.d.ts +16 -0
  38. package/dist/cjs/money.js +51 -0
  39. package/dist/cjs/next.d.ts +81 -0
  40. package/dist/cjs/next.js +103 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payments.d.ts +174 -0
  43. package/dist/cjs/payments.js +485 -0
  44. package/dist/cjs/resources.d.ts +109 -0
  45. package/dist/cjs/resources.js +189 -0
  46. package/dist/cjs/shutdown.d.ts +2 -0
  47. package/dist/cjs/shutdown.js +51 -0
  48. package/dist/cjs/transport.d.ts +14 -0
  49. package/dist/cjs/transport.js +204 -0
  50. package/dist/cjs/types.d.ts +218 -0
  51. package/dist/cjs/types.js +2 -0
  52. package/dist/cjs/user-agent.d.ts +1 -0
  53. package/dist/cjs/user-agent.js +53 -0
  54. package/dist/cjs/version.d.ts +2 -0
  55. package/dist/cjs/version.js +5 -0
  56. package/dist/cjs/webhooks.d.ts +36 -0
  57. package/dist/cjs/webhooks.js +108 -0
  58. package/dist/esm/ads-hashing.d.ts +37 -0
  59. package/dist/esm/ads-hashing.js +62 -0
  60. package/dist/esm/click-ids.d.ts +184 -0
  61. package/dist/esm/click-ids.js +526 -0
  62. package/dist/esm/client.d.ts +175 -0
  63. package/dist/esm/client.js +262 -0
  64. package/dist/esm/config.d.ts +12 -0
  65. package/dist/esm/config.js +82 -0
  66. package/dist/esm/core.d.ts +15 -0
  67. package/dist/esm/core.js +96 -0
  68. package/dist/esm/enums.d.ts +48 -0
  69. package/dist/esm/enums.js +44 -0
  70. package/dist/esm/errors.d.ts +117 -0
  71. package/dist/esm/errors.js +234 -0
  72. package/dist/esm/express.d.ts +49 -0
  73. package/dist/esm/express.js +40 -0
  74. package/dist/esm/fastify.d.ts +47 -0
  75. package/dist/esm/fastify.js +32 -0
  76. package/dist/esm/generated/index.d.ts +17534 -0
  77. package/dist/esm/generated/index.js +8754 -0
  78. package/dist/esm/goals.d.ts +116 -0
  79. package/dist/esm/goals.js +371 -0
  80. package/dist/esm/guard.d.ts +17 -0
  81. package/dist/esm/guard.js +36 -0
  82. package/dist/esm/http.d.ts +16 -0
  83. package/dist/esm/http.js +138 -0
  84. package/dist/esm/identity.d.ts +32 -0
  85. package/dist/esm/identity.js +92 -0
  86. package/dist/esm/index.d.ts +32 -0
  87. package/dist/esm/index.js +21 -0
  88. package/dist/esm/logger.d.ts +9 -0
  89. package/dist/esm/logger.js +5 -0
  90. package/dist/esm/money.d.ts +16 -0
  91. package/dist/esm/money.js +48 -0
  92. package/dist/esm/next.d.ts +81 -0
  93. package/dist/esm/next.js +96 -0
  94. package/dist/esm/package.json +1 -0
  95. package/dist/esm/payments.d.ts +174 -0
  96. package/dist/esm/payments.js +476 -0
  97. package/dist/esm/resources.d.ts +109 -0
  98. package/dist/esm/resources.js +183 -0
  99. package/dist/esm/shutdown.d.ts +2 -0
  100. package/dist/esm/shutdown.js +47 -0
  101. package/dist/esm/transport.d.ts +14 -0
  102. package/dist/esm/transport.js +166 -0
  103. package/dist/esm/types.d.ts +218 -0
  104. package/dist/esm/types.js +1 -0
  105. package/dist/esm/user-agent.d.ts +1 -0
  106. package/dist/esm/user-agent.js +16 -0
  107. package/dist/esm/version.d.ts +2 -0
  108. package/dist/esm/version.js +2 -0
  109. package/dist/esm/webhooks.d.ts +36 -0
  110. package/dist/esm/webhooks.js +105 -0
  111. package/package.json +128 -4
@@ -0,0 +1,109 @@
1
+ import { type RequestOptions } from './http.js';
2
+ import type { Click, Conversion, GoalEvent, Link, LinkUpdateResult, ListPage, QrCode } from './types.js';
3
+ type Params = Record<string, unknown>;
4
+ /** Conversions: the older API. New integrations should use goals. */
5
+ export declare class Conversions {
6
+ private readonly core;
7
+ /**
8
+ * Report a conversion (`POST /v1/conversions`). `params` uses the API's field names.
9
+ * In private mode only `external_id`, `goal`, `click_id`, `code`, `reference`, `value`, `currency`,
10
+ * `provider`, `is_first`, `occurred_at`, `consent`, `kept_by`, `browser_engine`, `platform` and the hashed
11
+ * identifiers `hashed_email`, `hashed_phone_e164`, `hashed_phone_digits` (64 lowercase hex; `hashForAds`) are allowed.
12
+ *
13
+ * With `goal` set to a Payment goal this is a trusted payment confirmation: send `provider` and the payment
14
+ * reference (`external_id`), and the answer is the goal event (`object: 'goal_event'`) instead of a conversion.
15
+ * Tell them apart by `object`.
16
+ *
17
+ * @example
18
+ * await clikgate.conversions.create({ external_id: 'ORD-1001', click_id: clickId, goal: 'order_paid', value: '1500.50', currency: 'NGN' });
19
+ */
20
+ create(params: Params, requestOptions?: RequestOptions): Promise<Conversion | GoalEvent>;
21
+ /**
22
+ * Reverse a conversion, fully or partly (`amount_minor`).
23
+ *
24
+ * @example
25
+ * await clikgate.conversions.reverse('cnv_01J…', { amount_minor: 200000, reason: 'partial refund' });
26
+ */
27
+ reverse(id: string, params?: Params, requestOptions?: RequestOptions): Promise<Conversion>;
28
+ }
29
+ /** Options for `links.qr`. */
30
+ export interface QrOptions {
31
+ format?: 'svg' | 'png';
32
+ /** 256–2048 pixels. */
33
+ size?: number;
34
+ margin?: number;
35
+ /** Hex colour without `#`, e.g. `000000`. */
36
+ dark?: string;
37
+ light?: string;
38
+ }
39
+ /** An async iterator over every link that also exposes the first page. */
40
+ export interface LinkIterator extends AsyncIterable<Link> {
41
+ /** Collect up to `max` links (default: all). */
42
+ toArray(max?: number): Promise<Link[]>;
43
+ }
44
+ /** Links: create, read, update (with approvals and locks), list and QR codes. */
45
+ export declare class Links {
46
+ private readonly core;
47
+ /**
48
+ * Create a link. The result's `warnings` include `no_preview` when there is no preview title and image.
49
+ *
50
+ * @example
51
+ * const link = await clikgate.links.create({ destination_url: 'https://example.com/spring', og_title: 'Spring sale', og_image_url: 'https://example.com/og.png' });
52
+ * console.log(link.short_url, link.warnings);
53
+ */
54
+ create(params: Params, requestOptions?: RequestOptions): Promise<Link>;
55
+ /**
56
+ * Fetch a link by ID.
57
+ *
58
+ * @example
59
+ * const link = await clikgate.links.get('lnk_01J…');
60
+ */
61
+ get(id: string, requestOptions?: RequestOptions): Promise<Link>;
62
+ /**
63
+ * Update a link. With two-person approval on, a destination change answers `202` and waits for a
64
+ * second person: the result is `{ applied: false, change_request }`. A locked link throws {@link LinkLockedError}.
65
+ * An explicit `null` clears a field.
66
+ *
67
+ * @example
68
+ * const result = await clikgate.links.update('lnk_01J…', { destination_url: 'https://example.com/summer' });
69
+ * if (!result.applied) console.log('waiting for approval:', result.change_request.id);
70
+ */
71
+ update(id: string, params: Params, requestOptions?: RequestOptions): Promise<LinkUpdateResult>;
72
+ /**
73
+ * Fetch one page of links (`limit` 1–100, `starting_after`, `ending_before`, filters such as `status`, `tag`, `campaign_id`).
74
+ *
75
+ * @example
76
+ * const page = await clikgate.links.listPage({ limit: 100, tag: 'promo' });
77
+ */
78
+ listPage(params?: Params, requestOptions?: RequestOptions): Promise<ListPage<Link>>;
79
+ /**
80
+ * Iterate over every link, fetching pages lazily.
81
+ *
82
+ * @example
83
+ * for await (const link of clikgate.links.list({ status: 'active', limit: 100 })) {
84
+ * console.log(link.short_url);
85
+ * }
86
+ */
87
+ list(params?: Params, requestOptions?: RequestOptions): LinkIterator;
88
+ /**
89
+ * Download the link's QR code.
90
+ *
91
+ * @example
92
+ * const qr = await clikgate.links.qr('lnk_01J…', { format: 'png', size: 1024 });
93
+ * await fs.promises.writeFile('qr.png', qr.data);
94
+ */
95
+ qr(id: string, options?: QrOptions, requestOptions?: RequestOptions): Promise<QrCode>;
96
+ }
97
+ /** Clicks. */
98
+ export declare class Clicks {
99
+ private readonly core;
100
+ /**
101
+ * Fetch a click by its ID (`clk_…`).
102
+ *
103
+ * @example
104
+ * const click = await clikgate.clicks.get(clickId);
105
+ * console.log(click.country, click.link?.id);
106
+ */
107
+ get(clickId: string, requestOptions?: RequestOptions): Promise<Click>;
108
+ }
109
+ export {};
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Clicks = exports.Links = exports.Conversions = void 0;
4
+ const guard_js_1 = require("./guard.js");
5
+ const http_js_1 = require("./http.js");
6
+ const money_js_1 = require("./money.js");
7
+ const ads_hashing_js_1 = require("./ads-hashing.js");
8
+ function withFormattedValue(core, params) {
9
+ const out = {};
10
+ for (const [k, v] of Object.entries(params))
11
+ if (v !== undefined)
12
+ out[k] = v;
13
+ if (out.value !== undefined && out.value !== null)
14
+ out.value = (0, money_js_1.formatValue)(out.value, (m) => core.warn('inexact_number', m));
15
+ return out;
16
+ }
17
+ /** Conversions: the older API. New integrations should use goals. */
18
+ class Conversions {
19
+ core;
20
+ /** @internal */
21
+ constructor(core) {
22
+ this.core = core;
23
+ }
24
+ /**
25
+ * Report a conversion (`POST /v1/conversions`). `params` uses the API's field names.
26
+ * In private mode only `external_id`, `goal`, `click_id`, `code`, `reference`, `value`, `currency`,
27
+ * `provider`, `is_first`, `occurred_at`, `consent`, `kept_by`, `browser_engine`, `platform` and the hashed
28
+ * identifiers `hashed_email`, `hashed_phone_e164`, `hashed_phone_digits` (64 lowercase hex; `hashForAds`) are allowed.
29
+ *
30
+ * With `goal` set to a Payment goal this is a trusted payment confirmation: send `provider` and the payment
31
+ * reference (`external_id`), and the answer is the goal event (`object: 'goal_event'`) instead of a conversion.
32
+ * Tell them apart by `object`.
33
+ *
34
+ * @example
35
+ * await clikgate.conversions.create({ external_id: 'ORD-1001', click_id: clickId, goal: 'order_paid', value: '1500.50', currency: 'NGN' });
36
+ */
37
+ async create(params, requestOptions = {}) {
38
+ const body = withFormattedValue(this.core, params);
39
+ (0, ads_hashing_js_1.checkHashedFields)(body);
40
+ const state = await this.core.guardState();
41
+ if (state.guard)
42
+ (0, guard_js_1.guardPayload)('conversion', body);
43
+ const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/conversions', body, ...requestOptions });
44
+ return data;
45
+ }
46
+ /**
47
+ * Reverse a conversion, fully or partly (`amount_minor`).
48
+ *
49
+ * @example
50
+ * await clikgate.conversions.reverse('cnv_01J…', { amount_minor: 200000, reason: 'partial refund' });
51
+ */
52
+ async reverse(id, params = {}, requestOptions = {}) {
53
+ const body = withFormattedValue(this.core, params);
54
+ const state = await this.core.guardState();
55
+ if (state.guard)
56
+ (0, guard_js_1.guardPayload)('reversal', body);
57
+ const { data } = await this.core.requester.request({ method: 'POST', path: `/v1/conversions/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}/reverse`, body, ...requestOptions });
58
+ return data;
59
+ }
60
+ }
61
+ exports.Conversions = Conversions;
62
+ /** Links: create, read, update (with approvals and locks), list and QR codes. */
63
+ class Links {
64
+ core;
65
+ /** @internal */
66
+ constructor(core) {
67
+ this.core = core;
68
+ }
69
+ /**
70
+ * Create a link. The result's `warnings` include `no_preview` when there is no preview title and image.
71
+ *
72
+ * @example
73
+ * const link = await clikgate.links.create({ destination_url: 'https://example.com/spring', og_title: 'Spring sale', og_image_url: 'https://example.com/og.png' });
74
+ * console.log(link.short_url, link.warnings);
75
+ */
76
+ async create(params, requestOptions = {}) {
77
+ const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/links', body: params, ...requestOptions });
78
+ return data;
79
+ }
80
+ /**
81
+ * Fetch a link by ID.
82
+ *
83
+ * @example
84
+ * const link = await clikgate.links.get('lnk_01J…');
85
+ */
86
+ async get(id, requestOptions = {}) {
87
+ const { data } = await this.core.requester.request({ method: 'GET', path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}`, ...requestOptions });
88
+ return data;
89
+ }
90
+ /**
91
+ * Update a link. With two-person approval on, a destination change answers `202` and waits for a
92
+ * second person: the result is `{ applied: false, change_request }`. A locked link throws {@link LinkLockedError}.
93
+ * An explicit `null` clears a field.
94
+ *
95
+ * @example
96
+ * const result = await clikgate.links.update('lnk_01J…', { destination_url: 'https://example.com/summer' });
97
+ * if (!result.applied) console.log('waiting for approval:', result.change_request.id);
98
+ */
99
+ async update(id, params, requestOptions = {}) {
100
+ const { status, data } = await this.core.requester.request({
101
+ method: 'PATCH',
102
+ path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}`,
103
+ body: params,
104
+ ...requestOptions,
105
+ });
106
+ if (status === 202)
107
+ return { applied: false, link: null, change_request: data, warnings: [] };
108
+ const link = data;
109
+ return { applied: true, link, change_request: null, warnings: Array.isArray(link?.warnings) ? link.warnings : [] };
110
+ }
111
+ /**
112
+ * Fetch one page of links (`limit` 1–100, `starting_after`, `ending_before`, filters such as `status`, `tag`, `campaign_id`).
113
+ *
114
+ * @example
115
+ * const page = await clikgate.links.listPage({ limit: 100, tag: 'promo' });
116
+ */
117
+ async listPage(params = {}, requestOptions = {}) {
118
+ const { data } = await this.core.requester.request({ method: 'GET', path: '/v1/links', query: params, ...requestOptions });
119
+ return data;
120
+ }
121
+ /**
122
+ * Iterate over every link, fetching pages lazily.
123
+ *
124
+ * @example
125
+ * for await (const link of clikgate.links.list({ status: 'active', limit: 100 })) {
126
+ * console.log(link.short_url);
127
+ * }
128
+ */
129
+ list(params = {}, requestOptions = {}) {
130
+ const listPage = (p) => this.listPage(p, requestOptions);
131
+ async function* iterate() {
132
+ let cursor = null;
133
+ for (;;) {
134
+ const page = await listPage(cursor ? { ...params, starting_after: cursor } : params);
135
+ for (const item of page.data ?? [])
136
+ yield item;
137
+ if (!page.has_more || !page.next_cursor)
138
+ return;
139
+ cursor = page.next_cursor;
140
+ }
141
+ }
142
+ return {
143
+ [Symbol.asyncIterator]: iterate,
144
+ async toArray(max = Number.POSITIVE_INFINITY) {
145
+ const out = [];
146
+ if (max <= 0)
147
+ return out;
148
+ for await (const l of iterate()) {
149
+ out.push(l);
150
+ if (out.length >= max)
151
+ break;
152
+ }
153
+ return out;
154
+ },
155
+ };
156
+ }
157
+ /**
158
+ * Download the link's QR code.
159
+ *
160
+ * @example
161
+ * const qr = await clikgate.links.qr('lnk_01J…', { format: 'png', size: 1024 });
162
+ * await fs.promises.writeFile('qr.png', qr.data);
163
+ */
164
+ async qr(id, options = {}, requestOptions = {}) {
165
+ const res = await this.core.requester.send({ method: 'GET', path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}/qr`, query: { ...options }, raw: true, ...requestOptions });
166
+ return { contentType: res.headers['content-type'] ?? 'application/octet-stream', data: res.body };
167
+ }
168
+ }
169
+ exports.Links = Links;
170
+ /** Clicks. */
171
+ class Clicks {
172
+ core;
173
+ /** @internal */
174
+ constructor(core) {
175
+ this.core = core;
176
+ }
177
+ /**
178
+ * Fetch a click by its ID (`clk_…`).
179
+ *
180
+ * @example
181
+ * const click = await clikgate.clicks.get(clickId);
182
+ * console.log(click.country, click.link?.id);
183
+ */
184
+ async get(clickId, requestOptions = {}) {
185
+ const { data } = await this.core.requester.request({ method: 'GET', path: `/v1/clicks/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(clickId, 'click_id'))}`, ...requestOptions });
186
+ return data;
187
+ }
188
+ }
189
+ exports.Clicks = Clicks;
@@ -0,0 +1,2 @@
1
+ /** @internal One process-wide registry of flush callbacks (SPEC 9.4), so N clients add one listener each. */
2
+ export {};
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ /** @internal One process-wide registry of flush callbacks (SPEC 9.4), so N clients add one listener each. */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.registerShutdown = registerShutdown;
5
+ exports.unregisterShutdown = unregisterShutdown;
6
+ const clients = new Set();
7
+ let installed = false;
8
+ const SIGNAL_FLUSH_MS = 5000;
9
+ const SIGNALS = ['SIGTERM', 'SIGINT'];
10
+ async function flushAll(timeoutMs) {
11
+ await Promise.allSettled([...clients].filter((c) => c.busy()).map((c) => c.flush(timeoutMs)));
12
+ }
13
+ function onBeforeExit() {
14
+ if ([...clients].some((c) => c.busy()))
15
+ void flushAll(SIGNAL_FLUSH_MS);
16
+ }
17
+ function onSignal(signal) {
18
+ void flushAll(SIGNAL_FLUSH_MS).finally(() => {
19
+ uninstall();
20
+ // let other listeners decide; with none left, re-raise so the default exit happens
21
+ if (process.listenerCount(signal) === 0)
22
+ process.kill(process.pid, signal);
23
+ });
24
+ }
25
+ function install() {
26
+ if (installed)
27
+ return;
28
+ installed = true;
29
+ process.on('beforeExit', onBeforeExit);
30
+ for (const s of SIGNALS)
31
+ process.on(s, onSignal);
32
+ }
33
+ function uninstall() {
34
+ if (!installed)
35
+ return;
36
+ installed = false;
37
+ process.off('beforeExit', onBeforeExit);
38
+ for (const s of SIGNALS)
39
+ process.off(s, onSignal);
40
+ }
41
+ /** @internal */
42
+ function registerShutdown(f) {
43
+ clients.add(f);
44
+ install();
45
+ }
46
+ /** @internal */
47
+ function unregisterShutdown(f) {
48
+ clients.delete(f);
49
+ if (clients.size === 0)
50
+ uninstall();
51
+ }
@@ -0,0 +1,14 @@
1
+ /** A `fetch`-compatible function (the global `fetch`, undici's, or a wrapper adding mTLS or tracing). */
2
+ export type FetchLike = (input: string, init: {
3
+ method: string;
4
+ headers: Record<string, string>;
5
+ body?: Uint8Array;
6
+ signal: AbortSignal;
7
+ redirect: 'manual';
8
+ }) => Promise<{
9
+ status: number;
10
+ headers: {
11
+ forEach(cb: (value: string, key: string) => void): void;
12
+ };
13
+ arrayBuffer(): Promise<ArrayBuffer>;
14
+ }>;
@@ -0,0 +1,204 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.fetchTransport = fetchTransport;
37
+ exports.resolveProxy = resolveProxy;
38
+ exports.nodeTransport = nodeTransport;
39
+ const http = __importStar(require("node:http"));
40
+ const https = __importStar(require("node:https"));
41
+ const tls = __importStar(require("node:tls"));
42
+ const errors_js_1 = require("./errors.js");
43
+ const timeoutError = (ms) => new errors_js_1.TimeoutError({ message: `The request timed out after ${ms} ms.`, code: 'timeout' });
44
+ const networkError = (cause) => new errors_js_1.NetworkError({
45
+ message: `Could not reach the Clikgate API: ${cause instanceof Error ? cause.message.replace(/\/\/[^@/]*@/g, '//***@') : 'connection failed'}`,
46
+ code: 'network_error',
47
+ });
48
+ /** @internal Wrap a fetch-compatible function as a Transport. */
49
+ function fetchTransport(fetchFn) {
50
+ return async (req) => {
51
+ const controller = new AbortController();
52
+ let timedOut = false;
53
+ const timer = setTimeout(() => {
54
+ timedOut = true;
55
+ controller.abort();
56
+ }, req.timeoutMs);
57
+ try {
58
+ const res = await fetchFn(req.url, { method: req.method, headers: req.headers, body: req.body, signal: controller.signal, redirect: 'manual' });
59
+ const headers = {};
60
+ res.headers.forEach((v, k) => {
61
+ headers[k.toLowerCase()] = v;
62
+ });
63
+ const body = new Uint8Array(await res.arrayBuffer());
64
+ return { status: res.status, headers, body };
65
+ }
66
+ catch (err) {
67
+ if (timedOut)
68
+ throw timeoutError(req.timeoutMs);
69
+ throw networkError(err);
70
+ }
71
+ finally {
72
+ clearTimeout(timer);
73
+ }
74
+ };
75
+ }
76
+ /** @internal Resolve the proxy for a target URL from the option or the environment. */
77
+ function resolveProxy(target, option, env = process.env) {
78
+ if (option === false)
79
+ return null;
80
+ const raw = option ?? (target.protocol === 'https:' ? env.HTTPS_PROXY ?? env.https_proxy ?? env.HTTP_PROXY ?? env.http_proxy : env.HTTP_PROXY ?? env.http_proxy);
81
+ if (!raw)
82
+ return null;
83
+ if (option === undefined) {
84
+ const noProxy = (env.NO_PROXY ?? env.no_proxy ?? '').split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);
85
+ const host = target.hostname.toLowerCase();
86
+ if (noProxy.some((p) => p === '*' || host === p.replace(/^\./, '') || host.endsWith(p.startsWith('.') ? p : `.${p}`)))
87
+ return null;
88
+ if (host === 'localhost' || host === '127.0.0.1' || host === '[::1]')
89
+ return null;
90
+ }
91
+ try {
92
+ return new URL(raw.includes('://') ? raw : `http://${raw}`);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ function proxyAuth(proxy) {
99
+ if (!proxy.username)
100
+ return {};
101
+ const cred = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
102
+ return { 'proxy-authorization': `Basic ${Buffer.from(cred).toString('base64')}` };
103
+ }
104
+ /** Open a CONNECT tunnel through the proxy and return a TLS socket to the target. */
105
+ function tunnel(proxy, target, timeoutMs) {
106
+ return new Promise((resolve, reject) => {
107
+ const port = Number(target.port || 443);
108
+ const connectReq = (proxy.protocol === 'https:' ? https : http).request({
109
+ host: proxy.hostname,
110
+ port: Number(proxy.port || (proxy.protocol === 'https:' ? 443 : 80)),
111
+ method: 'CONNECT',
112
+ path: `${target.hostname}:${port}`,
113
+ headers: { host: `${target.hostname}:${port}`, ...proxyAuth(proxy) },
114
+ timeout: timeoutMs,
115
+ });
116
+ connectReq.once('connect', (res, socket) => {
117
+ if (res.statusCode !== 200) {
118
+ socket.destroy();
119
+ reject(new Error(`proxy CONNECT answered ${res.statusCode ?? 'nothing'}`));
120
+ return;
121
+ }
122
+ const secure = tls.connect({ socket, servername: target.hostname });
123
+ secure.once('secureConnect', () => resolve(secure));
124
+ secure.once('error', reject);
125
+ });
126
+ connectReq.once('timeout', () => connectReq.destroy(new Error('proxy timeout')));
127
+ connectReq.once('error', reject);
128
+ connectReq.end();
129
+ });
130
+ }
131
+ const agents = { http: new http.Agent({ keepAlive: true }), https: new https.Agent({ keepAlive: true }) };
132
+ /** @internal The built-in transport: node:http(s), keep-alive, optional CONNECT proxy, no redirects. */
133
+ function nodeTransport(proxyOption) {
134
+ return (req) => new Promise((resolve, reject) => {
135
+ const target = new URL(req.url);
136
+ const proxy = resolveProxy(target, proxyOption);
137
+ let settled = false;
138
+ let timedOut = false;
139
+ const fail = (err) => {
140
+ if (settled)
141
+ return;
142
+ settled = true;
143
+ clearTimeout(timer);
144
+ reject(timedOut ? timeoutError(req.timeoutMs) : err instanceof errors_js_1.NetworkError || err instanceof errors_js_1.TimeoutError ? err : networkError(err));
145
+ };
146
+ let active = null;
147
+ const timer = setTimeout(() => {
148
+ timedOut = true;
149
+ active?.destroy();
150
+ fail(timeoutError(req.timeoutMs));
151
+ }, req.timeoutMs);
152
+ const send = (socket) => {
153
+ const isHttps = target.protocol === 'https:';
154
+ const options = {
155
+ method: req.method,
156
+ host: target.hostname.replace(/^\[|\]$/g, ''),
157
+ port: target.port || (isHttps ? 443 : 80),
158
+ path: `${target.pathname}${target.search}`,
159
+ headers: { ...req.headers, ...(req.body ? { 'content-length': String(req.body.byteLength) } : {}) },
160
+ };
161
+ if (socket) {
162
+ options.createConnection = () => socket;
163
+ options.agent = false;
164
+ }
165
+ else {
166
+ options.agent = isHttps ? agents.https : agents.http;
167
+ }
168
+ if (proxy && !isHttps) {
169
+ // plain-HTTP targets through a proxy use an absolute-form request
170
+ options.host = proxy.hostname;
171
+ options.port = Number(proxy.port || 80);
172
+ options.path = target.toString();
173
+ options.headers = { ...options.headers, ...proxyAuth(proxy) };
174
+ }
175
+ const r = (isHttps && !socket ? https : http).request(options, (res) => {
176
+ const chunks = [];
177
+ res.on('data', (c) => chunks.push(c));
178
+ res.on('end', () => {
179
+ if (settled)
180
+ return;
181
+ settled = true;
182
+ clearTimeout(timer);
183
+ const headers = {};
184
+ for (const [k, v] of Object.entries(res.headers))
185
+ if (v !== undefined)
186
+ headers[k.toLowerCase()] = Array.isArray(v) ? v.join(', ') : v;
187
+ resolve({ status: res.statusCode ?? 0, headers, body: new Uint8Array(Buffer.concat(chunks)) });
188
+ });
189
+ res.on('error', fail);
190
+ res.on('aborted', () => fail(new Error('response aborted')));
191
+ });
192
+ active = r;
193
+ r.on('error', fail);
194
+ if (req.body)
195
+ r.write(req.body);
196
+ r.end();
197
+ };
198
+ if (proxy && target.protocol === 'https:') {
199
+ tunnel(proxy, target, req.timeoutMs).then(send, fail);
200
+ }
201
+ else
202
+ send();
203
+ });
204
+ }