@tauri-apps/plugin-http 2.0.0-alpha.0 → 2.0.0-alpha.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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # HTTP
1
+ ![plugin-http](https://github.com/tauri-apps/plugins-workspace/raw/v2/plugins/http/banner.png)
2
2
 
3
3
  Access the HTTP client written in Rust.
4
4
 
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Access the HTTP client written in Rust.
2
+ * Make HTTP requests with the Rust backend.
3
3
  *
4
4
  * ## Security
5
5
  *
@@ -25,310 +25,31 @@ declare global {
25
25
  }
26
26
  }
27
27
  /**
28
+ * Options to configure the Rust client used to make fetch requests
29
+ *
28
30
  * @since 2.0.0
29
31
  */
30
- interface Duration {
31
- secs: number;
32
- nanos: number;
33
- }
34
- /**
35
- * @since 2.0.0
36
- */
37
- interface ClientOptions {
32
+ export interface ClientOptions {
38
33
  /**
39
34
  * Defines the maximum number of redirects the client should follow.
40
35
  * If set to 0, no redirects will be followed.
41
36
  */
42
37
  maxRedirections?: number;
43
- connectTimeout?: number | Duration;
44
- }
45
- /**
46
- * @since 2.0.0
47
- */
48
- declare enum ResponseType {
49
- JSON = 1,
50
- Text = 2,
51
- Binary = 3
52
- }
53
- /**
54
- * @since 2.0.0
55
- */
56
- interface FilePart<T> {
57
- file: string | T;
58
- mime?: string;
59
- fileName?: string;
60
- }
61
- type Part = string | Uint8Array | FilePart<Uint8Array>;
62
- /**
63
- * The body object to be used on POST and PUT requests.
64
- *
65
- * @since 2.0.0
66
- */
67
- declare class Body {
68
- type: string;
69
- payload: unknown;
70
- /** @ignore */
71
- private constructor();
72
- /**
73
- * Creates a new form data body. The form data is an object where each key is the entry name,
74
- * and the value is either a string or a file object.
75
- *
76
- * By default it sets the `application/x-www-form-urlencoded` Content-Type header,
77
- * but you can set it to `multipart/form-data` if the Cargo feature `multipart` is enabled.
78
- *
79
- * Note that a file path must be allowed in the `fs` scope.
80
- * @example
81
- * ```typescript
82
- * import { Body } from "@tauri-apps/plugin-http"
83
- * const body = Body.form({
84
- * key: 'value',
85
- * image: {
86
- * file: '/path/to/file', // either a path or an array buffer of the file contents
87
- * mime: 'image/jpeg', // optional
88
- * fileName: 'image.jpg' // optional
89
- * }
90
- * });
91
- *
92
- * // alternatively, use a FormData:
93
- * const form = new FormData();
94
- * form.append('key', 'value');
95
- * form.append('image', file, 'image.png');
96
- * const formBody = Body.form(form);
97
- * ```
98
- *
99
- * @param data The body data.
100
- *
101
- * @returns The body object ready to be used on the POST and PUT requests.
102
- *
103
- * @since 2.0.0
104
- */
105
- static form(data: Record<string, Part> | FormData): Body;
106
- /**
107
- * Creates a new JSON body.
108
- * @example
109
- * ```typescript
110
- * import { Body } from "@tauri-apps/plugin-http"
111
- * Body.json({
112
- * registered: true,
113
- * name: 'tauri'
114
- * });
115
- * ```
116
- *
117
- * @param data The body JSON object.
118
- *
119
- * @returns The body object ready to be used on the POST and PUT requests.
120
- *
121
- * @since 2.0.0
122
- */
123
- static json<K extends string | number | symbol, V>(data: Record<K, V>): Body;
124
- /**
125
- * Creates a new UTF-8 string body.
126
- * @example
127
- * ```typescript
128
- * import { Body } from "@tauri-apps/plugin-http"
129
- * Body.text('The body content as a string');
130
- * ```
131
- *
132
- * @param value The body string.
133
- *
134
- * @returns The body object ready to be used on the POST and PUT requests.
135
- *
136
- * @since 2.0.0
137
- */
138
- static text(value: string): Body;
139
- /**
140
- * Creates a new byte array body.
141
- * @example
142
- * ```typescript
143
- * import { Body } from "@tauri-apps/plugin-http"
144
- * Body.bytes(new Uint8Array([1, 2, 3]));
145
- * ```
146
- *
147
- * @param bytes The body byte array.
148
- *
149
- * @returns The body object ready to be used on the POST and PUT requests.
150
- *
151
- * @since 2.0.0
152
- */
153
- static bytes(bytes: Iterable<number> | ArrayLike<number> | ArrayBuffer): Body;
154
- }
155
- /** The request HTTP verb. */
156
- type HttpVerb = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS" | "CONNECT" | "TRACE";
157
- /**
158
- * Options object sent to the backend.
159
- *
160
- * @since 2.0.0
161
- */
162
- interface HttpOptions {
163
- method: HttpVerb;
164
- url: string;
165
- headers?: Record<string, unknown>;
166
- query?: Record<string, unknown>;
167
- body?: Body;
168
- timeout?: number | Duration;
169
- responseType?: ResponseType;
170
- }
171
- /** Request options. */
172
- type RequestOptions = Omit<HttpOptions, "method" | "url">;
173
- /** Options for the `fetch` API. */
174
- type FetchOptions = Omit<HttpOptions, "url">;
175
- /** @ignore */
176
- interface IResponse<T> {
177
- url: string;
178
- status: number;
179
- headers: Record<string, string>;
180
- rawHeaders: Record<string, string[]>;
181
- data: T;
38
+ /** Timeout in milliseconds */
39
+ connectTimeout?: number;
182
40
  }
183
41
  /**
184
- * Response object.
42
+ * Fetch a resource from the network. It returns a `Promise` that resolves to the
43
+ * `Response` to that `Request`, whether it is successful or not.
185
44
  *
186
- * @since 2.0.0
187
- * */
188
- declare class Response<T> {
189
- /** The request URL. */
190
- url: string;
191
- /** The response status code. */
192
- status: number;
193
- /** A boolean indicating whether the response was successful (status in the range 200–299) or not. */
194
- ok: boolean;
195
- /** The response headers. */
196
- headers: Record<string, string>;
197
- /** The response raw headers. */
198
- rawHeaders: Record<string, string[]>;
199
- /** The response data. */
200
- data: T;
201
- /** @ignore */
202
- constructor(response: IResponse<T>);
203
- }
204
- /**
205
- * @since 2.0.0
206
- */
207
- declare class Client {
208
- id: number;
209
- /** @ignore */
210
- constructor(id: number);
211
- /**
212
- * Drops the client instance.
213
- * @example
214
- * ```typescript
215
- * import { getClient } from '@tauri-apps/plugin-http';
216
- * const client = await getClient();
217
- * await client.drop();
218
- * ```
219
- */
220
- drop(): Promise<void>;
221
- /**
222
- * Makes an HTTP request.
223
- * @example
224
- * ```typescript
225
- * import { getClient } from '@tauri-apps/plugin-http';
226
- * const client = await getClient();
227
- * const response = await client.request({
228
- * method: 'GET',
229
- * url: 'http://localhost:3003/users',
230
- * });
231
- * ```
232
- */
233
- request<T>(options: HttpOptions): Promise<Response<T>>;
234
- /**
235
- * Makes a GET request.
236
- * @example
237
- * ```typescript
238
- * import { getClient, ResponseType } from '@tauri-apps/plugin-http';
239
- * const client = await getClient();
240
- * const response = await client.get('http://localhost:3003/users', {
241
- * timeout: 30,
242
- * // the expected response type
243
- * responseType: ResponseType.JSON
244
- * });
245
- * ```
246
- */
247
- get<T>(url: string, options?: RequestOptions): Promise<Response<T>>;
248
- /**
249
- * Makes a POST request.
250
- * @example
251
- * ```typescript
252
- * import { getClient, Body, ResponseType } from '@tauri-apps/plugin-http';
253
- * const client = await getClient();
254
- * const response = await client.post('http://localhost:3003/users', {
255
- * body: Body.json({
256
- * name: 'tauri',
257
- * password: 'awesome'
258
- * }),
259
- * // in this case the server returns a simple string
260
- * responseType: ResponseType.Text,
261
- * });
262
- * ```
263
- */
264
- post<T>(url: string, body?: Body, options?: RequestOptions): Promise<Response<T>>;
265
- /**
266
- * Makes a PUT request.
267
- * @example
268
- * ```typescript
269
- * import { getClient, Body } from '@tauri-apps/plugin-http';
270
- * const client = await getClient();
271
- * const response = await client.put('http://localhost:3003/users/1', {
272
- * body: Body.form({
273
- * file: {
274
- * file: '/home/tauri/avatar.png',
275
- * mime: 'image/png',
276
- * fileName: 'avatar.png'
277
- * }
278
- * })
279
- * });
280
- * ```
281
- */
282
- put<T>(url: string, body?: Body, options?: RequestOptions): Promise<Response<T>>;
283
- /**
284
- * Makes a PATCH request.
285
- * @example
286
- * ```typescript
287
- * import { getClient, Body } from '@tauri-apps/plugin-http';
288
- * const client = await getClient();
289
- * const response = await client.patch('http://localhost:3003/users/1', {
290
- * body: Body.json({ email: 'contact@tauri.app' })
291
- * });
292
- * ```
293
- */
294
- patch<T>(url: string, options?: RequestOptions): Promise<Response<T>>;
295
- /**
296
- * Makes a DELETE request.
297
- * @example
298
- * ```typescript
299
- * import { getClient } from '@tauri-apps/plugin-http';
300
- * const client = await getClient();
301
- * const response = await client.delete('http://localhost:3003/users/1');
302
- * ```
303
- */
304
- delete<T>(url: string, options?: RequestOptions): Promise<Response<T>>;
305
- }
306
- /**
307
- * Creates a new client using the specified options.
308
45
  * @example
309
46
  * ```typescript
310
- * import { getClient } from '@tauri-apps/plugin-http';
311
- * const client = await getClient();
47
+ * const response = await fetch("http://my.json.host/data.json");
48
+ * console.log(response.status); // e.g. 200
49
+ * console.log(response.statusText); // e.g. "OK"
50
+ * const jsonData = await response.json();
312
51
  * ```
313
52
  *
314
- * @param options Client configuration.
315
- *
316
- * @returns A promise resolving to the client instance.
317
- *
318
53
  * @since 2.0.0
319
54
  */
320
- declare function getClient(options?: ClientOptions): Promise<Client>;
321
- /**
322
- * Perform an HTTP request using the default client.
323
- * @example
324
- * ```typescript
325
- * import { fetch } from '@tauri-apps/plugin-http';
326
- * const response = await fetch('http://localhost:3003/users/2', {
327
- * method: 'GET',
328
- * timeout: 30,
329
- * });
330
- * ```
331
- */
332
- declare function fetch<T>(url: string, options?: FetchOptions): Promise<Response<T>>;
333
- export type { Duration, ClientOptions, Part, HttpVerb, HttpOptions, RequestOptions, FetchOptions, };
334
- export { getClient, fetch, Body, Client, Response, ResponseType, type FilePart, };
55
+ export declare function fetch(input: URL | Request | string, init?: RequestInit & ClientOptions): Promise<Response>;
@@ -2,380 +2,59 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // SPDX-License-Identifier: MIT
4
4
  /**
5
- * @since 2.0.0
6
- */
7
- var ResponseType;
8
- (function (ResponseType) {
9
- ResponseType[ResponseType["JSON"] = 1] = "JSON";
10
- ResponseType[ResponseType["Text"] = 2] = "Text";
11
- ResponseType[ResponseType["Binary"] = 3] = "Binary";
12
- })(ResponseType || (ResponseType = {}));
13
- /**
14
- * The body object to be used on POST and PUT requests.
15
- *
16
- * @since 2.0.0
17
- */
18
- class Body {
19
- /** @ignore */
20
- constructor(type, payload) {
21
- this.type = type;
22
- this.payload = payload;
23
- }
24
- /**
25
- * Creates a new form data body. The form data is an object where each key is the entry name,
26
- * and the value is either a string or a file object.
27
- *
28
- * By default it sets the `application/x-www-form-urlencoded` Content-Type header,
29
- * but you can set it to `multipart/form-data` if the Cargo feature `multipart` is enabled.
30
- *
31
- * Note that a file path must be allowed in the `fs` scope.
32
- * @example
33
- * ```typescript
34
- * import { Body } from "@tauri-apps/plugin-http"
35
- * const body = Body.form({
36
- * key: 'value',
37
- * image: {
38
- * file: '/path/to/file', // either a path or an array buffer of the file contents
39
- * mime: 'image/jpeg', // optional
40
- * fileName: 'image.jpg' // optional
41
- * }
42
- * });
43
- *
44
- * // alternatively, use a FormData:
45
- * const form = new FormData();
46
- * form.append('key', 'value');
47
- * form.append('image', file, 'image.png');
48
- * const formBody = Body.form(form);
49
- * ```
50
- *
51
- * @param data The body data.
52
- *
53
- * @returns The body object ready to be used on the POST and PUT requests.
54
- *
55
- * @since 2.0.0
56
- */
57
- static form(data) {
58
- const form = {};
59
- const append = (key, v) => {
60
- if (v !== null) {
61
- let r;
62
- if (typeof v === "string") {
63
- r = v;
64
- }
65
- else if (v instanceof Uint8Array || Array.isArray(v)) {
66
- r = Array.from(v);
67
- }
68
- else if (v instanceof File) {
69
- r = { file: v.name, mime: v.type, fileName: v.name };
70
- }
71
- else if (typeof v.file === "string") {
72
- r = { file: v.file, mime: v.mime, fileName: v.fileName };
73
- }
74
- else {
75
- r = { file: Array.from(v.file), mime: v.mime, fileName: v.fileName };
76
- }
77
- form[String(key)] = r;
78
- }
79
- };
80
- if (data instanceof FormData) {
81
- for (const [key, value] of data) {
82
- append(key, value);
83
- }
84
- }
85
- else {
86
- for (const [key, value] of Object.entries(data)) {
87
- append(key, value);
88
- }
89
- }
90
- return new Body("Form", form);
91
- }
92
- /**
93
- * Creates a new JSON body.
94
- * @example
95
- * ```typescript
96
- * import { Body } from "@tauri-apps/plugin-http"
97
- * Body.json({
98
- * registered: true,
99
- * name: 'tauri'
100
- * });
101
- * ```
102
- *
103
- * @param data The body JSON object.
104
- *
105
- * @returns The body object ready to be used on the POST and PUT requests.
106
- *
107
- * @since 2.0.0
108
- */
109
- static json(data) {
110
- return new Body("Json", data);
111
- }
112
- /**
113
- * Creates a new UTF-8 string body.
114
- * @example
115
- * ```typescript
116
- * import { Body } from "@tauri-apps/plugin-http"
117
- * Body.text('The body content as a string');
118
- * ```
119
- *
120
- * @param value The body string.
121
- *
122
- * @returns The body object ready to be used on the POST and PUT requests.
123
- *
124
- * @since 2.0.0
125
- */
126
- static text(value) {
127
- return new Body("Text", value);
128
- }
129
- /**
130
- * Creates a new byte array body.
131
- * @example
132
- * ```typescript
133
- * import { Body } from "@tauri-apps/plugin-http"
134
- * Body.bytes(new Uint8Array([1, 2, 3]));
135
- * ```
136
- *
137
- * @param bytes The body byte array.
138
- *
139
- * @returns The body object ready to be used on the POST and PUT requests.
140
- *
141
- * @since 2.0.0
142
- */
143
- static bytes(bytes) {
144
- // stringifying Uint8Array doesn't return an array of numbers, so we create one here
145
- return new Body("Bytes", Array.from(bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : bytes));
146
- }
147
- }
148
- /**
149
- * Response object.
5
+ * Fetch a resource from the network. It returns a `Promise` that resolves to the
6
+ * `Response` to that `Request`, whether it is successful or not.
150
7
  *
151
- * @since 2.0.0
152
- * */
153
- class Response {
154
- /** @ignore */
155
- constructor(response) {
156
- this.url = response.url;
157
- this.status = response.status;
158
- this.ok = this.status >= 200 && this.status < 300;
159
- this.headers = response.headers;
160
- this.rawHeaders = response.rawHeaders;
161
- this.data = response.data;
162
- }
163
- }
164
- /**
165
- * @since 2.0.0
166
- */
167
- class Client {
168
- /** @ignore */
169
- constructor(id) {
170
- this.id = id;
171
- }
172
- /**
173
- * Drops the client instance.
174
- * @example
175
- * ```typescript
176
- * import { getClient } from '@tauri-apps/plugin-http';
177
- * const client = await getClient();
178
- * await client.drop();
179
- * ```
180
- */
181
- async drop() {
182
- return window.__TAURI_INVOKE__("plugin:http|drop_client", {
183
- client: this.id,
184
- });
185
- }
186
- /**
187
- * Makes an HTTP request.
188
- * @example
189
- * ```typescript
190
- * import { getClient } from '@tauri-apps/plugin-http';
191
- * const client = await getClient();
192
- * const response = await client.request({
193
- * method: 'GET',
194
- * url: 'http://localhost:3003/users',
195
- * });
196
- * ```
197
- */
198
- async request(options) {
199
- const jsonResponse = !options.responseType || options.responseType === ResponseType.JSON;
200
- if (jsonResponse) {
201
- options.responseType = ResponseType.Text;
202
- }
203
- return window
204
- .__TAURI_INVOKE__("plugin:http|request", {
205
- clientId: this.id,
206
- options,
207
- })
208
- .then((res) => {
209
- const response = new Response(res);
210
- if (jsonResponse) {
211
- /* eslint-disable */
212
- try {
213
- response.data = JSON.parse(response.data);
214
- }
215
- catch (e) {
216
- if (response.ok && response.data === "") {
217
- response.data = {};
218
- }
219
- else if (response.ok) {
220
- throw Error(`Failed to parse response \`${response.data}\` as JSON: ${e};
221
- try setting the \`responseType\` option to \`ResponseType.Text\` or \`ResponseType.Binary\` if the API does not return a JSON response.`);
222
- }
223
- }
224
- /* eslint-enable */
225
- return response;
226
- }
227
- return response;
228
- });
229
- }
230
- /**
231
- * Makes a GET request.
232
- * @example
233
- * ```typescript
234
- * import { getClient, ResponseType } from '@tauri-apps/plugin-http';
235
- * const client = await getClient();
236
- * const response = await client.get('http://localhost:3003/users', {
237
- * timeout: 30,
238
- * // the expected response type
239
- * responseType: ResponseType.JSON
240
- * });
241
- * ```
242
- */
243
- async get(url, options) {
244
- return this.request({
245
- method: "GET",
246
- url,
247
- ...options,
248
- });
249
- }
250
- /**
251
- * Makes a POST request.
252
- * @example
253
- * ```typescript
254
- * import { getClient, Body, ResponseType } from '@tauri-apps/plugin-http';
255
- * const client = await getClient();
256
- * const response = await client.post('http://localhost:3003/users', {
257
- * body: Body.json({
258
- * name: 'tauri',
259
- * password: 'awesome'
260
- * }),
261
- * // in this case the server returns a simple string
262
- * responseType: ResponseType.Text,
263
- * });
264
- * ```
265
- */
266
- async post(url, body, options) {
267
- return this.request({
268
- method: "POST",
269
- url,
270
- body,
271
- ...options,
272
- });
273
- }
274
- /**
275
- * Makes a PUT request.
276
- * @example
277
- * ```typescript
278
- * import { getClient, Body } from '@tauri-apps/plugin-http';
279
- * const client = await getClient();
280
- * const response = await client.put('http://localhost:3003/users/1', {
281
- * body: Body.form({
282
- * file: {
283
- * file: '/home/tauri/avatar.png',
284
- * mime: 'image/png',
285
- * fileName: 'avatar.png'
286
- * }
287
- * })
288
- * });
289
- * ```
290
- */
291
- async put(url, body, options) {
292
- return this.request({
293
- method: "PUT",
294
- url,
295
- body,
296
- ...options,
297
- });
298
- }
299
- /**
300
- * Makes a PATCH request.
301
- * @example
302
- * ```typescript
303
- * import { getClient, Body } from '@tauri-apps/plugin-http';
304
- * const client = await getClient();
305
- * const response = await client.patch('http://localhost:3003/users/1', {
306
- * body: Body.json({ email: 'contact@tauri.app' })
307
- * });
308
- * ```
309
- */
310
- async patch(url, options) {
311
- return this.request({
312
- method: "PATCH",
313
- url,
314
- ...options,
315
- });
316
- }
317
- /**
318
- * Makes a DELETE request.
319
- * @example
320
- * ```typescript
321
- * import { getClient } from '@tauri-apps/plugin-http';
322
- * const client = await getClient();
323
- * const response = await client.delete('http://localhost:3003/users/1');
324
- * ```
325
- */
326
- async delete(url, options) {
327
- return this.request({
328
- method: "DELETE",
329
- url,
330
- ...options,
331
- });
332
- }
333
- }
334
- /**
335
- * Creates a new client using the specified options.
336
8
  * @example
337
9
  * ```typescript
338
- * import { getClient } from '@tauri-apps/plugin-http';
339
- * const client = await getClient();
10
+ * const response = await fetch("http://my.json.host/data.json");
11
+ * console.log(response.status); // e.g. 200
12
+ * console.log(response.statusText); // e.g. "OK"
13
+ * const jsonData = await response.json();
340
14
  * ```
341
15
  *
342
- * @param options Client configuration.
343
- *
344
- * @returns A promise resolving to the client instance.
345
- *
346
16
  * @since 2.0.0
347
17
  */
348
- async function getClient(options) {
349
- return window
350
- .__TAURI_INVOKE__("plugin:http|create_client", {
351
- options,
352
- })
353
- .then((id) => new Client(id));
354
- }
355
- /** @internal */
356
- let defaultClient = null;
357
- /**
358
- * Perform an HTTP request using the default client.
359
- * @example
360
- * ```typescript
361
- * import { fetch } from '@tauri-apps/plugin-http';
362
- * const response = await fetch('http://localhost:3003/users/2', {
363
- * method: 'GET',
364
- * timeout: 30,
365
- * });
366
- * ```
367
- */
368
- async function fetch(url, options) {
369
- var _a;
370
- if (defaultClient === null) {
371
- defaultClient = await getClient();
372
- }
373
- return defaultClient.request({
374
- url,
375
- method: (_a = options === null || options === void 0 ? void 0 : options.method) !== null && _a !== void 0 ? _a : "GET",
376
- ...options,
18
+ async function fetch(input, init) {
19
+ const maxRedirections = init === null || init === void 0 ? void 0 : init.maxRedirections;
20
+ const connectTimeout = init === null || init === void 0 ? void 0 : init.maxRedirections;
21
+ // Remove these fields before creating the request
22
+ if (init) {
23
+ delete init.maxRedirections;
24
+ delete init.connectTimeout;
25
+ }
26
+ const req = new Request(input, init);
27
+ const buffer = await req.arrayBuffer();
28
+ const reqData = buffer.byteLength ? Array.from(new Uint8Array(buffer)) : null;
29
+ const rid = await window.__TAURI_INVOKE__("plugin:http|fetch", {
30
+ cmd: "fetch",
31
+ method: req.method,
32
+ url: req.url,
33
+ headers: Array.from(req.headers.entries()),
34
+ data: reqData,
35
+ maxRedirections,
36
+ connectTimeout,
37
+ });
38
+ req.signal.addEventListener("abort", () => {
39
+ window.__TAURI_INVOKE__("plugin:http|fetch_cancel", {
40
+ rid,
41
+ });
42
+ });
43
+ const { status, statusText, url, headers } = await window.__TAURI_INVOKE__("plugin:http|fetch_send", {
44
+ rid,
45
+ });
46
+ const body = await window.__TAURI_INVOKE__("plugin:http|fetch_read_body", {
47
+ rid,
48
+ });
49
+ const res = new Response(Uint8Array.from(body), {
50
+ headers,
51
+ status,
52
+ statusText,
377
53
  });
54
+ // url is read only but seems like we can do this
55
+ Object.defineProperty(res, "url", { value: url });
56
+ return res;
378
57
  }
379
58
 
380
- export { Body, Client, Response, ResponseType, fetch, getClient };
59
+ export { fetch };
381
60
  //# sourceMappingURL=index.min.js.map
package/dist-js/index.mjs CHANGED
@@ -2,380 +2,59 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
  // SPDX-License-Identifier: MIT
4
4
  /**
5
- * @since 2.0.0
6
- */
7
- var ResponseType;
8
- (function (ResponseType) {
9
- ResponseType[ResponseType["JSON"] = 1] = "JSON";
10
- ResponseType[ResponseType["Text"] = 2] = "Text";
11
- ResponseType[ResponseType["Binary"] = 3] = "Binary";
12
- })(ResponseType || (ResponseType = {}));
13
- /**
14
- * The body object to be used on POST and PUT requests.
15
- *
16
- * @since 2.0.0
17
- */
18
- class Body {
19
- /** @ignore */
20
- constructor(type, payload) {
21
- this.type = type;
22
- this.payload = payload;
23
- }
24
- /**
25
- * Creates a new form data body. The form data is an object where each key is the entry name,
26
- * and the value is either a string or a file object.
27
- *
28
- * By default it sets the `application/x-www-form-urlencoded` Content-Type header,
29
- * but you can set it to `multipart/form-data` if the Cargo feature `multipart` is enabled.
30
- *
31
- * Note that a file path must be allowed in the `fs` scope.
32
- * @example
33
- * ```typescript
34
- * import { Body } from "@tauri-apps/plugin-http"
35
- * const body = Body.form({
36
- * key: 'value',
37
- * image: {
38
- * file: '/path/to/file', // either a path or an array buffer of the file contents
39
- * mime: 'image/jpeg', // optional
40
- * fileName: 'image.jpg' // optional
41
- * }
42
- * });
43
- *
44
- * // alternatively, use a FormData:
45
- * const form = new FormData();
46
- * form.append('key', 'value');
47
- * form.append('image', file, 'image.png');
48
- * const formBody = Body.form(form);
49
- * ```
50
- *
51
- * @param data The body data.
52
- *
53
- * @returns The body object ready to be used on the POST and PUT requests.
54
- *
55
- * @since 2.0.0
56
- */
57
- static form(data) {
58
- const form = {};
59
- const append = (key, v) => {
60
- if (v !== null) {
61
- let r;
62
- if (typeof v === "string") {
63
- r = v;
64
- }
65
- else if (v instanceof Uint8Array || Array.isArray(v)) {
66
- r = Array.from(v);
67
- }
68
- else if (v instanceof File) {
69
- r = { file: v.name, mime: v.type, fileName: v.name };
70
- }
71
- else if (typeof v.file === "string") {
72
- r = { file: v.file, mime: v.mime, fileName: v.fileName };
73
- }
74
- else {
75
- r = { file: Array.from(v.file), mime: v.mime, fileName: v.fileName };
76
- }
77
- form[String(key)] = r;
78
- }
79
- };
80
- if (data instanceof FormData) {
81
- for (const [key, value] of data) {
82
- append(key, value);
83
- }
84
- }
85
- else {
86
- for (const [key, value] of Object.entries(data)) {
87
- append(key, value);
88
- }
89
- }
90
- return new Body("Form", form);
91
- }
92
- /**
93
- * Creates a new JSON body.
94
- * @example
95
- * ```typescript
96
- * import { Body } from "@tauri-apps/plugin-http"
97
- * Body.json({
98
- * registered: true,
99
- * name: 'tauri'
100
- * });
101
- * ```
102
- *
103
- * @param data The body JSON object.
104
- *
105
- * @returns The body object ready to be used on the POST and PUT requests.
106
- *
107
- * @since 2.0.0
108
- */
109
- static json(data) {
110
- return new Body("Json", data);
111
- }
112
- /**
113
- * Creates a new UTF-8 string body.
114
- * @example
115
- * ```typescript
116
- * import { Body } from "@tauri-apps/plugin-http"
117
- * Body.text('The body content as a string');
118
- * ```
119
- *
120
- * @param value The body string.
121
- *
122
- * @returns The body object ready to be used on the POST and PUT requests.
123
- *
124
- * @since 2.0.0
125
- */
126
- static text(value) {
127
- return new Body("Text", value);
128
- }
129
- /**
130
- * Creates a new byte array body.
131
- * @example
132
- * ```typescript
133
- * import { Body } from "@tauri-apps/plugin-http"
134
- * Body.bytes(new Uint8Array([1, 2, 3]));
135
- * ```
136
- *
137
- * @param bytes The body byte array.
138
- *
139
- * @returns The body object ready to be used on the POST and PUT requests.
140
- *
141
- * @since 2.0.0
142
- */
143
- static bytes(bytes) {
144
- // stringifying Uint8Array doesn't return an array of numbers, so we create one here
145
- return new Body("Bytes", Array.from(bytes instanceof ArrayBuffer ? new Uint8Array(bytes) : bytes));
146
- }
147
- }
148
- /**
149
- * Response object.
5
+ * Fetch a resource from the network. It returns a `Promise` that resolves to the
6
+ * `Response` to that `Request`, whether it is successful or not.
150
7
  *
151
- * @since 2.0.0
152
- * */
153
- class Response {
154
- /** @ignore */
155
- constructor(response) {
156
- this.url = response.url;
157
- this.status = response.status;
158
- this.ok = this.status >= 200 && this.status < 300;
159
- this.headers = response.headers;
160
- this.rawHeaders = response.rawHeaders;
161
- this.data = response.data;
162
- }
163
- }
164
- /**
165
- * @since 2.0.0
166
- */
167
- class Client {
168
- /** @ignore */
169
- constructor(id) {
170
- this.id = id;
171
- }
172
- /**
173
- * Drops the client instance.
174
- * @example
175
- * ```typescript
176
- * import { getClient } from '@tauri-apps/plugin-http';
177
- * const client = await getClient();
178
- * await client.drop();
179
- * ```
180
- */
181
- async drop() {
182
- return window.__TAURI_INVOKE__("plugin:http|drop_client", {
183
- client: this.id,
184
- });
185
- }
186
- /**
187
- * Makes an HTTP request.
188
- * @example
189
- * ```typescript
190
- * import { getClient } from '@tauri-apps/plugin-http';
191
- * const client = await getClient();
192
- * const response = await client.request({
193
- * method: 'GET',
194
- * url: 'http://localhost:3003/users',
195
- * });
196
- * ```
197
- */
198
- async request(options) {
199
- const jsonResponse = !options.responseType || options.responseType === ResponseType.JSON;
200
- if (jsonResponse) {
201
- options.responseType = ResponseType.Text;
202
- }
203
- return window
204
- .__TAURI_INVOKE__("plugin:http|request", {
205
- clientId: this.id,
206
- options,
207
- })
208
- .then((res) => {
209
- const response = new Response(res);
210
- if (jsonResponse) {
211
- /* eslint-disable */
212
- try {
213
- response.data = JSON.parse(response.data);
214
- }
215
- catch (e) {
216
- if (response.ok && response.data === "") {
217
- response.data = {};
218
- }
219
- else if (response.ok) {
220
- throw Error(`Failed to parse response \`${response.data}\` as JSON: ${e};
221
- try setting the \`responseType\` option to \`ResponseType.Text\` or \`ResponseType.Binary\` if the API does not return a JSON response.`);
222
- }
223
- }
224
- /* eslint-enable */
225
- return response;
226
- }
227
- return response;
228
- });
229
- }
230
- /**
231
- * Makes a GET request.
232
- * @example
233
- * ```typescript
234
- * import { getClient, ResponseType } from '@tauri-apps/plugin-http';
235
- * const client = await getClient();
236
- * const response = await client.get('http://localhost:3003/users', {
237
- * timeout: 30,
238
- * // the expected response type
239
- * responseType: ResponseType.JSON
240
- * });
241
- * ```
242
- */
243
- async get(url, options) {
244
- return this.request({
245
- method: "GET",
246
- url,
247
- ...options,
248
- });
249
- }
250
- /**
251
- * Makes a POST request.
252
- * @example
253
- * ```typescript
254
- * import { getClient, Body, ResponseType } from '@tauri-apps/plugin-http';
255
- * const client = await getClient();
256
- * const response = await client.post('http://localhost:3003/users', {
257
- * body: Body.json({
258
- * name: 'tauri',
259
- * password: 'awesome'
260
- * }),
261
- * // in this case the server returns a simple string
262
- * responseType: ResponseType.Text,
263
- * });
264
- * ```
265
- */
266
- async post(url, body, options) {
267
- return this.request({
268
- method: "POST",
269
- url,
270
- body,
271
- ...options,
272
- });
273
- }
274
- /**
275
- * Makes a PUT request.
276
- * @example
277
- * ```typescript
278
- * import { getClient, Body } from '@tauri-apps/plugin-http';
279
- * const client = await getClient();
280
- * const response = await client.put('http://localhost:3003/users/1', {
281
- * body: Body.form({
282
- * file: {
283
- * file: '/home/tauri/avatar.png',
284
- * mime: 'image/png',
285
- * fileName: 'avatar.png'
286
- * }
287
- * })
288
- * });
289
- * ```
290
- */
291
- async put(url, body, options) {
292
- return this.request({
293
- method: "PUT",
294
- url,
295
- body,
296
- ...options,
297
- });
298
- }
299
- /**
300
- * Makes a PATCH request.
301
- * @example
302
- * ```typescript
303
- * import { getClient, Body } from '@tauri-apps/plugin-http';
304
- * const client = await getClient();
305
- * const response = await client.patch('http://localhost:3003/users/1', {
306
- * body: Body.json({ email: 'contact@tauri.app' })
307
- * });
308
- * ```
309
- */
310
- async patch(url, options) {
311
- return this.request({
312
- method: "PATCH",
313
- url,
314
- ...options,
315
- });
316
- }
317
- /**
318
- * Makes a DELETE request.
319
- * @example
320
- * ```typescript
321
- * import { getClient } from '@tauri-apps/plugin-http';
322
- * const client = await getClient();
323
- * const response = await client.delete('http://localhost:3003/users/1');
324
- * ```
325
- */
326
- async delete(url, options) {
327
- return this.request({
328
- method: "DELETE",
329
- url,
330
- ...options,
331
- });
332
- }
333
- }
334
- /**
335
- * Creates a new client using the specified options.
336
8
  * @example
337
9
  * ```typescript
338
- * import { getClient } from '@tauri-apps/plugin-http';
339
- * const client = await getClient();
10
+ * const response = await fetch("http://my.json.host/data.json");
11
+ * console.log(response.status); // e.g. 200
12
+ * console.log(response.statusText); // e.g. "OK"
13
+ * const jsonData = await response.json();
340
14
  * ```
341
15
  *
342
- * @param options Client configuration.
343
- *
344
- * @returns A promise resolving to the client instance.
345
- *
346
16
  * @since 2.0.0
347
17
  */
348
- async function getClient(options) {
349
- return window
350
- .__TAURI_INVOKE__("plugin:http|create_client", {
351
- options,
352
- })
353
- .then((id) => new Client(id));
354
- }
355
- /** @internal */
356
- let defaultClient = null;
357
- /**
358
- * Perform an HTTP request using the default client.
359
- * @example
360
- * ```typescript
361
- * import { fetch } from '@tauri-apps/plugin-http';
362
- * const response = await fetch('http://localhost:3003/users/2', {
363
- * method: 'GET',
364
- * timeout: 30,
365
- * });
366
- * ```
367
- */
368
- async function fetch(url, options) {
369
- var _a;
370
- if (defaultClient === null) {
371
- defaultClient = await getClient();
372
- }
373
- return defaultClient.request({
374
- url,
375
- method: (_a = options === null || options === void 0 ? void 0 : options.method) !== null && _a !== void 0 ? _a : "GET",
376
- ...options,
18
+ async function fetch(input, init) {
19
+ const maxRedirections = init === null || init === void 0 ? void 0 : init.maxRedirections;
20
+ const connectTimeout = init === null || init === void 0 ? void 0 : init.maxRedirections;
21
+ // Remove these fields before creating the request
22
+ if (init) {
23
+ delete init.maxRedirections;
24
+ delete init.connectTimeout;
25
+ }
26
+ const req = new Request(input, init);
27
+ const buffer = await req.arrayBuffer();
28
+ const reqData = buffer.byteLength ? Array.from(new Uint8Array(buffer)) : null;
29
+ const rid = await window.__TAURI_INVOKE__("plugin:http|fetch", {
30
+ cmd: "fetch",
31
+ method: req.method,
32
+ url: req.url,
33
+ headers: Array.from(req.headers.entries()),
34
+ data: reqData,
35
+ maxRedirections,
36
+ connectTimeout,
37
+ });
38
+ req.signal.addEventListener("abort", () => {
39
+ window.__TAURI_INVOKE__("plugin:http|fetch_cancel", {
40
+ rid,
41
+ });
42
+ });
43
+ const { status, statusText, url, headers } = await window.__TAURI_INVOKE__("plugin:http|fetch_send", {
44
+ rid,
45
+ });
46
+ const body = await window.__TAURI_INVOKE__("plugin:http|fetch_read_body", {
47
+ rid,
48
+ });
49
+ const res = new Response(Uint8Array.from(body), {
50
+ headers,
51
+ status,
52
+ statusText,
377
53
  });
54
+ // url is read only but seems like we can do this
55
+ Object.defineProperty(res, "url", { value: url });
56
+ return res;
378
57
  }
379
58
 
380
- export { Body, Client, Response, ResponseType, fetch, getClient };
59
+ export { fetch };
381
60
  //# sourceMappingURL=index.mjs.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tauri-apps/plugin-http",
3
- "version": "2.0.0-alpha.0",
3
+ "version": "2.0.0-alpha.1",
4
4
  "license": "MIT or APACHE-2.0",
5
5
  "authors": [
6
6
  "Tauri Programme within The Commons Conservancy"
@@ -24,7 +24,7 @@
24
24
  "tslib": "^2.5.0"
25
25
  },
26
26
  "dependencies": {
27
- "@tauri-apps/api": "2.0.0-alpha.4"
27
+ "@tauri-apps/api": "2.0.0-alpha.6"
28
28
  },
29
29
  "scripts": {
30
30
  "build": "rollup -c"