/
http.ts
529 lines (497 loc) · 13 KB
/
http.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
/**
* Access the HTTP client written in Rust.
*
* This package is also accessible with `window.__TAURI__.http` when `tauri.conf.json > build > withGlobalTauri` is set to true.
*
* The APIs must be allowlisted on `tauri.conf.json`:
* ```json
* {
* "tauri": {
* "allowlist": {
* "http": {
* "all": true, // enable all http APIs
* "request": true // enable HTTP request API
* }
* }
* }
* }
* ```
* It is recommended to allowlist only the APIs you use for optimal bundle size and security.
*
* ## Security
*
* This API has a scope configuration that forces you to restrict the URLs and paths that can be accessed using glob patterns.
*
* For instance, this scope configuration only allows making HTTP requests to the GitHub API for the `tauri-apps` organization:
* ```json
* {
* "tauri": {
* "allowlist": {
* "http": {
* "scope": ["https://api.github.com/repos/tauri-apps/*"]
* }
* }
* }
* }
* ```
* Trying to execute any API with a URL not configured on the scope results in a promise rejection due to denied access.
*
* @module
*/
import { invokeTauriCommand } from './helpers/tauri'
interface Duration {
secs: number
nanos: number
}
interface ClientOptions {
maxRedirections?: number
connectTimeout?: number | Duration
}
enum ResponseType {
JSON = 1,
Text = 2,
Binary = 3
}
interface FilePart<T> {
file: string | T
mime?: string
fileName?: string
}
type Part = string | Uint8Array | FilePart<Uint8Array>
/** The body object to be used on POST and PUT requests. */
class Body {
type: string
payload: unknown
/** @ignore */
private constructor(type: string, payload: unknown) {
this.type = type
this.payload = payload
}
/**
* Creates a new form data body. The form data is an object where each key is the entry name,
* and the value is either a string or a file object.
*
* By default it sets the `application/x-www-form-urlencoded` Content-Type header,
* but you can set it to `multipart/form-data` if the Cargo feature `http-multipart` is enabled.
*
* Note that a file path must be allowed in the `fs` allowlist scope.
* @example
* ```typescript
* import { Body } from "@tauri-apps/api/http"
* Body.form({
* key: 'value',
* image: {
* file: '/path/to/file', // either a path or an array buffer of the file contents
* mime: 'image/jpeg', // optional
* fileName: 'image.jpg' // optional
* }
* });
* ```
*
* @param data The body data.
*
* @return The body object ready to be used on the POST and PUT requests.
*/
static form(data: Record<string, Part>): Body {
const form: Record<string, string | number[] | FilePart<number[]>> = {}
for (const key in data) {
// eslint-disable-next-line security/detect-object-injection
const v = data[key]
let r
if (typeof v === 'string') {
r = v
} else if (v instanceof Uint8Array || Array.isArray(v)) {
r = Array.from(v)
} else if (typeof v.file === 'string') {
r = { file: v.file, mime: v.mime, fileName: v.fileName }
} else {
r = { file: Array.from(v.file), mime: v.mime, fileName: v.fileName }
}
// eslint-disable-next-line security/detect-object-injection
form[key] = r
}
return new Body('Form', form)
}
/**
* Creates a new JSON body.
* @example
* ```typescript
* import { Body } from "@tauri-apps/api/http"
* Body.json({
* registered: true,
* name: 'tauri'
* });
* ```
*
* @param data The body JSON object.
*
* @return The body object ready to be used on the POST and PUT requests.
*/
static json(data: Record<any, any>): Body {
return new Body('Json', data)
}
/**
* Creates a new UTF-8 string body.
* @example
* ```typescript
* import { Body } from "@tauri-apps/api/http"
* Body.text('The body content as a string');
* ```
*
* @param data The body string.
*
* @return The body object ready to be used on the POST and PUT requests.
*/
static text(value: string): Body {
return new Body('Text', value)
}
/**
* Creates a new byte array body.
* @example
* ```typescript
* import { Body } from "@tauri-apps/api/http"
* Body.bytes(new Uint8Array([1, 2, 3]));
* ```
*
* @param data The body byte array.
*
* @return The body object ready to be used on the POST and PUT requests.
*/
static bytes(bytes: Iterable<number> | ArrayLike<number>): Body {
// stringifying Uint8Array doesn't return an array of numbers, so we create one here
return new Body('Bytes', Array.from(bytes))
}
}
/** The request HTTP verb. */
type HttpVerb =
| 'GET'
| 'POST'
| 'PUT'
| 'DELETE'
| 'PATCH'
| 'HEAD'
| 'OPTIONS'
| 'CONNECT'
| 'TRACE'
/** Options object sent to the backend. */
interface HttpOptions {
method: HttpVerb
url: string
headers?: Record<string, any>
query?: Record<string, any>
body?: Body
timeout?: number | Duration
responseType?: ResponseType
}
/** Request options. */
type RequestOptions = Omit<HttpOptions, 'method' | 'url'>
/** Options for the `fetch` API. */
type FetchOptions = Omit<HttpOptions, 'url'>
/** @ignore */
interface IResponse<T> {
url: string
status: number
headers: Record<string, string>
rawHeaders: Record<string, string[]>
data: T
}
/** Response object. */
class Response<T> {
/** The request URL. */
url: string
/** The response status code. */
status: number
/** A boolean indicating whether the response was successful (status in the range 200–299) or not. */
ok: boolean
/** The response headers. */
headers: Record<string, string>
/** The response raw headers. */
rawHeaders: Record<string, string[]>
/** The response data. */
data: T
/** @ignore */
constructor(response: IResponse<T>) {
this.url = response.url
this.status = response.status
this.ok = this.status >= 200 && this.status < 300
this.headers = response.headers
this.rawHeaders = response.rawHeaders
this.data = response.data
}
}
class Client {
id: number
/** @ignore */
constructor(id: number) {
this.id = id
}
/**
* Drops the client instance.
* @example
* ```typescript
* import { getClient } from '@tauri-apps/api/http';
* const client = await getClient();
* await client.drop();
* ```
*
* @returns
*/
async drop(): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Http',
message: {
cmd: 'dropClient',
client: this.id
}
})
}
/**
* Makes an HTTP request.
* @example
* ```typescript
* import { getClient } from '@tauri-apps/api/http';
* const client = await getClient();
* const response = await client.request({
* method: 'GET',
* url: 'http://localhost:3003/users',
* });
* ```
*
* @param options The request options.
* @returns A promise resolving to the response.
*/
async request<T>(options: HttpOptions): Promise<Response<T>> {
const jsonResponse =
!options.responseType || options.responseType === ResponseType.JSON
if (jsonResponse) {
options.responseType = ResponseType.Text
}
return invokeTauriCommand<IResponse<T>>({
__tauriModule: 'Http',
message: {
cmd: 'httpRequest',
client: this.id,
options
}
}).then((res) => {
const response = new Response(res)
if (jsonResponse) {
/* eslint-disable */
try {
// @ts-expect-error
response.data = JSON.parse(response.data as string)
} catch (e) {
if (response.ok && (response.data as unknown as string) === '') {
// @ts-expect-error
response.data = {}
} else if (response.ok) {
throw Error(
`Failed to parse response \`${response.data}\` as JSON: ${e};
try setting the \`responseType\` option to \`ResponseType.Text\` or \`ResponseType.Binary\` if the API does not return a JSON response.`
)
}
}
/* eslint-enable */
return response
}
return response
})
}
/**
* Makes a GET request.
* @example
* ```typescript
* import { getClient, ResponseType } from '@tauri-apps/api/http';
* const client = await getClient();
* const response = await client.get('http://localhost:3003/users', {
* timeout: 30,
* // the expected response type
* responseType: ResponseType.JSON
* });
* ```
*
* @param url The request URL.
* @param options The request options.
* @returns A promise resolving to the response.
*/
async get<T>(url: string, options?: RequestOptions): Promise<Response<T>> {
return this.request({
method: 'GET',
url,
...options
})
}
/**
* Makes a POST request.
* @example
* ```typescript
* import { getClient, Body, ResponseType } from '@tauri-apps/api/http';
* const client = await getClient();
* const response = await client.post('http://localhost:3003/users', {
* body: Body.json({
* name: 'tauri',
* password: 'awesome'
* }),
* // in this case the server returns a simple string
* responseType: ResponseType.Text,
* });
* ```
*
* @param url The request URL.
* @param body The body of the request.
* @param options The request options.
* @returns A promise resolving to the response.
*/
async post<T>(
url: string,
body?: Body,
options?: RequestOptions
): Promise<Response<T>> {
return this.request({
method: 'POST',
url,
body,
...options
})
}
/**
* Makes a PUT request.
* @example
* ```typescript
* import { getClient, Body } from '@tauri-apps/api/http';
* const client = await getClient();
* const response = await client.put('http://localhost:3003/users/1', {
* body: Body.form({
* file: {
* file: '/home/tauri/avatar.png',
* mime: 'image/png',
* fileName: 'avatar.png'
* }
* })
* });
* ```
*
* @param url The request URL.
* @param body The body of the request.
* @param options Request options.
* @returns A promise resolving to the response.
*/
async put<T>(
url: string,
body?: Body,
options?: RequestOptions
): Promise<Response<T>> {
return this.request({
method: 'PUT',
url,
body,
...options
})
}
/**
* Makes a PATCH request.
* @example
* ```typescript
* import { getClient, Body } from '@tauri-apps/api/http';
* const client = await getClient();
* const response = await client.patch('http://localhost:3003/users/1', {
* body: Body.json({ email: 'contact@tauri.app' })
* });
* ```
*
* @param url The request URL.
* @param options The request options.
* @returns A promise resolving to the response.
*/
async patch<T>(url: string, options?: RequestOptions): Promise<Response<T>> {
return this.request({
method: 'PATCH',
url,
...options
})
}
/**
* Makes a DELETE request.
* @example
* ```typescript
* import { getClient } from '@tauri-apps/api/http';
* const client = await getClient();
* const response = await client.delete('http://localhost:3003/users/1');
* ```
*
* @param url The request URL.
* @param options The request options.
* @returns A promise resolving to the response.
*/
async delete<T>(url: string, options?: RequestOptions): Promise<Response<T>> {
return this.request({
method: 'DELETE',
url,
...options
})
}
}
/**
* Creates a new client using the specified options.
* @example
* ```typescript
* import { getClient } from '@tauri-apps/api/http';
* const client = await getClient();
* ```
*
* @param options Client configuration.
*
* @return A promise resolving to the client instance.
*/
async function getClient(options?: ClientOptions): Promise<Client> {
return invokeTauriCommand<number>({
__tauriModule: 'Http',
message: {
cmd: 'createClient',
options
}
}).then((id) => new Client(id))
}
/** @internal */
let defaultClient: Client | null = null
/**
* Perform an HTTP request using the default client.
* @example
* ```typescript
* import { fetch } from '@tauri-apps/api/http';
* const response = await fetch('http://localhost:3003/users/2', {
* method: 'GET',
* timeout: 30,
* });
* ```
*
* @param url The request URL.
* @param options The fetch options.
* @return The response object.
*/
async function fetch<T>(
url: string,
options?: FetchOptions
): Promise<Response<T>> {
if (defaultClient === null) {
defaultClient = await getClient()
}
return defaultClient.request({
url,
method: options?.method ?? 'GET',
...options
})
}
export type {
Duration,
ClientOptions,
Part,
HttpVerb,
HttpOptions,
RequestOptions,
FetchOptions
}
export { getClient, fetch, Body, Client, Response, ResponseType, FilePart }