Repository navigation
Expand file tree
/
Copy pathurl.ts
More file actions
280 lines (268 loc) · 9.58 KB
/
Copy pathurl.ts
File metadata and controls
280 lines (268 loc) · 9.58 KB
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
import type { Eval } from "../interpreter/runner.js"
import { constructor, fn, type Method, methods, prototypeFrom, receiver, requiresNew } from "../interpreter/native.js"
import { IteratorSymbol, PendingThrow, typeError, uriError } from "../interpreter/model.js"
import {
define,
defineAccessor,
entries,
get,
hidden,
Arr,
hostIterator,
Obj,
URLObj,
URLSearchParamsObj,
coerceToString,
isRuntimeReference,
type Value,
} from "../interpreter/objects.js"
import { applyCollectionCallback, preserveConsumerError } from "../interpreter/callback.js"
import type { Interpreter } from "../interpreter/interpreter.js"
const urlProperties = [
"href",
"origin",
"protocol",
"username",
"password",
"host",
"hostname",
"port",
"pathname",
"search",
"hash",
] as const
type UriFunction = "encodeURI" | "encodeURIComponent" | "decodeURI" | "decodeURIComponent"
const uriFunctions: Record<UriFunction, (value: string) => string> = {
encodeURI,
encodeURIComponent,
decodeURI,
decodeURIComponent,
}
export const uriGlobal = <R>(ctx: Interpreter<R>, name: UriFunction) =>
fn(ctx.builtins, name, 1, (_, args) => {
const value = coerceToString(args[0])
try {
return uriFunctions[name](value)
} catch (error) {
throw uriError(`${name} received malformed URI data: ${error instanceof Error ? error.message : String(error)}`)
}
})
const urlArgument = (value: Value): string => (value instanceof URLObj ? value.url.href : coerceToString(value))
export const urlGlobal = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.URL
const construct = (args: Array<Value>, into: Obj): URLObj => {
if (args.length === 0) {
throw typeError("new URL(...) requires a URL string and an optional base URL.")
}
const input = urlArgument(args[0])
const base = args[1] === undefined ? undefined : urlArgument(args[1])
try {
return new URLObj(into, builtins.URLSearchParams, new URL(input, base))
} catch {
throw typeError(`new URL(...) received an invalid URL${base === undefined ? "" : " or base URL"}.`)
}
}
const url = constructor(builtins, proto, {
name: "URL",
length: 1,
call: requiresNew("URL"),
construct: (args, newTarget) => construct(args, prototypeFrom(newTarget, proto)),
})
const parse = (name: "canParse" | "parse"): Method => [
name,
1,
(_, args) => {
if (args.length === 0) throw typeError(`URL.${name} requires a URL argument.`)
const input = urlArgument(args[0])
const base = args[1] === undefined ? undefined : urlArgument(args[1])
try {
const parsed = new URL(input, base)
return name === "canParse" ? true : new URLObj(proto, builtins.URLSearchParams, parsed)
} catch {
return name === "canParse" ? false : null
}
},
]
methods(builtins, url, [parse("canParse"), parse("parse")])
const self = (thisValue: Value, name: string) => receiver(URLObj, thisValue, `URL.prototype.${name}`)
for (const name of urlProperties) {
defineAccessor(
proto,
name,
(thisValue) => self(thisValue, name).url[name],
name === "origin"
? undefined
: (thisValue, value) => {
const target = self(thisValue, name)
try {
target.url[name] = coerceToString(value)
} catch (error) {
if (error instanceof PendingThrow) throw error
throw typeError(`URL.${name} received an invalid value.`)
}
},
)
}
defineAccessor(proto, "searchParams", (thisValue) => self(thisValue, "searchParams").searchParams)
methods(builtins, proto, [
["toString", 0, (thisValue) => self(thisValue, "toString").url.href],
["toJSON", 0, (thisValue) => self(thisValue, "toJSON").url.href],
])
return url
}
function* readPair<R>(ctx: Interpreter<R>, value: Value, label: string): Eval<Array<string>> {
const cursor = yield* ctx.iterate(value)
if (cursor === undefined) throw typeError(`${label} expects iterable [name, value] pairs.`)
const items: Array<string> = []
while (true) {
const step = yield* cursor.next()
if (step.done) return items
items.push(yield* preserveConsumerError(cursor.close, pairString(step.value)))
}
}
// A step, so a failing conversion closes the pair's iterator.
function* pairString(value: Value): Eval<string> {
return coerceToString(value)
}
/**
* Reads a synchronous iterable of `[name, value]` pairs as strings; `undefined` when `init` is not iterable. As in
* WebIDL, the whole sequence is converted before any pair's length is checked.
*/
export function* readPairs<R>(
ctx: Interpreter<R>,
init: Value,
label: string,
): Eval<Array<[string, string]> | undefined> {
const cursor = yield* ctx.iterate(init)
if (cursor === undefined) return undefined
const pairs: Array<Array<string>> = []
while (true) {
const step = yield* cursor.next()
if (step.done) {
if (pairs.some((entry) => entry.length !== 2)) throw typeError(`${label} expects iterable [name, value] pairs.`)
return pairs as Array<[string, string]>
}
pairs.push(yield* preserveConsumerError(cursor.close, readPair(ctx, step.value, label)))
}
}
function* constructURLSearchParams<R>(ctx: Interpreter<R>, init: Value, proto: Obj): Eval<URLSearchParamsObj> {
const wrap = (params: URLSearchParams) => new URLSearchParamsObj(proto, params)
if (init === undefined) return wrap(new URLSearchParams())
if (init instanceof URLSearchParamsObj) return wrap(new URLSearchParams(init.params))
if (typeof init === "string") return wrap(new URLSearchParams(init))
if (init === null || typeof init === "number" || typeof init === "boolean") {
return wrap(new URLSearchParams(coerceToString(init)))
}
const pairs = yield* readPairs(ctx, init, "new URLSearchParams(...)")
if (pairs !== undefined) return wrap(new URLSearchParams(pairs))
if (isRuntimeReference(init)) {
throw typeError("new URLSearchParams(...) expects a query string, data object, or synchronous iterable pairs.")
}
if (!(init instanceof Obj)) {
throw typeError("new URLSearchParams(...) expects a query string, data object, iterable pairs, or URLSearchParams.")
}
return wrap(
new URLSearchParams(Object.fromEntries(entries(init).map(([key, value]) => [key, coerceToString(value)]))),
)
}
export const urlSearchParamsGlobal = <R>(ctx: Interpreter<R>) => {
const builtins = ctx.builtins
const proto = builtins.URLSearchParams
const searchParams = constructor(builtins, proto, {
name: "URLSearchParams",
call: requiresNew("URLSearchParams"),
construct: (args, newTarget) => constructURLSearchParams(ctx, args[0], prototypeFrom(newTarget, proto)),
})
const self = (thisValue: Value, name: string) =>
receiver(URLSearchParamsObj, thisValue, `URLSearchParams.prototype.${name}`)
const wrap = (items: Array<Value>) => new Arr(builtins.Array, items)
const arg = (args: Array<Value>, index: number): string => coerceToString(args[index])
const requireArgs = (name: string, args: Array<Value>, count: number): void => {
if (args.length < count) {
throw typeError(`URLSearchParams.${name} requires ${count} argument${count === 1 ? "" : "s"}.`)
}
}
defineAccessor(proto, "size", (thisValue) => self(thisValue, "size").params.size)
methods(builtins, proto, [
[
"append",
2,
(thisValue, args) => {
requireArgs("append", args, 2)
self(thisValue, "append").params.append(arg(args, 0), arg(args, 1))
return undefined
},
],
[
"delete",
1,
(thisValue, args) => {
requireArgs("delete", args, 1)
const params = self(thisValue, "delete").params
if (args[1] !== undefined) params.delete(arg(args, 0), arg(args, 1))
else params.delete(arg(args, 0))
return undefined
},
],
[
"get",
1,
(thisValue, args) => {
requireArgs("get", args, 1)
return self(thisValue, "get").params.get(arg(args, 0))
},
],
[
"getAll",
1,
(thisValue, args) => {
requireArgs("getAll", args, 1)
return wrap(self(thisValue, "getAll").params.getAll(arg(args, 0)))
},
],
[
"has",
1,
(thisValue, args) => {
requireArgs("has", args, 1)
const params = self(thisValue, "has").params
return args[1] !== undefined ? params.has(arg(args, 0), arg(args, 1)) : params.has(arg(args, 0))
},
],
[
"set",
2,
(thisValue, args) => {
requireArgs("set", args, 2)
self(thisValue, "set").params.set(arg(args, 0), arg(args, 1))
return undefined
},
],
[
"sort",
0,
(thisValue) => {
self(thisValue, "sort").params.sort()
return undefined
},
],
["keys", 0, (thisValue) => hostIterator(builtins, self(thisValue, "keys").params.keys())],
["values", 0, (thisValue) => hostIterator(builtins, self(thisValue, "values").params.values())],
["entries", 0, (thisValue) => hostIterator(builtins, self(thisValue, "entries").iterator(builtins))],
["toString", 0, (thisValue) => self(thisValue, "toString").params.toString()],
[
"forEach",
1,
function* (thisValue, args) {
requireArgs("forEach", args, 1)
const target = self(thisValue, "forEach")
const apply = applyCollectionCallback(ctx, args[0], "URLSearchParams.forEach")
for (const [key, value] of Array.from(target.params.entries())) yield* apply([value, key, target], args[1])
return undefined
},
],
])
define(proto, IteratorSymbol, get(proto, "entries"), hidden)
return searchParams
}