@fingerprint/node-sdk 7.0.0-test.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/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ export * from './serverApiClient'
2
+ export {
3
+ ErrorResponse,
4
+ Event,
5
+ EventRuleAction,
6
+ EventUpdate,
7
+ GetEventOptions,
8
+ Options,
9
+ Region,
10
+ SearchEventsFilter,
11
+ SearchEventsResponse,
12
+ } from './types'
13
+ export * from './sealedResults'
14
+ export * from './errors/unsealError'
15
+ export * from './webhook'
16
+ export * from './errors/apiErrors'
@@ -0,0 +1,94 @@
1
+ import { createDecipheriv } from 'crypto'
2
+ import { inflateRaw } from 'zlib'
3
+ import { promisify } from 'util'
4
+ import { Event } from './types'
5
+ import { UnsealAggregateError, UnsealError } from './errors/unsealError'
6
+ import { Buffer } from 'buffer'
7
+
8
+ const asyncInflateRaw = promisify(inflateRaw)
9
+
10
+ export enum DecryptionAlgorithm {
11
+ Aes256Gcm = 'aes-256-gcm',
12
+ }
13
+
14
+ export interface DecryptionKey {
15
+ key: Buffer
16
+ algorithm: DecryptionAlgorithm | `${DecryptionAlgorithm}`
17
+ }
18
+
19
+ const SEALED_HEADER = Buffer.from([0x9e, 0x85, 0xdc, 0xed])
20
+
21
+ function isEventResponse(data: unknown): data is Event {
22
+ return Boolean(data && typeof data === 'object' && 'event_id' in data && 'timestamp' in data)
23
+ }
24
+
25
+ /**
26
+ * @private
27
+ * */
28
+ export function parseEventsResponse(unsealed: string): Event {
29
+ const json = JSON.parse(unsealed)
30
+
31
+ if (!isEventResponse(json)) {
32
+ throw new Error('Sealed data is not valid events response')
33
+ }
34
+
35
+ return json
36
+ }
37
+
38
+ /**
39
+ * Decrypts the sealed response with the provided keys.
40
+ * The SDK will try to decrypt the result with each key until it succeeds.
41
+ * To learn more about sealed results visit: https://dev.fingerprint.com/docs/sealed-client-results
42
+ * @throws UnsealAggregateError
43
+ * @throws Error
44
+ */
45
+ export async function unsealEventsResponse(sealedData: Buffer, decryptionKeys: DecryptionKey[]): Promise<Event> {
46
+ const unsealed = await unseal(sealedData, decryptionKeys)
47
+
48
+ return parseEventsResponse(unsealed)
49
+ }
50
+
51
+ /**
52
+ * @private
53
+ * */
54
+ export async function unseal(sealedData: Buffer, decryptionKeys: DecryptionKey[]) {
55
+ if (sealedData.subarray(0, SEALED_HEADER.length).toString('hex') !== SEALED_HEADER.toString('hex')) {
56
+ throw new Error('Invalid sealed data header')
57
+ }
58
+
59
+ const errors = new UnsealAggregateError([])
60
+
61
+ for (const decryptionKey of decryptionKeys) {
62
+ switch (decryptionKey.algorithm) {
63
+ case DecryptionAlgorithm.Aes256Gcm:
64
+ try {
65
+ return await unsealAes256Gcm(sealedData, decryptionKey.key)
66
+ } catch (e) {
67
+ errors.addError(new UnsealError(decryptionKey, e as Error))
68
+ continue
69
+ }
70
+
71
+ default:
72
+ throw new Error(`Unsupported decryption algorithm: ${decryptionKey.algorithm}`)
73
+ }
74
+ }
75
+
76
+ throw errors
77
+ }
78
+
79
+ async function unsealAes256Gcm(sealedData: Buffer, decryptionKey: Buffer) {
80
+ const nonceLength = 12
81
+ const nonce = sealedData.subarray(SEALED_HEADER.length, SEALED_HEADER.length + nonceLength)
82
+
83
+ const authTagLength = 16
84
+ const authTag = sealedData.subarray(-authTagLength)
85
+
86
+ const ciphertext = sealedData.subarray(SEALED_HEADER.length + nonceLength, -authTagLength)
87
+
88
+ const decipher = createDecipheriv('aes-256-gcm', decryptionKey, nonce).setAuthTag(authTag)
89
+ const compressed = Buffer.concat([decipher.update(ciphertext), decipher.final()])
90
+
91
+ const payload = await asyncInflateRaw(compressed)
92
+
93
+ return payload.toString()
94
+ }
@@ -0,0 +1,321 @@
1
+ import { AllowedMethod, getRequestPath, GetRequestPathOptions, SuccessJsonOrVoid } from './urlUtils'
2
+ import {
3
+ Event,
4
+ EventUpdate,
5
+ FingerprintApi,
6
+ GetEventOptions,
7
+ Options,
8
+ Region,
9
+ SearchEventsFilter,
10
+ SearchEventsResponse,
11
+ } from './types'
12
+ import { paths } from './generatedApiTypes'
13
+ import { RequestError, SdkError, TooManyRequestsError } from './errors/apiErrors'
14
+ import { isErrorResponse } from './errors/handleErrorResponse'
15
+ import { toError } from './errors/toError'
16
+
17
+ export class FingerprintServerApiClient implements FingerprintApi {
18
+ public readonly region: Region
19
+
20
+ public readonly apiKey: string
21
+
22
+ protected readonly fetch: typeof fetch
23
+
24
+ private readonly defaultHeaders: Record<string, string>
25
+
26
+ /**
27
+ * FingerprintJS server API client used to fetch data from FingerprintJS
28
+ * @constructor
29
+ * @param {Options} options - Options for FingerprintJS server API client
30
+ */
31
+ constructor(options: Readonly<Options>) {
32
+ if (!options.apiKey) {
33
+ throw Error('Api key is not set')
34
+ }
35
+
36
+ // These type assertions are safe because the Options type allows the
37
+ // region or authentication mode to be specified as a string or an enum value.
38
+ // The resulting JS from using the enum value or the string is identical.
39
+ this.region = (options.region as Region) ?? Region.Global
40
+
41
+ this.apiKey = options.apiKey
42
+ this.fetch = options.fetch ?? fetch
43
+
44
+ this.defaultHeaders = {
45
+ Authorization: `Bearer ${this.apiKey}`,
46
+ ...options.defaultHeaders,
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Retrieves a specific identification event with the information from each activated product — Identification and all active [Smart signals](https://dev.fingerprint.com/docs/smart-signals-overview).
52
+ *
53
+ * @param eventId - identifier of the event
54
+ * @param {object|undefined} options - Optional `getEvent` operation options
55
+ * @param {string|undefined} options.ruleset_id - Optional ruleset ID to evaluate against the event
56
+ *
57
+ * @returns {Promise<Event>} - promise with event response. For more information, see the [Server API documentation](https://dev.fingerprint.com/reference/getevent).
58
+ *
59
+ * @example
60
+ * ```javascript Handling an event
61
+ * client
62
+ * .getEvent('<eventId>')
63
+ * .then((event) => console.log(event))
64
+ * .catch((error) => {
65
+ * if (error instanceof RequestError) {
66
+ * console.log(error.statusCode, error.message)
67
+ * // Access raw response in error
68
+ * console.log(error.response)
69
+ * }
70
+ * })
71
+ * ```
72
+ *
73
+ * @example Handling an event with rule_action
74
+ * ```javascript
75
+ * client
76
+ * .getEvent('<eventId>', { ruleset_id: '<rulesetId>' })
77
+ * .then((event) => {
78
+ * const ruleAction = event.rule_action
79
+ * if (ruleAction?.type === 'block') {
80
+ * console.log('Blocked by rule:', ruleAction.rule_id, ruleAction.status_code)
81
+ * }
82
+ * })
83
+ * .catch((error) => {
84
+ * if (error instanceof RequestError) {
85
+ * console.log(error.statusCode, error.message)
86
+ * }
87
+ * })
88
+ * ```
89
+ * */
90
+ public async getEvent(eventId: string, options?: GetEventOptions): Promise<Event> {
91
+ if (!eventId) {
92
+ throw new TypeError('eventId is not set')
93
+ }
94
+
95
+ return this.callApi({
96
+ path: '/events/{event_id}',
97
+ pathParams: [eventId],
98
+ method: 'get',
99
+ queryParams: options,
100
+ })
101
+ }
102
+
103
+ /**
104
+ * Update an event with a given event ID
105
+ * @description Change information in existing events specified by `eventId` or *flag suspicious events*.
106
+ *
107
+ * When an event is created, it is assigned `linkedId` and `tag` submitted through the JS agent parameters. This information might not be available on the client so the Server API allows for updating the attributes after the fact.
108
+ *
109
+ * **Warning** It's not possible to update events older than one month.
110
+ *
111
+ * @param body - Data to update the event with.
112
+ * @param eventId The unique event [identifier](https://docs.fingerprint.com/reference/js-agent-v4-get-function#event_id).
113
+ *
114
+ * @return {Promise<void>}
115
+ *
116
+ * @example
117
+ * ```javascript
118
+ * const body = {
119
+ * linked_id: 'linked_id',
120
+ * suspect: false,
121
+ * }
122
+ *
123
+ * client
124
+ * .updateEvent(body, '<eventId>')
125
+ * .then(() => {
126
+ * // Event was successfully updated
127
+ * })
128
+ * .catch((error) => {
129
+ * if (error instanceof RequestError) {
130
+ * console.log(error.statusCode, error.message)
131
+ * // Access raw response in error
132
+ * console.log(error.response)
133
+ *
134
+ * if(error.statusCode === 409) {
135
+ * // Event is not mutable yet, wait a couple of seconds and retry the update.
136
+ * }
137
+ * }
138
+ * })
139
+ * ```
140
+ */
141
+ public async updateEvent(body: EventUpdate, eventId: string): Promise<void> {
142
+ if (!body) {
143
+ throw new TypeError('body is not set')
144
+ }
145
+
146
+ if (!eventId) {
147
+ throw new TypeError('eventId is not set')
148
+ }
149
+
150
+ return this.callApi({
151
+ path: '/events/{event_id}',
152
+ pathParams: [eventId],
153
+ method: 'patch',
154
+ body: JSON.stringify(body),
155
+ })
156
+ }
157
+
158
+ /**
159
+ * Delete data by visitor ID
160
+ * Request deleting all data associated with the specified visitor ID. This API is useful for compliance with privacy regulations. All delete requests are queued:
161
+ * Recent data (10 days or newer) belonging to the specified visitor will be deleted within 24 hours. * Data from older (11 days or more) identification events will be deleted after 90 days.
162
+ * If you are interested in using this API, please [contact our support team](https://fingerprint.com/support/) to activate it for you. Otherwise, you will receive a 403.
163
+ *
164
+ * @param visitorId The [visitor ID](https://dev.fingerprint.com/docs/js-agent#visitorid) you want to delete.*
165
+ *
166
+ * @return {Promise<void>} Promise that resolves when the deletion request is successfully queued
167
+ *
168
+ * @example
169
+ * ```javascript
170
+ * client
171
+ * .deleteVisitorData('<visitorId>')
172
+ * .then(() => {
173
+ * // Data deletion request was successfully queued
174
+ * })
175
+ * .catch((error) => {
176
+ * if (error instanceof RequestError) {
177
+ * console.log(error.statusCode, error.message)
178
+ * // Access raw response in error
179
+ * console.log(error.response)
180
+ * }
181
+ * })
182
+ * ```
183
+ */
184
+ public async deleteVisitorData(visitorId: string): Promise<void> {
185
+ if (!visitorId) {
186
+ throw new TypeError('visitorId is not set')
187
+ }
188
+
189
+ return this.callApi({
190
+ path: '/visitors/{visitor_id}',
191
+ pathParams: [visitorId],
192
+ method: 'delete',
193
+ })
194
+ }
195
+
196
+ /**
197
+ * Search for identification events, including Smart Signals, using
198
+ * multiple filtering criteria. If you don't provide `start` or `end`
199
+ * parameters, the default search range is the last 7 days.
200
+ *
201
+ * Please note that events include mobile signals (e.g. `rootApps`) even if
202
+ * the request originated from a non-mobile platform. We recommend you
203
+ * **ignore** mobile signals for such requests.
204
+ *
205
+ * @param {SearchEventsFilter} filter - Events filter
206
+ * @param {number} filter.limit - Limit the number of events returned. Must be greater than 0.
207
+ * @param {string|undefined} filter.pagination_key - Use `pagination_key` to get the next page of results.
208
+ * @param {string|undefined} filter.visitor_id - Unique [visitor identifier](https://dev.fingerprint.com/reference/get-function#visitorid) issued by Fingerprint Identification. Filter for events matching this `visitor_id`.
209
+ * @param {string|undefined} filter.bot - Filter events by the bot detection result, specifically:
210
+ * - events where any kind of bot was detected.
211
+ * - events where a good bot was detected.
212
+ * - events where a bad bot was detected.
213
+ * - events where no bot was detected.
214
+ *
215
+ * Allowed values: `all`, `good`, `bad`, `none`.
216
+ * @param {string|undefined} filter.ip_address - Filter events by IP address range. The range can be as specific as a
217
+ * single IP (/32 for IPv4 or /128 for IPv6).
218
+ * All ip_address filters must use CIDR notation, for example,
219
+ * 10.0.0.0/24, 192.168.0.1/32
220
+ * @param {string|undefined} filter.linked_id - Filter events by your custom identifier.
221
+ * You can use [linked IDs](https://dev.fingerprint.com/reference/get-function#linkedid) to
222
+ * associate identification requests with your own identifier, for
223
+ * example, session ID, purchase ID, or transaction ID. You can then
224
+ * use this `linked_id` parameter to retrieve all events associated
225
+ * with your custom identifier.
226
+ * @param {string|undefined} filter.url - Filter events by the URL (`url` property) associated with the event.
227
+ * @param {string|undefined} filter.origin - Filter events by the origin field of the event. Origin could be the website domain or mobile app bundle ID (eg: com.foo.bar)
228
+ * @param {number|undefined} filter.start - Filter events with a timestamp greater than the start time, in Unix time (milliseconds).
229
+ * @param {number|undefined} filter.end - Filter events with a timestamp smaller than the end time, in Unix time (milliseconds).
230
+ * @param {boolean|undefined} filter.reverse - Sort events in reverse timestamp order.
231
+ * @param {boolean|undefined} filter.suspect - Filter events previously tagged as suspicious via the [Update API](https://dev.fingerprint.com/reference/updateevent).
232
+ * @param {boolean|undefined} filter.vpn - Filter events by VPN Detection result.
233
+ * @param {boolean|undefined} filter.virtual_machine - Filter events by Virtual Machine Detection result.
234
+ * @param {boolean|undefined} filter.tampering - Filter events by Browser Tampering Detection result.
235
+ * @param {boolean|undefined} filter.anti_detect_browser - Filter events by Anti-detect Browser Detection result.
236
+ * @param {boolean|undefined} filter.incognito - Filter events by Browser Incognito Detection result.
237
+ * @param {boolean|undefined} filter.privacy_settings - Filter events by Privacy Settings Detection result.
238
+ * @param {boolean|undefined} filter.jailbroken - Filter events by Jailbroken Device Detection result.
239
+ * @param {boolean|undefined} filter.frida - Filter events by Frida Detection result.
240
+ * @param {boolean|undefined} filter.factory_reset - Filter events by Factory Reset Detection result.
241
+ * @param {boolean|undefined} filter.cloned_app - Filter events by Cloned App Detection result.
242
+ * @param {boolean|undefined} filter.emulator - Filter events by Android Emulator Detection result.
243
+ * @param {boolean|undefined} filter.root_apps - Filter events by Rooted Device Detection result.
244
+ * @param {'high'|'medium'|'low'|undefined} filter.vpn_confidence - Filter events by VPN Detection result confidence level.
245
+ * @param {number|undefined} filter.min_suspect_score - Filter events with Suspect Score result above a provided minimum threshold.
246
+ * @param {boolean|undefined} filter.developer_tools - Filter events by Developer Tools detection result.
247
+ * @param {boolean|undefined} filter.location_spoofing - Filter events by Location Spoofing detection result.
248
+ * @param {boolean|undefined} filter.mitm_attack - Filter events by MITM (Man-in-the-Middle) Attack detection result.
249
+ * @param {boolean|undefined} filter.proxy - Filter events by Proxy detection result.
250
+ * @param {string|undefined} filter.sdk_version - Filter events by a specific SDK version associated with the identification event (`sdk.version` property).
251
+ * @param {string|undefined} filter.sdk_platform - Filter events by the SDK Platform associated with the identification event (`sdk.platform` property).
252
+ * @param {string[]|undefined} filter.environment - Filter for events by providing one or more environment IDs (`environment_id` property).
253
+ * */
254
+ async searchEvents(filter: SearchEventsFilter): Promise<SearchEventsResponse> {
255
+ return this.callApi({
256
+ path: '/events',
257
+ method: 'get',
258
+ queryParams: filter,
259
+ })
260
+ }
261
+
262
+ private async callApi<Path extends keyof paths, Method extends AllowedMethod<Path>>(
263
+ options: GetRequestPathOptions<Path, Method> & { headers?: Record<string, string>; body?: BodyInit }
264
+ ): Promise<SuccessJsonOrVoid<Path, Method>> {
265
+ const url = getRequestPath({
266
+ ...options,
267
+ region: this.region,
268
+ })
269
+
270
+ let response: Response
271
+ try {
272
+ response = await this.fetch(url, {
273
+ method: options.method.toUpperCase(),
274
+ headers: {
275
+ ...this.defaultHeaders,
276
+ ...options.headers,
277
+ },
278
+ body: options.body,
279
+ })
280
+ } catch (e) {
281
+ throw new SdkError('Network or fetch error', undefined, e as Error)
282
+ }
283
+
284
+ const contentType = response.headers.get('content-type') ?? ''
285
+ const isJson = contentType.includes('application/json')
286
+
287
+ if (response.ok) {
288
+ const hasNoBody = response.status === 204 || response.headers.get('content-length') === '0'
289
+
290
+ if (hasNoBody) {
291
+ return undefined as SuccessJsonOrVoid<Path, Method>
292
+ }
293
+
294
+ if (!isJson) {
295
+ throw new SdkError('Expected JSON response but received non-JSON content type', response)
296
+ }
297
+
298
+ let data
299
+ try {
300
+ data = await response.clone().json()
301
+ } catch (e) {
302
+ throw new SdkError('Failed to parse JSON response', response, toError(e))
303
+ }
304
+ return data as SuccessJsonOrVoid<Path, Method>
305
+ }
306
+
307
+ let errPayload
308
+ try {
309
+ errPayload = await response.clone().json()
310
+ } catch (e) {
311
+ throw new SdkError('Failed to parse JSON response', response, toError(e))
312
+ }
313
+ if (isErrorResponse(errPayload)) {
314
+ if (response.status === 429) {
315
+ throw new TooManyRequestsError(errPayload, response)
316
+ }
317
+ throw new RequestError(errPayload.error.message, errPayload, response.status, errPayload.error.code, response)
318
+ }
319
+ throw RequestError.unknown(response)
320
+ }
321
+ }
package/src/types.ts ADDED
@@ -0,0 +1,90 @@
1
+ import { components, operations, paths } from './generatedApiTypes'
2
+
3
+ export enum Region {
4
+ EU = 'EU',
5
+ AP = 'AP',
6
+ Global = 'Global',
7
+ }
8
+
9
+ /**
10
+ * Options for FingerprintJS server API client
11
+ */
12
+ export interface Options {
13
+ /**
14
+ * Secret API key
15
+ */
16
+ apiKey: string
17
+ /**
18
+ * Region of the FingerprintJS service server
19
+ */
20
+ region?: Region | `${Region}`
21
+
22
+ /**
23
+ * Optional fetch implementation
24
+ * */
25
+ fetch?: typeof fetch
26
+
27
+ /**
28
+ * Optional default headers
29
+ */
30
+ defaultHeaders?: Record<string, string>
31
+ }
32
+
33
+ export type ErrorResponse = components['schemas']['ErrorResponse']
34
+
35
+ /**
36
+ * More info: https://dev.fingerprintjs.com/docs/server-api#query-parameters
37
+ */
38
+ export type SearchEventsFilter = paths['/events']['get']['parameters']['query']
39
+ export type SearchEventsResponse = components['schemas']['EventSearch']
40
+
41
+ /**
42
+ * More info: https://dev.fingerprint.com/reference/server-api-v4-get-event
43
+ */
44
+ export type Event = components['schemas']['Event']
45
+
46
+ export type GetEventOptions = paths['/events/{event_id}']['get']['parameters']['query']
47
+
48
+ export type EventUpdate = components['schemas']['EventUpdate']
49
+
50
+ export type EventRuleAction = components['schemas']['EventRuleAction']
51
+
52
+ // Extract just the `path` parameters as a tuple of strings
53
+ type ExtractPathParamStrings<Path> = Path extends { parameters: { path: infer P } }
54
+ ? P extends Record<string, any>
55
+ ? [P[keyof P]] // We extract the path parameter values as a tuple of strings
56
+ : []
57
+ : []
58
+
59
+ // Utility type to extract query parameters from an operation and differentiate required/optional
60
+ export type ExtractQueryParams<Path> = Path extends { parameters: { query?: infer Q } }
61
+ ? undefined extends Q // Check if Q can be undefined (meaning it's optional)
62
+ ? Q | undefined // If so, it's optional
63
+ : Q // Otherwise, it's required
64
+ : never // If no query parameters, return never
65
+
66
+ // Utility type to extract request body from an operation (for POST, PUT, etc.)
67
+ type ExtractRequestBody<Path> = Path extends { requestBody: { content: { 'application/json': infer B } } } ? B : never
68
+
69
+ // Utility type to extract the response type for 200 status code
70
+ type ExtractResponse<Path> = Path extends { responses: { 200: { content: { 'application/json': infer R } } } }
71
+ ? R
72
+ : void
73
+
74
+ // Extracts args to given API method
75
+ type ApiMethodArgs<Path extends keyof operations> = [
76
+ // If method has body, extract it as first parameter
77
+ ...(ExtractRequestBody<operations[Path]> extends never ? [] : [body: ExtractRequestBody<operations[Path]>]),
78
+ // Next are path params, e.g. for path "/events/{event_id}" it will be one string parameter,
79
+ ...ExtractPathParamStrings<operations[Path]>,
80
+ // Last parameter will be the query params, if any
81
+ ...(ExtractQueryParams<operations[Path]> extends never ? [] : [params: ExtractQueryParams<operations[Path]>]),
82
+ ]
83
+
84
+ type ApiMethod<Path extends keyof operations> = (
85
+ ...args: ApiMethodArgs<Path>
86
+ ) => Promise<ExtractResponse<operations[Path]>>
87
+
88
+ export type FingerprintApi = {
89
+ [Operation in keyof operations]: ApiMethod<Operation>
90
+ }
@@ -0,0 +1,171 @@
1
+ import { ExtractQueryParams, Region } from './types'
2
+ import { version } from '../package.json'
3
+ import { paths } from './generatedApiTypes'
4
+
5
+ const apiVersion = 'v4'
6
+
7
+ const euRegionUrl = 'https://eu.api.fpjs.io/'
8
+ const apRegionUrl = 'https://ap.api.fpjs.io/'
9
+ const globalRegionUrl = 'https://api.fpjs.io/'
10
+
11
+ type QueryStringScalar = string | number | boolean | null | undefined
12
+
13
+ type QueryStringParameters = Record<string, QueryStringScalar | string[]> & {
14
+ api_key?: string
15
+ ii: string
16
+ }
17
+
18
+ export function getIntegrationInfo() {
19
+ return `fingerprint-pro-server-node-sdk/${version}`
20
+ }
21
+
22
+ function serializeQueryStringParams(params: QueryStringParameters): string {
23
+ const entries: [string, string][] = []
24
+
25
+ for (const [key, value] of Object.entries(params)) {
26
+ if (value == null) {
27
+ continue
28
+ }
29
+
30
+ if (Array.isArray(value)) {
31
+ for (const v of value) {
32
+ if (v == null) {
33
+ continue
34
+ }
35
+ entries.push([key, String(v)])
36
+ }
37
+ } else {
38
+ entries.push([key, String(value)])
39
+ }
40
+ }
41
+
42
+ const urlSearchParams = new URLSearchParams(entries)
43
+
44
+ return urlSearchParams.toString()
45
+ }
46
+
47
+ function getServerApiUrl(region: Region): string {
48
+ switch (region) {
49
+ case Region.EU:
50
+ return euRegionUrl
51
+ case Region.AP:
52
+ return apRegionUrl
53
+ case Region.Global:
54
+ return globalRegionUrl
55
+ default:
56
+ throw new Error('Unsupported region')
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Extracts parameter placeholders into a literal union type.
62
+ * For example `extractPathParams<'/users/{userId}/posts/{postId}'>` resolves to `"userId" | "postId"
63
+ */
64
+ type ExtractPathParams<T extends string> = T extends `${string}{${infer Param}}${infer Rest}`
65
+ ? Param | ExtractPathParams<Rest>
66
+ : never
67
+
68
+ type PathParams<Path extends keyof paths> =
69
+ ExtractPathParams<Path> extends never
70
+ ? { pathParams?: never }
71
+ : {
72
+ pathParams: ExtractPathParams<Path> extends never ? never : string[]
73
+ }
74
+
75
+ type QueryParams<Path extends keyof paths, Method extends keyof paths[Path]> =
76
+ ExtractQueryParams<paths[Path][Method]> extends never
77
+ ? { queryParams?: any } // No query params
78
+ : {
79
+ queryParams?: ExtractQueryParams<paths[Path][Method]> // Optional query params
80
+ }
81
+
82
+ type IsNever<Type> = [Exclude<Type, undefined>] extends [never] ? true : false
83
+ export type NonNeverKeys<Type> = {
84
+ [Key in keyof Type]-?: IsNever<Type[Key]> extends true ? never : Key
85
+ }[keyof Type]
86
+ export type AllowedMethod<Path extends keyof paths> = Extract<Exclude<NonNeverKeys<paths[Path]>, 'parameters'>, string>
87
+
88
+ type JsonContentOf<Response> = Response extends { content: { 'application/json': infer T } } ? T : never
89
+
90
+ type UnionJsonFromResponses<Response> = {
91
+ [StatusCode in keyof Response]: JsonContentOf<Response[StatusCode]>
92
+ }[keyof Response]
93
+
94
+ type StartingWithSuccessCode<Response> = {
95
+ [StatusCode in keyof Response]: `${StatusCode & number}` extends `2${number}${number}` ? StatusCode : never
96
+ }[keyof Response]
97
+
98
+ type SuccessResponses<Response> = Pick<Response, Extract<StartingWithSuccessCode<Response>, keyof Response>>
99
+
100
+ type OperationOf<Path extends keyof paths, Method extends AllowedMethod<Path>> = paths[Path][Method]
101
+
102
+ type ResponsesOf<Path extends keyof paths, Method extends AllowedMethod<Path>> =
103
+ OperationOf<Path, Method> extends { responses: infer Response } ? Response : never
104
+
105
+ type SuccessJson<Path extends keyof paths, Method extends AllowedMethod<Path>> = UnionJsonFromResponses<
106
+ SuccessResponses<ResponsesOf<Path, Method>>
107
+ >
108
+
109
+ export type SuccessJsonOrVoid<Path extends keyof paths, Method extends AllowedMethod<Path>> = [
110
+ SuccessJson<Path, Method>,
111
+ ] extends [never]
112
+ ? void
113
+ : SuccessJson<Path, Method>
114
+
115
+ export type GetRequestPathOptions<Path extends keyof paths, Method extends AllowedMethod<Path>> = {
116
+ path: Path
117
+ method: Method
118
+ region?: Region
119
+ } & PathParams<Path> &
120
+ QueryParams<Path, Method>
121
+
122
+ /**
123
+ * Formats a URL for the FingerprintJS server API by replacing placeholders and
124
+ * appending query string parameters.
125
+ *
126
+ * @internal
127
+ *
128
+ * @param {GetRequestPathOptions<Path, Method>} options
129
+ * @param {Path} options.path - The path of the API endpoint
130
+ * @param {string[]} [options.pathParams] - Path parameters to be replaced in the path
131
+ * @param {QueryParams<Path, Method>["queryParams"]} [options.queryParams] - Query string
132
+ * parameters to be appended to the URL
133
+ * @param {Region} options.region - The region of the API endpoint
134
+ * @param {Method} options.method - The method of the API endpoint
135
+ *
136
+ * @returns {string} The formatted URL with parameters replaced and query string
137
+ * parameters appended
138
+ */
139
+ export function getRequestPath<Path extends keyof paths, Method extends AllowedMethod<Path>>({
140
+ path,
141
+ pathParams,
142
+ queryParams,
143
+ region,
144
+ // method mention here so that it can be referenced in JSDoc
145
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
146
+ method: _,
147
+ }: GetRequestPathOptions<Path, Method>): string {
148
+ // Step 1: Extract the path parameters (placeholders) from the path
149
+ const placeholders = Array.from(path.matchAll(/{(.*?)}/g)).map((match) => match[1])
150
+
151
+ // Step 2: Replace the placeholders with provided pathParams
152
+ let formattedPath: string = `${apiVersion}${path}`
153
+ placeholders.forEach((placeholder, index) => {
154
+ if (pathParams?.[index]) {
155
+ formattedPath = formattedPath.replace(`{${placeholder}}`, pathParams[index])
156
+ } else {
157
+ throw new Error(`Missing path parameter for ${placeholder}`)
158
+ }
159
+ })
160
+
161
+ const queryStringParameters: QueryStringParameters = {
162
+ ...(queryParams ?? {}),
163
+ ii: getIntegrationInfo(),
164
+ }
165
+
166
+ const url = new URL(getServerApiUrl(region ?? Region.Global))
167
+ url.pathname = formattedPath
168
+ url.search = serializeQueryStringParams(queryStringParameters)
169
+
170
+ return url.toString()
171
+ }