返回 CodeWhale
url_prelude.js
根目录 / crates / workflow-js / src / url_prelude.js
1 "use strict";
2 (() => {
3 const SPECIAL_PORTS = Object.freeze({
4 "http:": "80",
5 "https:": "443",
6 "ws:": "80",
7 "wss:": "443",
8 "ftp:": "21",
9 "file:": "",
10 });
11
12 const isSpecialScheme = (protocol) =>
13 Object.prototype.hasOwnProperty.call(SPECIAL_PORTS, protocol);
14
15 const defaultPort = (protocol) =>
16 isSpecialScheme(protocol) ? SPECIAL_PORTS[protocol] : "";
17
18 const stripOuterC0AndSpace = (value) =>
19 value.replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, "");
20
21 const stripTabAndNewline = (value) => value.replace(/[\t\r\n]/g, "");
22
23 const toUtf8Bytes = (str) => {
24 const bytes = [];
25 for (let i = 0; i < str.length; i++) {
26 let cp = str.charCodeAt(i);
27 if (cp >= 0xd800 && cp <= 0xdbff) {
28 if (i + 1 < str.length) {
29 const next = str.charCodeAt(i + 1);
30 if (next >= 0xdc00 && next <= 0xdfff) {
31 cp = 0x10000 + ((cp - 0xd800) << 10) + (next - 0xdc00);
32 i++;
33 } else {
34 cp = 0xfffd;
35 }
36 } else {
37 cp = 0xfffd;
38 }
39 } else if (cp >= 0xdc00 && cp <= 0xdfff) {
40 cp = 0xfffd;
41 }
42 if (cp < 0x80) {
43 bytes.push(cp);
44 } else if (cp < 0x800) {
45 bytes.push(0xc0 | (cp >> 6), 0x80 | (cp & 0x3f));
46 } else if (cp < 0x10000) {
47 bytes.push(
48 0xe0 | (cp >> 12),
49 0x80 | ((cp >> 6) & 0x3f),
50 0x80 | (cp & 0x3f)
51 );
52 } else {
53 bytes.push(
54 0xf0 | (cp >> 18),
55 0x80 | ((cp >> 12) & 0x3f),
56 0x80 | ((cp >> 6) & 0x3f),
57 0x80 | (cp & 0x3f)
58 );
59 }
60 }
61 return bytes;
62 };
63
64 const utf8BytesToString = (bytes) => {
65 let out = "";
66 let i = 0;
67 while (i < bytes.length) {
68 const b0 = bytes[i];
69 if (b0 < 0x80) {
70 out += String.fromCharCode(b0);
71 i++;
72 } else if (b0 >= 0xc2 && b0 <= 0xdf && i + 1 < bytes.length) {
73 const b1 = bytes[i + 1];
74 if ((b1 & 0xc0) === 0x80) {
75 out += String.fromCharCode(((b0 & 0x1f) << 6) | (b1 & 0x3f));
76 i += 2;
77 } else {
78 out += "\ufffd";
79 i++;
80 }
81 } else if (b0 >= 0xe0 && b0 <= 0xef && i + 2 < bytes.length) {
82 const b1 = bytes[i + 1];
83 const b2 = bytes[i + 2];
84 const lower = b0 === 0xe0 ? 0xa0 : 0x80;
85 const upper = b0 === 0xed ? 0x9f : 0xbf;
86 if (b1 >= lower && b1 <= upper && (b2 & 0xc0) === 0x80) {
87 out += String.fromCharCode(
88 ((b0 & 0x0f) << 12) | ((b1 & 0x3f) << 6) | (b2 & 0x3f)
89 );
90 i += 3;
91 } else {
92 out += "\ufffd";
93 i++;
94 }
95 } else if (b0 >= 0xf0 && b0 <= 0xf4 && i + 3 < bytes.length) {
96 const b1 = bytes[i + 1];
97 const b2 = bytes[i + 2];
98 const b3 = bytes[i + 3];
99 const lower = b0 === 0xf0 ? 0x90 : 0x80;
100 const upper = b0 === 0xf4 ? 0x8f : 0xbf;
101 if (
102 b1 >= lower &&
103 b1 <= upper &&
104 (b2 & 0xc0) === 0x80 &&
105 (b3 & 0xc0) === 0x80
106 ) {
107 const cp =
108 ((b0 & 0x07) << 18) |
109 ((b1 & 0x3f) << 12) |
110 ((b2 & 0x3f) << 6) |
111 (b3 & 0x3f);
112 const offset = cp - 0x10000;
113 out += String.fromCharCode(
114 0xd800 + (offset >> 10),
115 0xdc00 + (offset & 0x3ff)
116 );
117 i += 4;
118 } else {
119 out += "\ufffd";
120 i++;
121 }
122 } else {
123 out += "\ufffd";
124 i++;
125 }
126 }
127 return out;
128 };
129
130 const percentEncodeByte = (byte) =>
131 "%" + byte.toString(16).toUpperCase().padStart(2, "0");
132
133 const percentEncode = (str, shouldEncodeAscii) => {
134 const bytes = toUtf8Bytes(str);
135 let out = "";
136 for (let i = 0; i < bytes.length; i++) {
137 const b = bytes[i];
138 if (b < 0x80 && !shouldEncodeAscii(b)) {
139 out += String.fromCharCode(b);
140 } else {
141 out += percentEncodeByte(b);
142 }
143 }
144 return out;
145 };
146
147 const isC0OrDel = (b) => b <= 0x1f || b > 0x7e;
148
149 const isFragmentEncode = (b) =>
150 isC0OrDel(b) ||
151 b === 0x20 ||
152 b === 0x22 ||
153 b === 0x3c ||
154 b === 0x3e ||
155 b === 0x60;
156
157 const isPathEncode = (b) =>
158 isFragmentEncode(b) ||
159 b === 0x23 ||
160 b === 0x3f ||
161 b === 0x7b ||
162 b === 0x7d;
163
164 const isUserinfoEncode = (b) =>
165 isPathEncode(b) ||
166 b === 0x2f ||
167 b === 0x3a ||
168 b === 0x3b ||
169 b === 0x3d ||
170 b === 0x40 ||
171 (b >= 0x5b && b <= 0x5e) ||
172 b === 0x7c;
173
174 const encodeFragment = (str) => percentEncode(str, isFragmentEncode);
175
176 const encodeQuery = (str, special) =>
177 percentEncode(
178 str,
179 (b) =>
180 isC0OrDel(b) ||
181 b === 0x20 ||
182 b === 0x22 ||
183 b === 0x23 ||
184 b === 0x3c ||
185 b === 0x3e ||
186 (special && b === 0x27)
187 );
188
189 const encodePath = (str) => percentEncode(str, isPathEncode);
190
191 const encodeUserinfo = (str) => percentEncode(str, isUserinfoEncode);
192
193 const formEncode = (str) => {
194 const bytes = toUtf8Bytes(str);
195 let out = "";
196 for (let i = 0; i < bytes.length; i++) {
197 const b = bytes[i];
198 if (b === 0x20) {
199 out += "+";
200 } else if (
201 b === 0x2a ||
202 b === 0x2d ||
203 b === 0x2e ||
204 (b >= 0x30 && b <= 0x39) ||
205 (b >= 0x41 && b <= 0x5a) ||
206 b === 0x5f ||
207 (b >= 0x61 && b <= 0x7a)
208 ) {
209 out += String.fromCharCode(b);
210 } else {
211 out += percentEncodeByte(b);
212 }
213 }
214 return out;
215 };
216
217 const hexValue = (code) => {
218 if (code >= 0x30 && code <= 0x39) return code - 0x30;
219 if (code >= 0x41 && code <= 0x46) return code - 0x37;
220 if (code >= 0x61 && code <= 0x66) return code - 0x57;
221 return -1;
222 };
223
224 const formDecode = (str) => {
225 const spaced = str.replace(/\+/g, " ");
226 if (spaced.indexOf("%") === -1) return spaced;
227 const rawBytes = toUtf8Bytes(spaced);
228 const out = [];
229 for (let i = 0; i < rawBytes.length; i++) {
230 if (rawBytes[i] === 0x25 && i + 2 < rawBytes.length) {
231 const hi = hexValue(rawBytes[i + 1]);
232 const lo = hexValue(rawBytes[i + 2]);
233 if (hi !== -1 && lo !== -1) {
234 out.push((hi << 4) | lo);
235 i += 2;
236 continue;
237 }
238 }
239 out.push(rawBytes[i]);
240 }
241 return utf8BytesToString(out);
242 };
243
244 const parseQueryStringInto = (entries, input) => {
245 const cleaned = input.startsWith("?") ? input.slice(1) : input;
246 if (cleaned === "") return;
247 const parts = cleaned.split("&");
248 for (let i = 0; i < parts.length; i++) {
249 const part = parts[i];
250 if (part === "") continue;
251 const eq = part.indexOf("=");
252 if (eq === -1) {
253 entries.push([formDecode(part), ""]);
254 } else {
255 entries.push([formDecode(part.slice(0, eq)), formDecode(part.slice(eq + 1))]);
256 }
257 }
258 };
259
260 const serializeEntries = (entries) => {
261 if (entries.length === 0) return "";
262 const parts = new Array(entries.length);
263 for (let i = 0; i < entries.length; i++) {
264 parts[i] = formEncode(entries[i][0]) + "=" + formEncode(entries[i][1]);
265 }
266 return parts.join("&");
267 };
268
269 const normalizePathSegments = (path) => {
270 const raw = path.startsWith("/") ? path.slice(1) : path;
271 const segments = raw.split("/");
272 const out = [];
273 for (let i = 0; i < segments.length; i++) {
274 const seg = segments[i];
275 const lower = seg.toLowerCase();
276 const isLast = i === segments.length - 1;
277 if (
278 lower === ".." ||
279 lower === ".%2e" ||
280 lower === "%2e." ||
281 lower === "%2e%2e"
282 ) {
283 out.pop();
284 if (isLast) out.push("");
285 } else if (lower === "." || lower === "%2e") {
286 if (isLast) out.push("");
287 } else {
288 out.push(seg);
289 }
290 }
291 return "/" + out.join("/");
292 };
293
294 const parseIpv4Octets = (input) => {
295 const parts = input.split(".");
296 if (parts.length !== 4) return null;
297 const octets = [];
298 for (let i = 0; i < 4; i++) {
299 if (!/^\d{1,3}$/.test(parts[i])) return null;
300 if (parts[i].length > 1 && parts[i].startsWith("0")) return null;
301 const num = Number(parts[i]);
302 if (num > 255) return null;
303 octets.push(num);
304 }
305 return octets;
306 };
307
308 const parseIpv6 = (inner) => {
309 if (inner === "") {
310 throw new TypeError("Invalid URL");
311 }
312 const halves = inner.split("::");
313 if (halves.length > 2) {
314 throw new TypeError("Invalid URL");
315 }
316 const parseHalf = (half, allowIpv4) => {
317 if (half === "") return [];
318 const tokens = half.split(":");
319 const pieces = [];
320 for (let i = 0; i < tokens.length; i++) {
321 const tok = tokens[i];
322 if (tok === "") {
323 throw new TypeError("Invalid URL");
324 }
325 if (allowIpv4 && i === tokens.length - 1 && tok.indexOf(".") !== -1) {
326 const octets = parseIpv4Octets(tok);
327 if (!octets) {
328 throw new TypeError("Invalid URL");
329 }
330 pieces.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]);
331 } else {
332 if (!/^[0-9A-Fa-f]{1,4}$/.test(tok)) {
333 throw new TypeError("Invalid URL");
334 }
335 pieces.push(parseInt(tok, 16));
336 }
337 }
338 return pieces;
339 };
340 const left = parseHalf(halves[0], halves.length === 1);
341 const right = halves.length === 2 ? parseHalf(halves[1], true) : [];
342 const pieces = [];
343 if (halves.length === 2) {
344 const missing = 8 - (left.length + right.length);
345 if (missing < 1) {
346 throw new TypeError("Invalid URL");
347 }
348 for (let i = 0; i < left.length; i++) pieces.push(left[i]);
349 for (let i = 0; i < missing; i++) pieces.push(0);
350 for (let i = 0; i < right.length; i++) pieces.push(right[i]);
351 } else {
352 if (left.length !== 8) {
353 throw new TypeError("Invalid URL");
354 }
355 for (let i = 0; i < 8; i++) pieces.push(left[i]);
356 }
357
358 let bestStart = -1;
359 let bestLen = 1;
360 let curStart = -1;
361 let curLen = 0;
362 for (let i = 0; i < 8; i++) {
363 if (pieces[i] === 0) {
364 if (curStart === -1) curStart = i;
365 curLen++;
366 if (curLen > bestLen) {
367 bestStart = curStart;
368 bestLen = curLen;
369 }
370 } else {
371 curStart = -1;
372 curLen = 0;
373 }
374 }
375
376 let out = "[";
377 let skip = false;
378 for (let i = 0; i < 8; i++) {
379 if (skip) {
380 if (i < bestStart + bestLen) continue;
381 skip = false;
382 }
383 if (bestStart === i) {
384 out += i === 0 ? "::" : ":";
385 skip = true;
386 continue;
387 }
388 out += pieces[i].toString(16);
389 if (i !== 7) out += ":";
390 }
391 return out + "]";
392 };
393
394 const parsePort = (rawPort, protocol) => {
395 if (rawPort === "") return "";
396 if (!/^\d+$/.test(rawPort)) {
397 throw new TypeError("Invalid URL");
398 }
399 const num = Number(rawPort);
400 if (!Number.isSafeInteger(num) || num < 0 || num > 65535) {
401 throw new TypeError("Invalid URL");
402 }
403 const canonical = String(num);
404 return canonical === defaultPort(protocol) ? "" : canonical;
405 };
406
407 const FORBIDDEN_HOST_RE = /[\u0000-\u0020#/:<>?@[\\\]^|\u007F]/;
408
409 const parseHostAndPort = (hostPort, protocol, allowEmptyHost) => {
410 if (hostPort === "") {
411 if (allowEmptyHost) return { hostname: "", port: "" };
412 throw new TypeError("Invalid URL");
413 }
414 if (hostPort.startsWith("[")) {
415 const close = hostPort.indexOf("]");
416 if (close === -1) {
417 throw new TypeError("Invalid URL");
418 }
419 const hostname = parseIpv6(hostPort.slice(1, close));
420 const rest = hostPort.slice(close + 1);
421 if (rest === "") {
422 return { hostname, port: "" };
423 }
424 if (!rest.startsWith(":")) {
425 throw new TypeError("Invalid URL");
426 }
427 return { hostname, port: parsePort(rest.slice(1), protocol) };
428 }
429 const firstColon = hostPort.indexOf(":");
430 let rawHost = hostPort;
431 let rawPort;
432 if (firstColon !== -1) {
433 rawHost = hostPort.slice(0, firstColon);
434 rawPort = hostPort.slice(firstColon + 1);
435 if (rawPort.indexOf(":") !== -1) {
436 throw new TypeError("Invalid URL");
437 }
438 }
439 if (rawHost === "") {
440 if (allowEmptyHost && rawPort === undefined) {
441 return { hostname: "", port: "" };
442 }
443 throw new TypeError("Invalid URL");
444 }
445 if (FORBIDDEN_HOST_RE.test(rawHost)) {
446 throw new TypeError("Invalid URL");
447 }
448 const hostname = rawHost.toLowerCase();
449 const port = rawPort === undefined ? "" : parsePort(rawPort, protocol);
450 return { hostname, port };
451 };
452
453 const parseAuthority = (rawAuthority, protocol) => {
454 const at = rawAuthority.lastIndexOf("@");
455 let username = "";
456 let password = "";
457 let hostPort = rawAuthority;
458 if (at !== -1) {
459 const userinfo = rawAuthority.slice(0, at);
460 hostPort = rawAuthority.slice(at + 1);
461 const colon = userinfo.indexOf(":");
462 if (colon !== -1) {
463 username = encodeUserinfo(userinfo.slice(0, colon));
464 password = encodeUserinfo(userinfo.slice(colon + 1));
465 } else {
466 username = encodeUserinfo(userinfo);
467 }
468 }
469 const allowEmptyHost = !isSpecialScheme(protocol) || protocol === "file:";
470 const { hostname, port } = parseHostAndPort(hostPort, protocol, allowEmptyHost);
471 return { username, password, hostname, port };
472 };
473
474 const splitAtFirst = (value, needle) => {
475 const idx = value.indexOf(needle);
476 if (idx === -1) return [value, null];
477 return [value.slice(0, idx), value.slice(idx + 1)];
478 };
479
480 const SCHEME_RE = /^([A-Za-z][A-Za-z0-9+.-]*):/;
481
482 const resolveRelativePath = (basePathname, relativePath) => {
483 const lastSlash = basePathname.lastIndexOf("/");
484 const dir = lastSlash === -1 ? "/" : basePathname.slice(0, lastSlash + 1);
485 return normalizePathSegments(dir + relativePath);
486 };
487
488 const parseUrl = (inputValue, baseValue) => {
489 const raw = stripTabAndNewline(stripOuterC0AndSpace(String(inputValue)));
490 let base = null;
491 if (baseValue !== undefined) {
492 try {
493 base = parseUrl(baseValue, undefined);
494 } catch (_) {
495 throw new TypeError("Invalid base URL");
496 }
497 }
498
499 const schemeMatch = SCHEME_RE.exec(raw);
500 if (schemeMatch) {
501 const protocol = schemeMatch[1].toLowerCase() + ":";
502 const afterScheme = raw.slice(schemeMatch[0].length);
503 const [beforeHash, rawFrag] = splitAtFirst(afterScheme, "#");
504 const [beforeQuery, rawQuery] = splitAtFirst(beforeHash, "?");
505 const special = isSpecialScheme(protocol);
506 const fragment = rawFrag === null ? null : encodeFragment(rawFrag);
507 const query = rawQuery === null ? null : encodeQuery(rawQuery, special);
508
509 if (special) {
510 const slashed = beforeQuery.replace(/\\/g, "/");
511 if (base && base.protocol === protocol && !slashed.startsWith("//")) {
512 if (slashed === "") {
513 return {
514 protocol: base.protocol,
515 username: base.username,
516 password: base.password,
517 hostname: base.hostname,
518 port: base.port,
519 pathname: base.pathname,
520 query: rawQuery === null ? base.query : query,
521 fragment,
522 hasAuthority: base.hasAuthority,
523 };
524 }
525 const pathname = slashed.startsWith("/")
526 ? encodePath(normalizePathSegments(slashed))
527 : encodePath(resolveRelativePath(base.pathname, slashed));
528 return {
529 protocol: base.protocol,
530 username: base.username,
531 password: base.password,
532 hostname: base.hostname,
533 port: base.port,
534 pathname,
535 query,
536 fragment,
537 hasAuthority: base.hasAuthority,
538 };
539 }
540
541 if (protocol === "file:") {
542 let rest = slashed;
543 let hostname = "";
544 if (rest.startsWith("//")) {
545 rest = rest.slice(2);
546 const slash = rest.indexOf("/");
547 const rawHost = slash === -1 ? rest : rest.slice(0, slash);
548 const rawPath = slash === -1 ? "" : rest.slice(slash);
549 if (rawHost !== "" && rawHost.toLowerCase() !== "localhost") {
550 const parsed = parseHostAndPort(rawHost, protocol, true);
551 if (parsed.port !== "") {
552 throw new TypeError("Invalid URL");
553 }
554 hostname = parsed.hostname;
555 }
556 const pathname = encodePath(
557 normalizePathSegments(rawPath === "" ? "/" : rawPath)
558 );
559 return {
560 protocol,
561 username: "",
562 password: "",
563 hostname,
564 port: "",
565 pathname,
566 query,
567 fragment,
568 hasAuthority: true,
569 };
570 }
571 const pathname = encodePath(
572 normalizePathSegments(rest.startsWith("/") ? rest : "/" + rest)
573 );
574 return {
575 protocol,
576 username: "",
577 password: "",
578 hostname: "",
579 port: "",
580 pathname,
581 query,
582 fragment,
583 hasAuthority: true,
584 };
585 }
586
587 const stripped = slashed.replace(/^\/+/, "");
588 const slash = stripped.indexOf("/");
589 const rawAuthority = slash === -1 ? stripped : stripped.slice(0, slash);
590 const rawPath = slash === -1 ? "/" : stripped.slice(slash);
591 const auth = parseAuthority(rawAuthority, protocol);
592 const pathname = encodePath(normalizePathSegments(rawPath));
593 return {
594 protocol,
595 username: auth.username,
596 password: auth.password,
597 hostname: auth.hostname,
598 port: auth.port,
599 pathname,
600 query,
601 fragment,
602 hasAuthority: true,
603 };
604 }
605
606 if (beforeQuery.startsWith("//")) {
607 const afterSlashes = beforeQuery.slice(2);
608 const slash = afterSlashes.indexOf("/");
609 const rawAuthority = slash === -1 ? afterSlashes : afterSlashes.slice(0, slash);
610 const auth = parseAuthority(rawAuthority, protocol);
611 const pathname =
612 slash === -1
613 ? ""
614 : encodePath(normalizePathSegments(afterSlashes.slice(slash)));
615 return {
616 protocol,
617 username: auth.username,
618 password: auth.password,
619 hostname: auth.hostname,
620 port: auth.port,
621 pathname,
622 query,
623 fragment,
624 hasAuthority: true,
625 };
626 }
627
628 return {
629 protocol,
630 username: "",
631 password: "",
632 hostname: "",
633 port: "",
634 pathname: encodePath(beforeQuery),
635 query,
636 fragment,
637 hasAuthority: false,
638 };
639 }
640
641 if (!base) {
642 throw new TypeError("Invalid URL");
643 }
644
645 const [beforeHash, rawFrag] = splitAtFirst(raw, "#");
646 const fragment = rawFrag === null ? null : encodeFragment(rawFrag);
647 if (beforeHash === "") {
648 return {
649 protocol: base.protocol,
650 username: base.username,
651 password: base.password,
652 hostname: base.hostname,
653 port: base.port,
654 pathname: base.pathname,
655 query: base.query,
656 fragment,
657 hasAuthority: base.hasAuthority,
658 };
659 }
660
661 if (!base.hasAuthority) {
662 throw new TypeError("Invalid URL");
663 }
664
665 const special = isSpecialScheme(base.protocol);
666 const [rawBeforeQuery, rawQuery] = splitAtFirst(beforeHash, "?");
667 const beforeQuery = special ? rawBeforeQuery.replace(/\\/g, "/") : rawBeforeQuery;
668 const query = rawQuery === null ? null : encodeQuery(rawQuery, special);
669
670 if (beforeQuery.startsWith("//")) {
671 const rebuilt =
672 base.protocol +
673 beforeQuery +
674 (rawQuery === null ? "" : "?" + rawQuery) +
675 (rawFrag === null ? "" : "#" + rawFrag);
676 return parseUrl(rebuilt, undefined);
677 }
678
679 if (beforeQuery === "") {
680 return {
681 protocol: base.protocol,
682 username: base.username,
683 password: base.password,
684 hostname: base.hostname,
685 port: base.port,
686 pathname: base.pathname,
687 query,
688 fragment,
689 hasAuthority: true,
690 };
691 }
692
693 const pathname = beforeQuery.startsWith("/")
694 ? encodePath(normalizePathSegments(beforeQuery))
695 : encodePath(resolveRelativePath(base.pathname, beforeQuery));
696
697 return {
698 protocol: base.protocol,
699 username: base.username,
700 password: base.password,
701 hostname: base.hostname,
702 port: base.port,
703 pathname,
704 query,
705 fragment,
706 hasAuthority: true,
707 };
708 };
709
710 const formatHost = (state) =>
711 state.port === "" ? state.hostname : state.hostname + ":" + state.port;
712
713 const formatOrigin = (state) => {
714 if (
715 state.protocol === "http:" ||
716 state.protocol === "https:" ||
717 state.protocol === "ws:" ||
718 state.protocol === "wss:" ||
719 state.protocol === "ftp:"
720 ) {
721 return state.protocol + "//" + formatHost(state);
722 }
723 return "null";
724 };
725
726 const formatHref = (state) => {
727 let out = state.protocol;
728 if (state.hasAuthority) {
729 out += "//";
730 if (state.username !== "" || state.password !== "") {
731 out += state.username;
732 if (state.password !== "") {
733 out += ":" + state.password;
734 }
735 out += "@";
736 }
737 out += formatHost(state);
738 }
739 out += state.pathname;
740 if (state.query !== null) {
741 out += "?" + state.query;
742 }
743 if (state.fragment !== null) {
744 out += "#" + state.fragment;
745 }
746 return out;
747 };
748
749 const paramsState = new WeakMap();
750 const urlState = new WeakMap();
751
752 const requireParamsState = (self) => {
753 const state = paramsState.get(self);
754 if (!state) {
755 throw new TypeError("Illegal invocation");
756 }
757 return state;
758 };
759
760 const requireUrlState = (self) => {
761 const state = urlState.get(self);
762 if (!state) {
763 throw new TypeError("Illegal invocation");
764 }
765 return state;
766 };
767
768 const initSearchParams = (entries, init) => {
769 if (init === undefined || init === null) return;
770 if (typeof init === "string") {
771 parseQueryStringInto(entries, init);
772 return;
773 }
774 const existing = paramsState.get(init);
775 if (existing) {
776 for (let i = 0; i < existing.entries.length; i++) {
777 entries.push([existing.entries[i][0], existing.entries[i][1]]);
778 }
779 return;
780 }
781 if (typeof init === "object" && typeof init[Symbol.iterator] === "function") {
782 for (const pair of init) {
783 if (
784 pair === null ||
785 typeof pair !== "object" ||
786 typeof pair[Symbol.iterator] !== "function"
787 ) {
788 throw new TypeError(
789 "URLSearchParams sequence element must be an iterable pair"
790 );
791 }
792 const items = Array.from(pair);
793 if (items.length !== 2) {
794 throw new TypeError(
795 "URLSearchParams sequence element must have exactly 2 items"
796 );
797 }
798 entries.push([String(items[0]), String(items[1])]);
799 }
800 return;
801 }
802 if (typeof init === "object") {
803 const keys = Object.keys(init);
804 for (let i = 0; i < keys.length; i++) {
805 entries.push([String(keys[i]), String(init[keys[i]])]);
806 }
807 return;
808 }
809 parseQueryStringInto(entries, String(init));
810 };
811
812 class URLSearchParams {
813 constructor(init) {
814 const entries = [];
815 initSearchParams(entries, init);
816 paramsState.set(this, { entries, onUpdate: null });
817 }
818
819 get size() {
820 return requireParamsState(this).entries.length;
821 }
822
823 append(name, value) {
824 if (arguments.length < 2) {
825 throw new TypeError("URLSearchParams.append requires 2 arguments");
826 }
827 const state = requireParamsState(this);
828 state.entries.push([String(name), String(value)]);
829 if (state.onUpdate) state.onUpdate();
830 }
831
832 delete(name, value) {
833 if (arguments.length < 1) {
834 throw new TypeError("URLSearchParams.delete requires at least 1 argument");
835 }
836 const state = requireParamsState(this);
837 const key = String(name);
838 const matchValue = arguments.length >= 2 && value !== undefined;
839 const target = matchValue ? String(value) : "";
840 const next = [];
841 for (let i = 0; i < state.entries.length; i++) {
842 const pair = state.entries[i];
843 if (pair[0] === key && (!matchValue || pair[1] === target)) {
844 continue;
845 }
846 next.push(pair);
847 }
848 state.entries = next;
849 if (state.onUpdate) state.onUpdate();
850 }
851
852 get(name) {
853 if (arguments.length < 1) {
854 throw new TypeError("URLSearchParams.get requires 1 argument");
855 }
856 const state = requireParamsState(this);
857 const key = String(name);
858 for (let i = 0; i < state.entries.length; i++) {
859 if (state.entries[i][0] === key) {
860 return state.entries[i][1];
861 }
862 }
863 return null;
864 }
865
866 getAll(name) {
867 if (arguments.length < 1) {
868 throw new TypeError("URLSearchParams.getAll requires 1 argument");
869 }
870 const state = requireParamsState(this);
871 const key = String(name);
872 const values = [];
873 for (let i = 0; i < state.entries.length; i++) {
874 if (state.entries[i][0] === key) {
875 values.push(state.entries[i][1]);
876 }
877 }
878 return values;
879 }
880
881 has(name, value) {
882 if (arguments.length < 1) {
883 throw new TypeError("URLSearchParams.has requires at least 1 argument");
884 }
885 const state = requireParamsState(this);
886 const key = String(name);
887 const matchValue = arguments.length >= 2 && value !== undefined;
888 const target = matchValue ? String(value) : "";
889 for (let i = 0; i < state.entries.length; i++) {
890 const pair = state.entries[i];
891 if (pair[0] === key && (!matchValue || pair[1] === target)) {
892 return true;
893 }
894 }
895 return false;
896 }
897
898 set(name, value) {
899 if (arguments.length < 2) {
900 throw new TypeError("URLSearchParams.set requires 2 arguments");
901 }
902 const state = requireParamsState(this);
903 const key = String(name);
904 const val = String(value);
905 let replaced = false;
906 const next = [];
907 for (let i = 0; i < state.entries.length; i++) {
908 const pair = state.entries[i];
909 if (pair[0] === key) {
910 if (!replaced) {
911 next.push([key, val]);
912 replaced = true;
913 }
914 } else {
915 next.push(pair);
916 }
917 }
918 if (!replaced) {
919 next.push([key, val]);
920 }
921 state.entries = next;
922 if (state.onUpdate) state.onUpdate();
923 }
924
925 sort() {
926 const state = requireParamsState(this);
927 state.entries.sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
928 if (state.onUpdate) state.onUpdate();
929 }
930
931 entries() {
932 const state = requireParamsState(this);
933 return (function* () {
934 for (let i = 0; i < state.entries.length; i++) {
935 yield [state.entries[i][0], state.entries[i][1]];
936 }
937 })();
938 }
939
940 keys() {
941 const state = requireParamsState(this);
942 return (function* () {
943 for (let i = 0; i < state.entries.length; i++) {
944 yield state.entries[i][0];
945 }
946 })();
947 }
948
949 values() {
950 const state = requireParamsState(this);
951 return (function* () {
952 for (let i = 0; i < state.entries.length; i++) {
953 yield state.entries[i][1];
954 }
955 })();
956 }
957
958 forEach(callback, thisArg) {
959 const state = requireParamsState(this);
960 if (typeof callback !== "function") {
961 throw new TypeError("URLSearchParams.forEach callback must be a function");
962 }
963 for (let i = 0; i < state.entries.length; i++) {
964 callback.call(thisArg, state.entries[i][1], state.entries[i][0], this);
965 }
966 }
967
968 toString() {
969 return serializeEntries(requireParamsState(this).entries);
970 }
971
972 [Symbol.iterator]() {
973 return this.entries();
974 }
975 }
976
977 Object.defineProperty(URLSearchParams.prototype, Symbol.toStringTag, {
978 value: "URLSearchParams",
979 configurable: true,
980 });
981
982 const syncParamsFromQuery = (state) => {
983 const pState = paramsState.get(state.searchParams);
984 const next = [];
985 if (state.query !== null && state.query !== "") {
986 parseQueryStringInto(next, state.query);
987 }
988 pState.entries = next;
989 };
990
991 class URL {
992 constructor(input, base) {
993 if (arguments.length < 1) {
994 throw new TypeError("Failed to construct 'URL': 1 argument required");
995 }
996 const state = parseUrl(input, base);
997 const searchParams = new URLSearchParams(state.query || "");
998 const pState = paramsState.get(searchParams);
999 pState.onUpdate = () => {
1000 const serialized = serializeEntries(pState.entries);
1001 state.query = serialized === "" ? null : serialized;
1002 };
1003 state.searchParams = searchParams;
1004 urlState.set(this, state);
1005 }
1006
1007 static canParse(input, base) {
1008 if (arguments.length < 1) return false;
1009 try {
1010 parseUrl(input, base);
1011 return true;
1012 } catch (_) {
1013 return false;
1014 }
1015 }
1016
1017 static parse(input, base) {
1018 if (arguments.length < 1) return null;
1019 try {
1020 return new URL(input, base);
1021 } catch (_) {
1022 return null;
1023 }
1024 }
1025
1026 get href() {
1027 return formatHref(requireUrlState(this));
1028 }
1029
1030 set href(value) {
1031 const state = requireUrlState(this);
1032 const parsed = parseUrl(value, undefined);
1033 state.protocol = parsed.protocol;
1034 state.username = parsed.username;
1035 state.password = parsed.password;
1036 state.hostname = parsed.hostname;
1037 state.port = parsed.port;
1038 state.pathname = parsed.pathname;
1039 state.query = parsed.query;
1040 state.fragment = parsed.fragment;
1041 state.hasAuthority = parsed.hasAuthority;
1042 syncParamsFromQuery(state);
1043 }
1044
1045 get origin() {
1046 return formatOrigin(requireUrlState(this));
1047 }
1048
1049 get protocol() {
1050 return requireUrlState(this).protocol;
1051 }
1052
1053 set protocol(value) {
1054 const state = requireUrlState(this);
1055 const raw = stripTabAndNewline(String(value));
1056 const match = /^([A-Za-z][A-Za-z0-9+.-]*)(?::|$)/.exec(raw);
1057 if (!match) return;
1058 const nextProtocol = match[1].toLowerCase() + ":";
1059 if (isSpecialScheme(state.protocol) !== isSpecialScheme(nextProtocol)) {
1060 return;
1061 }
1062 if (
1063 (state.protocol === "file:" || nextProtocol === "file:") &&
1064 state.protocol !== nextProtocol
1065 ) {
1066 return;
1067 }
1068 state.protocol = nextProtocol;
1069 if (state.port !== "" && state.port === defaultPort(nextProtocol)) {
1070 state.port = "";
1071 }
1072 }
1073
1074 get username() {
1075 return requireUrlState(this).username;
1076 }
1077
1078 set username(value) {
1079 const state = requireUrlState(this);
1080 if (!state.hasAuthority || state.hostname === "" || state.protocol === "file:") {
1081 return;
1082 }
1083 state.username = encodeUserinfo(String(value));
1084 }
1085
1086 get password() {
1087 return requireUrlState(this).password;
1088 }
1089
1090 set password(value) {
1091 const state = requireUrlState(this);
1092 if (!state.hasAuthority || state.hostname === "" || state.protocol === "file:") {
1093 return;
1094 }
1095 state.password = encodeUserinfo(String(value));
1096 }
1097
1098 get host() {
1099 return formatHost(requireUrlState(this));
1100 }
1101
1102 set host(value) {
1103 const state = requireUrlState(this);
1104 if (!state.hasAuthority) return;
1105 const raw = stripTabAndNewline(String(value));
1106 try {
1107 const allowEmpty = !isSpecialScheme(state.protocol) || state.protocol === "file:";
1108 const parsed = parseHostAndPort(raw, state.protocol, allowEmpty);
1109 if (state.protocol === "file:" && parsed.port !== "") return;
1110 state.hostname = parsed.hostname;
1111 const portGiven = raw.startsWith("[")
1112 ? raw.slice(raw.indexOf("]") + 1).startsWith(":")
1113 : raw.indexOf(":") !== -1;
1114 if (portGiven) state.port = parsed.port;
1115 } catch (_) {}
1116 }
1117
1118 get hostname() {
1119 return requireUrlState(this).hostname;
1120 }
1121
1122 set hostname(value) {
1123 const state = requireUrlState(this);
1124 if (!state.hasAuthority) return;
1125 const raw = stripTabAndNewline(String(value));
1126 if (!raw.startsWith("[") && raw.indexOf(":") !== -1) return;
1127 try {
1128 const allowEmpty = !isSpecialScheme(state.protocol) || state.protocol === "file:";
1129 const parsed = parseHostAndPort(raw, state.protocol, allowEmpty);
1130 if (parsed.port !== "") return;
1131 state.hostname = parsed.hostname;
1132 } catch (_) {}
1133 }
1134
1135 get port() {
1136 return requireUrlState(this).port;
1137 }
1138
1139 set port(value) {
1140 const state = requireUrlState(this);
1141 if (!state.hasAuthority || state.hostname === "" || state.protocol === "file:") {
1142 return;
1143 }
1144 const raw = stripTabAndNewline(String(value));
1145 if (raw === "") {
1146 state.port = "";
1147 return;
1148 }
1149 try {
1150 state.port = parsePort(raw, state.protocol);
1151 } catch (_) {}
1152 }
1153
1154 get pathname() {
1155 return requireUrlState(this).pathname;
1156 }
1157
1158 set pathname(value) {
1159 const state = requireUrlState(this);
1160 if (!state.hasAuthority) return;
1161 let raw = stripTabAndNewline(String(value));
1162 if (isSpecialScheme(state.protocol)) {
1163 raw = raw.replace(/\\/g, "/");
1164 if (!raw.startsWith("/")) raw = "/" + raw;
1165 state.pathname = encodePath(normalizePathSegments(raw));
1166 } else {
1167 if (raw === "") {
1168 state.pathname = "";
1169 } else {
1170 if (!raw.startsWith("/")) raw = "/" + raw;
1171 state.pathname = encodePath(normalizePathSegments(raw));
1172 }
1173 }
1174 }
1175
1176 get search() {
1177 const query = requireUrlState(this).query;
1178 return query ? "?" + query : "";
1179 }
1180
1181 set search(value) {
1182 const state = requireUrlState(this);
1183 const raw = stripTabAndNewline(String(value));
1184 if (raw === "") {
1185 state.query = null;
1186 } else {
1187 const stripped = raw.startsWith("?") ? raw.slice(1) : raw;
1188 state.query = encodeQuery(stripped, isSpecialScheme(state.protocol));
1189 }
1190 syncParamsFromQuery(state);
1191 }
1192
1193 get searchParams() {
1194 return requireUrlState(this).searchParams;
1195 }
1196
1197 get hash() {
1198 const fragment = requireUrlState(this).fragment;
1199 return fragment ? "#" + fragment : "";
1200 }
1201
1202 set hash(value) {
1203 const state = requireUrlState(this);
1204 const raw = stripTabAndNewline(String(value));
1205 if (raw === "") {
1206 state.fragment = null;
1207 } else {
1208 const stripped = raw.startsWith("#") ? raw.slice(1) : raw;
1209 state.fragment = encodeFragment(stripped);
1210 }
1211 }
1212
1213 toString() {
1214 return this.href;
1215 }
1216
1217 toJSON() {
1218 return this.href;
1219 }
1220 }
1221
1222 Object.defineProperty(URL.prototype, Symbol.toStringTag, {
1223 value: "URL",
1224 configurable: true,
1225 });
1226
1227 globalThis.URLSearchParams = URLSearchParams;
1228 globalThis.URL = URL;
1229 })();
1230
1230 lines JAVASCRIPT