@clikgate/node 0.0.0-stage → 2.0.1

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 (119) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +311 -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 +191 -0
  10. package/dist/cjs/client.js +291 -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/customer-id.d.ts +26 -0
  16. package/dist/cjs/customer-id.js +52 -0
  17. package/dist/cjs/enums.d.ts +48 -0
  18. package/dist/cjs/enums.js +47 -0
  19. package/dist/cjs/errors.d.ts +117 -0
  20. package/dist/cjs/errors.js +257 -0
  21. package/dist/cjs/express.d.ts +49 -0
  22. package/dist/cjs/express.js +44 -0
  23. package/dist/cjs/fastify.d.ts +47 -0
  24. package/dist/cjs/fastify.js +35 -0
  25. package/dist/cjs/generated/index.d.ts +17793 -0
  26. package/dist/cjs/generated/index.js +8896 -0
  27. package/dist/cjs/goals.d.ts +116 -0
  28. package/dist/cjs/goals.js +381 -0
  29. package/dist/cjs/guard.d.ts +17 -0
  30. package/dist/cjs/guard.js +40 -0
  31. package/dist/cjs/http.d.ts +16 -0
  32. package/dist/cjs/http.js +148 -0
  33. package/dist/cjs/identity.d.ts +42 -0
  34. package/dist/cjs/identity.js +133 -0
  35. package/dist/cjs/index.d.ts +34 -0
  36. package/dist/cjs/index.js +70 -0
  37. package/dist/cjs/known-customers.d.ts +45 -0
  38. package/dist/cjs/known-customers.js +95 -0
  39. package/dist/cjs/logger.d.ts +9 -0
  40. package/dist/cjs/logger.js +8 -0
  41. package/dist/cjs/money.d.ts +16 -0
  42. package/dist/cjs/money.js +51 -0
  43. package/dist/cjs/next.d.ts +81 -0
  44. package/dist/cjs/next.js +103 -0
  45. package/dist/cjs/package.json +1 -0
  46. package/dist/cjs/payments.d.ts +174 -0
  47. package/dist/cjs/payments.js +485 -0
  48. package/dist/cjs/resources.d.ts +109 -0
  49. package/dist/cjs/resources.js +189 -0
  50. package/dist/cjs/shutdown.d.ts +2 -0
  51. package/dist/cjs/shutdown.js +51 -0
  52. package/dist/cjs/transport.d.ts +14 -0
  53. package/dist/cjs/transport.js +204 -0
  54. package/dist/cjs/types.d.ts +218 -0
  55. package/dist/cjs/types.js +2 -0
  56. package/dist/cjs/user-agent.d.ts +1 -0
  57. package/dist/cjs/user-agent.js +53 -0
  58. package/dist/cjs/version.d.ts +2 -0
  59. package/dist/cjs/version.js +5 -0
  60. package/dist/cjs/webhooks.d.ts +36 -0
  61. package/dist/cjs/webhooks.js +108 -0
  62. package/dist/esm/ads-hashing.d.ts +37 -0
  63. package/dist/esm/ads-hashing.js +62 -0
  64. package/dist/esm/click-ids.d.ts +184 -0
  65. package/dist/esm/click-ids.js +526 -0
  66. package/dist/esm/client.d.ts +191 -0
  67. package/dist/esm/client.js +287 -0
  68. package/dist/esm/config.d.ts +12 -0
  69. package/dist/esm/config.js +82 -0
  70. package/dist/esm/core.d.ts +15 -0
  71. package/dist/esm/core.js +96 -0
  72. package/dist/esm/customer-id.d.ts +26 -0
  73. package/dist/esm/customer-id.js +47 -0
  74. package/dist/esm/enums.d.ts +48 -0
  75. package/dist/esm/enums.js +44 -0
  76. package/dist/esm/errors.d.ts +117 -0
  77. package/dist/esm/errors.js +234 -0
  78. package/dist/esm/express.d.ts +49 -0
  79. package/dist/esm/express.js +40 -0
  80. package/dist/esm/fastify.d.ts +47 -0
  81. package/dist/esm/fastify.js +32 -0
  82. package/dist/esm/generated/index.d.ts +17793 -0
  83. package/dist/esm/generated/index.js +8833 -0
  84. package/dist/esm/goals.d.ts +116 -0
  85. package/dist/esm/goals.js +371 -0
  86. package/dist/esm/guard.d.ts +17 -0
  87. package/dist/esm/guard.js +36 -0
  88. package/dist/esm/http.d.ts +16 -0
  89. package/dist/esm/http.js +138 -0
  90. package/dist/esm/identity.d.ts +42 -0
  91. package/dist/esm/identity.js +125 -0
  92. package/dist/esm/index.d.ts +34 -0
  93. package/dist/esm/index.js +23 -0
  94. package/dist/esm/known-customers.d.ts +45 -0
  95. package/dist/esm/known-customers.js +90 -0
  96. package/dist/esm/logger.d.ts +9 -0
  97. package/dist/esm/logger.js +5 -0
  98. package/dist/esm/money.d.ts +16 -0
  99. package/dist/esm/money.js +48 -0
  100. package/dist/esm/next.d.ts +81 -0
  101. package/dist/esm/next.js +96 -0
  102. package/dist/esm/package.json +1 -0
  103. package/dist/esm/payments.d.ts +174 -0
  104. package/dist/esm/payments.js +476 -0
  105. package/dist/esm/resources.d.ts +109 -0
  106. package/dist/esm/resources.js +183 -0
  107. package/dist/esm/shutdown.d.ts +2 -0
  108. package/dist/esm/shutdown.js +47 -0
  109. package/dist/esm/transport.d.ts +14 -0
  110. package/dist/esm/transport.js +166 -0
  111. package/dist/esm/types.d.ts +218 -0
  112. package/dist/esm/types.js +1 -0
  113. package/dist/esm/user-agent.d.ts +1 -0
  114. package/dist/esm/user-agent.js +16 -0
  115. package/dist/esm/version.d.ts +2 -0
  116. package/dist/esm/version.js +2 -0
  117. package/dist/esm/webhooks.d.ts +36 -0
  118. package/dist/esm/webhooks.js +105 -0
  119. package/package.json +128 -4
