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
|
// Copyright 2018 the Deno authors. All rights reserved. MIT license.
import { assert, createResolvable, notImplemented } from "./util";
import * as flatbuffers from "./flatbuffers";
import { sendAsync } from "./dispatch";
import * as msg from "gen/msg_generated";
import * as domTypes from "./dom_types";
import { TextDecoder } from "./text_encoding";
import { DenoBlob } from "./blob";
import { Headers } from "./headers";
import * as io from "./io";
import { read, close } from "./files";
import { Buffer } from "./buffer";
class Body implements domTypes.Body, domTypes.ReadableStream, io.ReadCloser {
bodyUsed = false;
private _bodyPromise: null | Promise<ArrayBuffer> = null;
private _data: ArrayBuffer | null = null;
readonly locked: boolean = false; // TODO
readonly body: null | Body = this;
constructor(private rid: number, readonly contentType: string) {}
private async _bodyBuffer(): Promise<ArrayBuffer> {
assert(this._bodyPromise == null);
const buf = new Buffer();
try {
const nread = await buf.readFrom(this);
const ui8 = buf.bytes();
assert(ui8.byteLength === nread);
this._data = ui8.buffer.slice(
ui8.byteOffset,
ui8.byteOffset + nread
) as ArrayBuffer;
assert(this._data.byteLength === nread);
} finally {
this.close();
}
return this._data;
}
async arrayBuffer(): Promise<ArrayBuffer> {
// If we've already bufferred the response, just return it.
if (this._data != null) {
return this._data;
}
// If there is no _bodyPromise yet, start it.
if (this._bodyPromise == null) {
this._bodyPromise = this._bodyBuffer();
}
return this._bodyPromise;
}
async blob(): Promise<domTypes.Blob> {
const arrayBuffer = await this.arrayBuffer();
return new DenoBlob([arrayBuffer], {
type: this.contentType
});
}
async formData(): Promise<domTypes.FormData> {
return notImplemented();
}
// tslint:disable-next-line:no-any
async json(): Promise<any> {
const text = await this.text();
return JSON.parse(text);
}
async text(): Promise<string> {
const ab = await this.arrayBuffer();
const decoder = new TextDecoder("utf-8");
return decoder.decode(ab);
}
read(p: Uint8Array): Promise<io.ReadResult> {
return read(this.rid, p);
}
close(): void {
close(this.rid);
}
async cancel(): Promise<void> {
return notImplemented();
}
getReader(): domTypes.ReadableStreamReader {
return notImplemented();
}
}
class Response implements domTypes.Response {
readonly url: string = "";
statusText = "FIXME"; // TODO
readonly type = "basic"; // TODO
redirected = false; // TODO
headers: domTypes.Headers;
readonly trailer: Promise<domTypes.Headers>;
bodyUsed = false;
readonly body: Body;
constructor(
readonly status: number,
headersList: Array<[string, string]>,
rid: number,
body_: null | Body = null
) {
this.trailer = createResolvable();
this.headers = new Headers(headersList);
const contentType = this.headers.get("content-type") || "";
if (body_ == null) {
this.body = new Body(rid, contentType);
} else {
this.body = body_;
}
}
async arrayBuffer(): Promise<ArrayBuffer> {
return this.body.arrayBuffer();
}
async blob(): Promise<domTypes.Blob> {
return this.body.blob();
}
async formData(): Promise<domTypes.FormData> {
return this.body.formData();
}
// tslint:disable-next-line:no-any
async json(): Promise<any> {
return this.body.json();
}
async text(): Promise<string> {
return this.body.text();
}
get ok(): boolean {
return 200 <= this.status && this.status < 300;
}
clone(): domTypes.Response {
if (this.bodyUsed) {
throw new TypeError(
"Failed to execute 'clone' on 'Response': Response body is already used"
);
}
const iterators = this.headers.entries();
const headersList: Array<[string, string]> = [];
for (const header of iterators) {
headersList.push(header);
}
return new Response(this.status, headersList, -1, this.body);
}
}
function msgHttpRequest(
builder: flatbuffers.Builder,
url: string,
method: null | string,
headers: null | domTypes.Headers
): flatbuffers.Offset {
const methodOffset = !method ? -1 : builder.createString(method);
let fieldsOffset: flatbuffers.Offset = -1;
const urlOffset = builder.createString(url);
if (headers) {
const kvOffsets: flatbuffers.Offset[] = [];
for (const [key, val] of headers.entries()) {
const keyOffset = builder.createString(key);
const valOffset = builder.createString(val);
msg.KeyValue.startKeyValue(builder);
msg.KeyValue.addKey(builder, keyOffset);
msg.KeyValue.addValue(builder, valOffset);
kvOffsets.push(msg.KeyValue.endKeyValue(builder));
}
fieldsOffset = msg.HttpHeader.createFieldsVector(builder, kvOffsets);
} else {
}
msg.HttpHeader.startHttpHeader(builder);
msg.HttpHeader.addIsRequest(builder, true);
msg.HttpHeader.addUrl(builder, urlOffset);
if (methodOffset >= 0) {
msg.HttpHeader.addMethod(builder, methodOffset);
}
if (fieldsOffset >= 0) {
msg.HttpHeader.addFields(builder, fieldsOffset);
}
return msg.HttpHeader.endHttpHeader(builder);
}
/** Fetch a resource from the network. */
export async function fetch(
input: domTypes.Request | string,
init?: domTypes.RequestInit
): Promise<Response> {
let url: string;
let method: string | null = null;
let headers: domTypes.Headers | null = null;
if (typeof input === "string") {
url = input;
if (init != null) {
method = init.method || null;
if (init.headers) {
headers =
init.headers instanceof Headers
? init.headers
: new Headers(init.headers);
} else {
headers = null;
}
}
} else {
url = input.url;
method = input.method;
headers = input.headers;
}
// Send Fetch message
const builder = flatbuffers.createBuilder();
const headerOff = msgHttpRequest(builder, url, method, headers);
msg.Fetch.startFetch(builder);
msg.Fetch.addHeader(builder, headerOff);
const resBase = await sendAsync(
builder,
msg.Any.Fetch,
msg.Fetch.endFetch(builder)
);
// Decode FetchRes
assert(msg.Any.FetchRes === resBase.innerType());
const inner = new msg.FetchRes();
assert(resBase.inner(inner) != null);
const header = inner.header()!;
const bodyRid = inner.bodyRid();
assert(!header.isRequest());
const status = header.status();
const headersList = deserializeHeaderFields(header);
const response = new Response(status, headersList, bodyRid);
return response;
}
function deserializeHeaderFields(m: msg.HttpHeader): Array<[string, string]> {
const out: Array<[string, string]> = [];
for (let i = 0; i < m.fieldsLength(); i++) {
const item = m.fields(i)!;
out.push([item.key()!, item.value()!]);
}
return out;
}
|