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