@@ -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,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,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
+ }
@@ -0,0 +1,218 @@
1
+ import type { GoalKind, GoalStatus, Provider } from './enums.js';
2
+ /** Wire objects returned by the hand-written resources. Keys are as the API sends them (snake_case). */
3
+ /** Where a goal event was attributed. */
4
+ export interface GoalAttribution {
5
+ link_id: string | null;
6
+ campaign_id: string | null;
7
+ clicked_at: string | null;
8
+ }
9
+ /** A goal event (`POST /v1/goals/events`). */
10
+ export interface GoalEvent {
11
+ object: 'goal_event';
12
+ /** `cnv_…`; a Payment goal waiting for its report has its confirmation id (`pcf_…`). */
13
+ id: string;
14
+ /** The outcome: `counted`, `waiting` (a Payment goal waiting for its confirmation) or `refused`. Compare with `GoalStatus`. */
15
+ status: GoalStatus;
16
+ /** `null` when counted; else why, e.g. `waiting_for_confirmation`, `already_counted_for_click`, `rejected_bot`. */
17
+ reason: string | null;
18
+ /** The goal's kind (set in the goal's settings): `standard` or `payment`. */
19
+ goal_kind?: GoalKind;
20
+ /** Whether this event counts in totals: `status === 'counted'`. */
21
+ counted: boolean;
22
+ /** `true` when a value was dropped (browsers and apps can't set a Payment goal's value). */
23
+ value_ignored?: boolean;
24
+ /** The event's attribution state: `attributed`, `unattributed`, `rejected_bot`, … (`null` while a Payment goal waits). */
25
+ event_status?: string | null;
26
+ goal: string;
27
+ /** Your reference; `null` in private mode. */
28
+ reference: string | null;
29
+ /** Normal units as a decimal string, e.g. `"2000000"`. Never a float. */
30
+ value: string | null;
31
+ /**
32
+ * The same amount in the currency's minor units (kobo, cents), e.g. `200000000`. `null` without a value.
33
+ * Prefer `value` for exact amounts: minor units above 2^53 lose precision as a JS number.
34
+ */
35
+ value_minor?: number | null;
36
+ currency: string | null;
37
+ reversed_value?: string | null;
38
+ /** `reversed_value` in minor units; `null` when nothing was reversed. */
39
+ reversed_value_minor?: number | null;
40
+ first_for_click: boolean | null;
41
+ is_first: boolean | null;
42
+ unattributed_reason?: string | null;
43
+ duplicate_of_id?: string | null;
44
+ attributed_to: GoalAttribution | null;
45
+ /** A Payment goal sent by your server: the confirmation it became. `null` otherwise. */
46
+ payment?: GoalPayment | null;
47
+ occurred_at: string;
48
+ received_at: string;
49
+ livemode: boolean;
50
+ [key: string]: unknown;
51
+ }
52
+ /** The confirmation a Payment goal sent by your server became. */
53
+ export interface GoalPayment {
54
+ /** `pcf_…` */
55
+ confirmation_id: string;
56
+ /** `matched`, `waiting_for_report`, `counted_without_report`, `duplicate`, … (new values can appear). */
57
+ match_status: string;
58
+ /** The browser's or app's report it matched (`prp_…`), or `null`. */
59
+ report_id: string | null;
60
+ /** The provider (a `Provider` value, or a newer gateway's key). */
61
+ provider: Provider | (string & {});
62
+ [key: string]: unknown;
63
+ }
64
+ /** One item of a batch result. */
65
+ export interface GoalBatchItem {
66
+ index: number;
67
+ ok: boolean;
68
+ status: number;
69
+ goal_event?: GoalEvent | null;
70
+ error?: {
71
+ type?: string;
72
+ code?: string;
73
+ message?: string;
74
+ param?: string | null;
75
+ [key: string]: unknown;
76
+ } | null;
77
+ }
78
+ /** `POST /v1/goals/events/batch` result: one item per event, in order. */
79
+ export interface GoalBatchResult {
80
+ object: 'list';
81
+ data: GoalBatchItem[];
82
+ }
83
+ /** A non-blocking finding on a link, e.g. `no_preview`. */
84
+ export interface LinkWarning {
85
+ code: string;
86
+ message: string;
87
+ param?: string | null;
88
+ }
89
+ /** A link (`/v1/links`). Only the most used fields are typed; the rest are kept. */
90
+ export interface Link {
91
+ object: 'link';
92
+ id: string;
93
+ short_url: string;
94
+ domain: string;
95
+ slug: string;
96
+ status: string;
97
+ destination_url: string;
98
+ fallback_url: string | null;
99
+ title: string | null;
100
+ og_title: string | null;
101
+ og_image_url: string | null;
102
+ tags: string[];
103
+ metadata: Record<string, unknown>;
104
+ /** Non-blocking warnings, e.g. `no_preview`. */
105
+ warnings: LinkWarning[];
106
+ /** `"premium"` on `ciz.to` links, else `null`. */
107
+ domain_badge?: 'premium' | null;
108
+ /** True when destination, fallback and deep-link changes are refused (`409 link_locked`). */
109
+ locked?: boolean;
110
+ created_at: string;
111
+ updated_at: string;
112
+ livemode: boolean;
113
+ [key: string]: unknown;
114
+ }
115
+ /** A pending destination change awaiting a second person's approval (`202` on update). */
116
+ export interface LinkChangeRequest {
117
+ object: 'link_change_request';
118
+ id: string;
119
+ link_id: string;
120
+ requested_by: string;
121
+ /** Who asked for the change: `user`, `key`, `client` or `cli` (a plain string; new values can appear). */
122
+ requested_by_type: string;
123
+ from_url: string;
124
+ to_url: string;
125
+ status: 'pending' | 'approved' | 'rejected' | 'expired';
126
+ decided_by: string | null;
127
+ decided_at: string | null;
128
+ /** The approver's or rejecter's note, once decided. */
129
+ decision_note: string | null;
130
+ created_at: string;
131
+ expires_at: string;
132
+ /** `true` for live-environment data, `false` for test mode. */
133
+ livemode: boolean;
134
+ [key: string]: unknown;
135
+ }
136
+ /** The result of `links.update`: applied now, or waiting for approval. */
137
+ export type LinkUpdateResult = {
138
+ applied: true;
139
+ link: Link;
140
+ change_request: null;
141
+ warnings: LinkWarning[];
142
+ } | {
143
+ applied: false;
144
+ link: null;
145
+ change_request: LinkChangeRequest;
146
+ warnings: LinkWarning[];
147
+ };
148
+ /** A click (`/v1/clicks/{id}`). */
149
+ export interface Click {
150
+ object: 'click';
151
+ id: string;
152
+ occurred_at: string;
153
+ link: {
154
+ id: string;
155
+ [key: string]: unknown;
156
+ } | null;
157
+ campaign: {
158
+ id: string;
159
+ [key: string]: unknown;
160
+ } | null;
161
+ country?: string | null;
162
+ device_type?: string | null;
163
+ is_suspected_bot: boolean;
164
+ livemode: boolean;
165
+ [key: string]: unknown;
166
+ }
167
+ /** A conversion (older API). */
168
+ export interface Conversion {
169
+ object: 'conversion';
170
+ id: string;
171
+ status?: string;
172
+ [key: string]: unknown;
173
+ }
174
+ /** One page of a list. */
175
+ export interface ListPage<T> {
176
+ object: 'list';
177
+ data: T[];
178
+ has_more: boolean;
179
+ next_cursor: string | null;
180
+ }
181
+ /** A goal as `GET /v1/server-sdk/config` describes it. */
182
+ export interface ConfigGoal {
183
+ key: string;
184
+ value_mode: 'none' | 'optional' | 'required';
185
+ default_currency: string | null;
186
+ }
187
+ /** `GET /v1/server-sdk/config`. */
188
+ export interface ServerSdkConfig {
189
+ mode: 'live' | 'test';
190
+ organization_id: string;
191
+ private_mode: boolean;
192
+ click_id_param: string;
193
+ goals: ConfigGoal[];
194
+ minimum_sdk_versions: Partial<Record<'node' | 'python' | 'php' | 'java' | 'dotnet', string>>;
195
+ [key: string]: unknown;
196
+ }
197
+ /** A webhook event. */
198
+ export interface WebhookEvent<T = Record<string, unknown>> {
199
+ id: string;
200
+ object: 'event';
201
+ /** e.g. `goal.completed`, `link.destination_changed`, `subscription.updated`. */
202
+ type: string;
203
+ api_version: string;
204
+ created_at: string;
205
+ organization_id: string;
206
+ livemode: boolean;
207
+ data: {
208
+ object: T;
209
+ previous_attributes?: Record<string, unknown> | null;
210
+ [key: string]: unknown;
211
+ };
212
+ [key: string]: unknown;
213
+ }
214
+ /** QR code bytes. */
215
+ export interface QrCode {
216
+ contentType: string;
217
+ data: Uint8Array;
218
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,16 @@
1
+ import * as os from 'node:os';
2
+ import { VERSION } from './version.js';
3
+ const ARCH = { x64: 'x64', arm64: 'arm64', ia32: 'x86', arm: 'arm' };
4
+ const OS = { win32: 'windows' };
5
+ /** @internal Versions must match `^[0-9][0-9A-Za-z.+-]{0,39}$` for the backend parser (SPEC section 4). */
6
+ export function sanitise(version) {
7
+ return version.replace(/^v/, '').replace(/[^0-9A-Za-z.+-]/g, '-').slice(0, 40);
8
+ }
9
+ /**
10
+ * @internal `clikgate-node/<v> (node <v>; <os> <arch>)` (SPEC section 4). This is the only telemetry.
11
+ */
12
+ export function userAgent(platform = os.platform(), arch = process.arch, nodeVersion = process.versions.node) {
13
+ const osName = (OS[platform] ?? platform).toLowerCase();
14
+ const archName = ARCH[arch] ?? arch.toLowerCase().replace(/\s+/g, '');
15
+ return `clikgate-node/${sanitise(VERSION)} (node ${sanitise(nodeVersion)}; ${osName} ${archName})`;
16
+ }
@@ -0,0 +1,2 @@
1
+ /** The SDK version (kept equal to package.json by `npm run check:version`). */
2
+ export declare const VERSION = "2.0.1";
@@ -0,0 +1,2 @@
1
+ /** The SDK version (kept equal to package.json by `npm run check:version`). */
2
+ export const VERSION = '2.0.1';